1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
|
//! Low-level IPC mechanism for Sequoia.
//!
//! # Rationale
//!
//! Sequoia makes use of background services e.g. for managing and
//! updating public keys.
//!
//! # Design
//!
//! We use the filesystem as namespace to discover services. Every
//! service has a file called rendezvous point. Access to this file
//! is serialized using file locking. This file contains a socket
//! address and a cookie that we use to connect to the server and
//! authenticate us. If the file does not exist, is malformed, or
//! does not point to a usable server, we start a new one on demand.
//!
//! This design mimics Unix sockets, but works on Windows too.
//!
//! # External vs internal servers
//!
//! These servers can be either in external processes, or co-located
//! within the current process. In either case, other processes may
//! connect to the server.
//!
//! # Note
//!
//! Windows support is currently not implemented, but should be
//! straight forward.
extern crate fs2;
use self::fs2::FileExt;
use std::fs;
use std::io::{self, Read, Write};
use std::net::{SocketAddr, AddrParseError, TcpStream, TcpListener};
use std::path::PathBuf;
use futures::{Future, Stream};
use tokio_core::{self, net};
use tokio_io;
use tokio_io::io::{ReadHalf, ReadExact};
use tokio_io::AsyncRead;
use capnp_rpc::{RpcSystem, twoparty};
use capnp_rpc::rpc_twoparty_capnp::Side;
/* Unix-specific options. */
use std::os::unix::io::FromRawFd;
use std::os::unix::fs::OpenOptionsExt;
/* XXX: Implement Windows support. */
use std::process::{Command, Stdio};
use std::os::unix::io::AsRawFd;
use std::thread;
/// Servers need to implement this trait.
pub trait Handler {
/// Called on every connection.
fn handle(&self,
network: twoparty::VatNetwork<ReadHalf<net::TcpStream>>)
-> RpcSystem<Side>;
}
/// A factory for handlers.
pub type HandlerFactory = fn(descriptor: Descriptor,
handle: tokio_core::reactor::Handle) -> Option<Box<Handler>>;
/// A descriptor is used to connect to a service.
#[derive(Clone)]
pub struct Descriptor {
pub home: PathBuf,
pub rendezvous: PathBuf,
executable: PathBuf,
factory: HandlerFactory,
}
const LOCALHOST: &str = "127.0.0.1";
impl Descriptor {
/// Create a descriptor given its rendezvous point, the path to
/// the servers executable file, and a handler factory.
pub fn new(home: PathBuf, rendezvous: PathBuf, executable: PathBuf, factory: HandlerFactory)
-> Self {
Descriptor {
home: home,
rendezvous: rendezvous,
executable: executable,
factory: factory,
}
}
/// Connect to a descriptor, starting the server if necessary.
pub fn connect(&self, handle: &tokio_core::reactor::Handle) -> io::Result<RpcSystem<Side>> {
let mut file = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.mode(0o600)
.open(&self.rendezvous)?;
file.lock_exclusive()?;
let mut c = vec![];
file.read_to_end(&mut c)?;
if let Some((cookie, a)) = Cookie::extract(c) {
let addr: Result<SocketAddr, AddrParseError> = String::from_utf8_lossy(&a).parse();
if addr.is_err() {
/* Malformed. Invalidate the cookie and try again. */
file.set_len(0)?;
drop(file);
return self.connect(handle);
}
let stream = TcpStream::connect(addr.unwrap());
if let Ok(mut s) = stream {
cookie.send(&mut s)?;
/* Tokioize. */
let stream = net::TcpStream::from_stream(s, &handle)?;
stream.set_nodelay(true)?;
let (reader, writer) = stream.split();
let network =
Box::new(twoparty::VatNetwork::new(reader, writer,
Side::Client,
Default::default()));
let rpc_system = RpcSystem::new(network, None);
Ok(rpc_system)
} else {
/* Failed to connect. Invalidate the cookie and try again. */
file.set_len(0)?;
drop(file);
self.connect(handle)
}
} else {
let cookie = Cookie::new()?;
let addr = self.start(true).or(self.start(false))?;
let mut stream = TcpStream::connect(addr)?;
cookie.send(&mut stream)?;
/* XXX: It'd be nice not to waste this connection. */
drop(stream);
/* Write connection information to file. */
file.set_len(0)?;
cookie.send(&mut file)?;
write!(file, "{}:{}", LOCALHOST, addr.port())?;
drop(file);
self.connect(handle)
}
}
/// Try to create a TCP socket, bind it to a random port on
/// localhost.
fn listen(&self) -> io::Result<TcpListener> {
let port = OsRng::new()?.next_u32() as u16;
TcpListener::bind((LOCALHOST, port))
}
/// Start the service, either as an external process or as a
/// thread.
fn start(&self, external: bool) -> io::Result<SocketAddr> {
/* Listen on a random port on localhost. */
let mut listener = self.listen();
while listener.is_err() {
listener = self.listen();
}
let listener = listener.unwrap();
let addr = listener.local_addr()?;
/* Start the server, connect to it, and send the cookie. */
if external {
self.fork(listener)?;
} else {
self.spawn(listener)?;
}
Ok(addr)
}
fn fork(&self, l: TcpListener) -> io::Result<()> {
// Convert to raw fd, then forget l so that it will not be
// closed when it is dropped.
let fd = l.as_raw_fd();
::std::mem::forget(l);
Command::new(&self.executable.clone().into_os_string())
// l will be closed here if the exec fails.
.stdin(unsafe { Stdio::from_raw_fd(fd) })
.spawn()?;
Ok(())
}
fn spawn(&self, l: TcpListener) -> io::Result<()> {
let descriptor = self.clone();
thread::spawn(move || -> io::Result<()> {
Ok(Server::new(descriptor)
.expect("Failed to spawn server") // XXX
.serve_listener(l)
.expect(
|