Skip to main content

link_cli/protocol/ipc/
mod.rs

1//! Interchangeable inter-process communication transports (issue #140).
2//!
3//! The LiNo text and binary protocols need a reliable, ordered, duplex byte
4//! stream. This module turns every IPC mechanism of the operating system into
5//! such a stream, an [`IpcStream`], chosen by an endpoint string, so the
6//! mechanism is a decorator layer under the protocol: a [`LinksServer`]
7//! listens and a [`LinksClient`] connects through any of them, a server can
8//! listen on several at once and [`forward`] stacks them.
9//!
10//! | Endpoint | Mechanism |
11//! | --- | --- |
12//! | `host:port`, `tcp:host:port` | TCP/IP |
13//! | `udp:host:port` | UDP datagrams with a reliable session |
14//! | `unix:PATH`, `unix:@NAME` | Unix domain stream socket |
15//! | `pipe:NAME` | Windows named pipe; on POSIX the same as `fifo` |
16//! | `fifo:DIR` | two POSIX named pipes |
17//! | `stdio`, `exec:COMMAND` | anonymous pipes of standard input/output |
18//! | `shm:DIR`, `mmap:DIR`, `file:DIR` | shared memory, memory-mapped file, file on disk |
19//! | `signal:DIR` | memory-mapped ring announced by OS signals (Windows: events) |
20//! | `mq:DIR`, `sysvmq:DIR` | POSIX and System V message queues |
21//! | `mailslot:DIR`, `copydata:DIR`, `alpc:DIR` | Windows mailslots, `WM_COPYDATA`, ALPC |
22//!
23//! The wire format of every kind is specified in
24//! `docs/protocol/ipc-transports-v1.md`; the C# and JavaScript
25//! implementations follow the same document, so any of them talks to any
26//! other.
27//!
28//! ```
29//! use link_cli::protocol::ipc::Endpoint;
30//!
31//! let endpoint = Endpoint::parse("shm:/tmp/links?capacity=1048576").unwrap();
32//! assert_eq!(endpoint.kind(), "shm");
33//! assert_eq!(endpoint.address(), "/tmp/links");
34//! assert_eq!(Endpoint::parse("127.0.0.1:8080").unwrap().kind(), "tcp");
35//! ```
36//!
37//! [`LinksServer`]: super::LinksServer
38//! [`LinksClient`]: super::LinksClient
39
40mod datagram;
41mod endpoint;
42mod json;
43mod net;
44mod rendezvous;
45mod ring;
46mod stdio;
47#[cfg(unix)]
48mod unix;
49#[cfg(windows)]
50mod windows;
51
52pub use endpoint::Endpoint;
53
54use std::collections::BTreeMap;
55use std::fmt;
56use std::io::{self, Read, Write};
57use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
58use std::sync::mpsc;
59use std::sync::{Arc, Mutex, OnceLock};
60use std::thread;
61use std::time::Duration;
62
63/// Every built-in endpoint kind, in documentation order.
64pub const KINDS: &[&str] = &[
65    "tcp", "udp", "unix", "pipe", "fifo", "stdio", "exec", "shm", "mmap", "file", "signal", "mq",
66    "sysvmq", "mailslot", "copydata", "alpc",
67];
68
69/// One side of a duplex byte channel.
70///
71/// Reading and writing may happen on two threads at once, and
72/// [`shutdown`](Self::shutdown) may come from a third one.
73pub trait Transport: Send + Sync + fmt::Debug {
74    /// Reads at least one byte, waiting up to `timeout` (`None`: forever).
75    /// `Ok(0)` is the end of the incoming direction; a timeout is
76    /// [`io::ErrorKind::TimedOut`].
77    fn read(&self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<usize>;
78    /// Writes at least one byte of `buf`.
79    fn write(&self, buf: &[u8]) -> io::Result<usize>;
80    /// Pushes buffered bytes to the peer.
81    fn flush(&self) -> io::Result<()> {
82        Ok(())
83    }
84    /// Ends the outgoing direction; the peer reads the end of the stream.
85    fn close_write(&self) -> io::Result<()>;
86    /// Hangs up both directions; pending and later operations end.
87    fn shutdown(&self);
88    /// The endpoint kind, such as `shm`.
89    fn kind(&self) -> &'static str;
90}
91
92/// A cloneable duplex byte stream over any [`Transport`].
93///
94/// Clones share the channel, so one thread can read while another writes.
95#[derive(Clone)]
96pub struct IpcStream {
97    inner: Arc<dyn Transport>,
98    read_timeout: Option<Duration>,
99}
100
101impl fmt::Debug for IpcStream {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        formatter
104            .debug_struct("IpcStream")
105            .field("transport", &self.inner)
106            .field("read_timeout", &self.read_timeout)
107            .finish()
108    }
109}
110
111impl IpcStream {
112    /// Wraps a transport.
113    pub fn new(transport: impl Transport + 'static) -> Self {
114        Self::from_arc(Arc::new(transport))
115    }
116
117    /// Wraps a shared transport.
118    pub fn from_arc(transport: Arc<dyn Transport>) -> Self {
119        Self {
120            inner: transport,
121            read_timeout: None,
122        }
123    }
124
125    /// The endpoint kind of the transport.
126    pub fn kind(&self) -> &'static str {
127        self.inner.kind()
128    }
129
130    /// The transport.
131    pub fn transport(&self) -> &Arc<dyn Transport> {
132        &self.inner
133    }
134
135    /// Makes reads of this handle fail with [`io::ErrorKind::TimedOut`]
136    /// after `timeout`; `None` waits forever.
137    pub fn set_read_timeout(&mut self, timeout: Option<Duration>) {
138        self.read_timeout = timeout;
139    }
140
141    /// The read timeout of this handle.
142    pub fn read_timeout(&self) -> Option<Duration> {
143        self.read_timeout
144    }
145
146    /// Ends the outgoing direction.
147    pub fn close_write(&self) -> io::Result<()> {
148        self.inner.close_write()
149    }
150
151    /// Hangs up both directions.
152    pub fn shutdown(&self) {
153        self.inner.shutdown()
154    }
155}
156
157impl Read for IpcStream {
158    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
159        if buf.is_empty() {
160            return Ok(0);
161        }
162        loop {
163            match self.inner.read(buf, self.read_timeout) {
164                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
165                result => return result,
166            }
167        }
168    }
169}
170
171impl Write for IpcStream {
172    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
173        if buf.is_empty() {
174            return Ok(0);
175        }
176        loop {
177            match self.inner.write(buf) {
178                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
179                result => return result,
180            }
181        }
182    }
183
184    fn flush(&mut self) -> io::Result<()> {
185        self.inner.flush()
186    }
187}
188
189/// Wakes a blocked [`Listener::accept`] so it notices that it was closed.
190pub type Waker = Arc<dyn Fn() + Send + Sync>;
191
192/// Accepts [`IpcStream`]s on one endpoint.
193pub trait Listener: Send + fmt::Debug {
194    /// Waits for the next connection; `Ok(None)` when the listener was closed
195    /// or can never accept another one (a `stdio` listener after its single
196    /// connection ended).
197    fn accept(&mut self) -> io::Result<Option<IpcStream>>;
198    /// The endpoint clients connect to, such as `shm:/tmp/links` or, for TCP,
199    /// the bound `host:port`.
200    fn endpoint(&self) -> String;
201    /// Every endpoint clients connect to: one, except for a
202    /// [`MultiListener`].
203    fn endpoints(&self) -> Vec<String> {
204        vec![self.endpoint()]
205    }
206    /// The bound TCP address, for TCP listeners.
207    fn local_addr(&self) -> Option<std::net::SocketAddr> {
208        None
209    }
210    /// A function that closes the listener from any thread: the blocked or
211    /// next [`accept`](Self::accept) returns `Ok(None)`.
212    fn closer(&self) -> Waker;
213}
214
215/// Connects to `endpoint` (see [`Endpoint`]).
216pub fn connect(endpoint: &str) -> io::Result<IpcStream> {
217    connect_endpoint(&Endpoint::parse(endpoint)?)
218}
219
220/// Connects to a parsed endpoint.
221pub fn connect_endpoint(endpoint: &Endpoint) -> io::Result<IpcStream> {
222    trace!("connect {endpoint}");
223    let stream = match registered(endpoint.kind()) {
224        Some(Registered {
225            connect: Some(connect),
226            ..
227        }) => connect(endpoint),
228        Some(_) => Err(unsupported(endpoint.kind(), "connecting")),
229        None => builtin_connect(endpoint),
230    };
231    match &stream {
232        Ok(_) => trace!("connected {endpoint}"),
233        Err(error) => trace!("connect {endpoint} failed: {error}"),
234    }
235    stream
236}
237
238/// Listens on `endpoint` (see [`Endpoint`]).
239pub fn listen(endpoint: &str) -> io::Result<Box<dyn Listener>> {
240    listen_endpoint(&Endpoint::parse(endpoint)?)
241}
242
243/// Listens on a parsed endpoint.
244pub fn listen_endpoint(endpoint: &Endpoint) -> io::Result<Box<dyn Listener>> {
245    let listener = match registered(endpoint.kind()) {
246        Some(Registered {
247            listen: Some(listen),
248            ..
249        }) => listen(endpoint),
250        Some(_) => Err(unsupported(endpoint.kind(), "listening")),
251        None => builtin_listen(endpoint),
252    }?;
253    trace!("listening on {}", listener.endpoint());
254    Ok(listener)
255}
256
257/// Wraps a connected TCP stream (Nagle's algorithm is turned off).
258pub fn from_tcp_stream(stream: std::net::TcpStream) -> IpcStream {
259    net::tcp_stream(stream)
260}
261
262/// Wraps an already bound TCP listener.
263pub fn from_tcp_listener(listener: std::net::TcpListener) -> io::Result<Box<dyn Listener>> {
264    Ok(Box::new(net::TcpIpcListener::new(listener)?))
265}
266
267/// Listens on every endpoint at once; one listener is returned as it is.
268pub fn listen_all<S: AsRef<str>>(endpoints: &[S]) -> io::Result<Box<dyn Listener>> {
269    let mut listeners = Vec::with_capacity(endpoints.len());
270    for endpoint in endpoints {
271        listeners.push(listen(endpoint.as_ref())?);
272    }
273    match listeners.len() {
274        0 => Err(io::Error::new(
275            io::ErrorKind::InvalidInput,
276            "no endpoint to listen on",
277        )),
278        1 => Ok(listeners.pop().expect("one listener")),
279        _ => Ok(Box::new(MultiListener::new(listeners))),
280    }
281}
282
283/// Whether this build can connect to (`listen == false`) or listen on the
284/// kind on the current platform.
285pub fn supports(kind: &str, listen: bool) -> bool {
286    if let Some(registered) = registered(kind) {
287        return if listen {
288            registered.listen.is_some()
289        } else {
290            registered.connect.is_some()
291        };
292    }
293    let kind = kind.to_ascii_lowercase();
294    match kind.as_str() {
295        "tcp" | "udp" | "mmap" | "file" | "shm" | "signal" | "pipe" => cfg!(any(unix, windows)),
296        "stdio" => listen,
297        "exec" => !listen,
298        "unix" => cfg!(any(unix, windows)),
299        "fifo" => cfg!(unix),
300        "sysvmq" => cfg!(any(target_os = "linux", target_vendor = "apple")),
301        "mq" => cfg!(target_os = "linux"),
302        "mailslot" | "copydata" => cfg!(windows),
303        "alpc" => cfg!(all(windows, target_pointer_width = "64")),
304        _ => false,
305    }
306}
307
308/// Opens an outgoing connection of a custom kind.
309pub type ConnectFn = Arc<dyn Fn(&Endpoint) -> io::Result<IpcStream> + Send + Sync>;
310/// Opens a listener of a custom kind.
311pub type ListenFn = Arc<dyn Fn(&Endpoint) -> io::Result<Box<dyn Listener>> + Send + Sync>;
312
313#[derive(Clone)]
314struct Registered {
315    connect: Option<ConnectFn>,
316    listen: Option<ListenFn>,
317}
318
319fn registry() -> &'static Mutex<BTreeMap<String, Registered>> {
320    static REGISTRY: OnceLock<Mutex<BTreeMap<String, Registered>>> = OnceLock::new();
321    REGISTRY.get_or_init(|| Mutex::new(BTreeMap::new()))
322}
323
324fn registered(kind: &str) -> Option<Registered> {
325    registry()
326        .lock()
327        .unwrap_or_else(|poisoned| poisoned.into_inner())
328        .get(&kind.to_ascii_lowercase())
329        .cloned()
330}
331
332/// Whether `kind` was added with [`register`].
333pub(crate) fn is_registered(kind: &str) -> bool {
334    registered(kind).is_some()
335}
336
337/// Adds a custom endpoint kind, such as a transport over a device driver.
338///
339/// `kind` is lowercase ASCII letters, digits and `-`; built-in kinds cannot
340/// be replaced, and registering a kind again replaces the earlier one.
341pub fn register(
342    kind: &str,
343    connect: Option<ConnectFn>,
344    listen: Option<ListenFn>,
345) -> io::Result<()> {
346    let kind = kind.to_ascii_lowercase();
347    if kind.is_empty()
348        || !kind
349            .bytes()
350            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
351    {
352        return Err(io::Error::new(
353            io::ErrorKind::InvalidInput,
354            format!("invalid endpoint kind `{kind}`"),
355        ));
356    }
357    if KINDS.contains(&kind.as_str()) {
358        return Err(io::Error::new(
359            io::ErrorKind::AlreadyExists,
360            format!("`{kind}` is a built-in endpoint kind"),
361        ));
362    }
363    registry()
364        .lock()
365        .unwrap_or_else(|poisoned| poisoned.into_inner())
366        .insert(kind, Registered { connect, listen });
367    Ok(())
368}
369
370fn unsupported(kind: &str, what: &str) -> io::Error {
371    io::Error::new(
372        io::ErrorKind::Unsupported,
373        format!("{what} on `{kind}:` endpoints is not supported on this platform"),
374    )
375}
376
377fn builtin_connect(endpoint: &Endpoint) -> io::Result<IpcStream> {
378    match endpoint.kind() {
379        "tcp" => net::connect_tcp(endpoint),
380        "udp" => net::connect_udp(endpoint),
381        "exec" => stdio::connect_exec(endpoint),
382        "stdio" => Err(io::Error::new(
383            io::ErrorKind::Unsupported,
384            "`stdio` can only be listened on; connect with `exec:COMMAND` instead",
385        )),
386        "mmap" | "file" | "shm" | "signal" => ring::connect(endpoint),
387        "unix" => net::connect_unix(endpoint),
388        #[cfg(unix)]
389        "pipe" | "fifo" => unix::connect_fifo(endpoint),
390        #[cfg(windows)]
391        "pipe" => windows::connect_pipe(endpoint),
392        #[cfg(any(target_os = "linux", target_vendor = "apple"))]
393        "sysvmq" => unix::connect_sysvmq(endpoint),
394        #[cfg(target_os = "linux")]
395        "mq" => unix::connect_mq(endpoint),
396        #[cfg(windows)]
397        "mailslot" => windows::connect_mailslot(endpoint),
398        #[cfg(windows)]
399        "copydata" => windows::connect_copydata(endpoint),
400        #[cfg(all(windows, target_pointer_width = "64"))]
401        "alpc" => windows::connect_alpc(endpoint),
402        kind => Err(unsupported(kind, "connecting")),
403    }
404}
405
406fn builtin_listen(endpoint: &Endpoint) -> io::Result<Box<dyn Listener>> {
407    match endpoint.kind() {
408        "tcp" => net::listen_tcp(endpoint),
409        "udp" => net::listen_udp(endpoint),
410        "stdio" => stdio::listen_stdio(endpoint),
411        "exec" => Err(io::Error::new(
412            io::ErrorKind::Unsupported,
413            "`exec` can only be connected to; listen on `stdio` in the started command",
414        )),
415        "mmap" | "file" | "shm" | "signal" => ring::listen(endpoint),
416        "unix" => net::listen_unix(endpoint),
417        #[cfg(unix)]
418        "pipe" | "fifo" => unix::listen_fifo(endpoint),
419        #[cfg(windows)]
420        "pipe" => windows::listen_pipe(endpoint),
421        #[cfg(any(target_os = "linux", target_vendor = "apple"))]
422        "sysvmq" => unix::listen_sysvmq(endpoint),
423        #[cfg(target_os = "linux")]
424        "mq" => unix::listen_mq(endpoint),
425        #[cfg(windows)]
426        "mailslot" => windows::listen_mailslot(endpoint),
427        #[cfg(windows)]
428        "copydata" => windows::listen_copydata(endpoint),
429        #[cfg(all(windows, target_pointer_width = "64"))]
430        "alpc" => windows::listen_alpc(endpoint),
431        kind => Err(unsupported(kind, "listening")),
432    }
433}
434
435/// Listens on several endpoints at once; see [`listen_all`].
436pub struct MultiListener {
437    endpoints: Vec<String>,
438    local_addr: Option<std::net::SocketAddr>,
439    closers: Vec<Waker>,
440    incoming: mpsc::Receiver<Option<io::Result<IpcStream>>>,
441    open: usize,
442    closed: Arc<AtomicBool>,
443}
444
445impl fmt::Debug for MultiListener {
446    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
447        formatter
448            .debug_struct("MultiListener")
449            .field("endpoints", &self.endpoints)
450            .finish_non_exhaustive()
451    }
452}
453
454impl MultiListener {
455    /// Accepts on every listener; each one runs on a thread of its own.
456    pub fn new(listeners: Vec<Box<dyn Listener>>) -> Self {
457        let (sender, incoming) = mpsc::channel();
458        let endpoints = listeners
459            .iter()
460            .flat_map(|listener| listener.endpoints())
461            .collect();
462        let local_addr = listeners.iter().find_map(|listener| listener.local_addr());
463        let closers = listeners.iter().map(|listener| listener.closer()).collect();
464        let open = listeners.len();
465        for mut listener in listeners {
466            let sender = sender.clone();
467            thread::spawn(move || loop {
468                match listener.accept() {
469                    Ok(Some(stream)) => {
470                        if sender.send(Some(Ok(stream))).is_err() {
471                            return;
472                        }
473                    }
474                    Ok(None) => {
475                        let _ = sender.send(None);
476                        return;
477                    }
478                    Err(error) => {
479                        if sender.send(Some(Err(error))).is_err() {
480                            return;
481                        }
482                    }
483                }
484            });
485        }
486        Self {
487            endpoints,
488            local_addr,
489            closers,
490            incoming,
491            open,
492            closed: Arc::new(AtomicBool::new(false)),
493        }
494    }
495}
496
497impl Listener for MultiListener {
498    fn accept(&mut self) -> io::Result<Option<IpcStream>> {
499        while self.open > 0 && !self.closed.load(Ordering::SeqCst) {
500            match self.incoming.recv() {
501                Ok(Some(result)) => return result.map(Some),
502                Ok(None) => self.open -= 1,
503                Err(_) => break,
504            }
505        }
506        Ok(None)
507    }
508
509    fn endpoint(&self) -> String {
510        self.endpoints.join(" ")
511    }
512
513    fn endpoints(&self) -> Vec<String> {
514        self.endpoints.clone()
515    }
516
517    fn local_addr(&self) -> Option<std::net::SocketAddr> {
518        self.local_addr
519    }
520
521    fn closer(&self) -> Waker {
522        let closers = self.closers.clone();
523        let closed = Arc::clone(&self.closed);
524        Arc::new(move || {
525            closed.store(true, Ordering::SeqCst);
526            for closer in &closers {
527                closer();
528            }
529        })
530    }
531}
532
533impl Drop for MultiListener {
534    fn drop(&mut self) {
535        for closer in &self.closers {
536            closer();
537        }
538    }
539}
540
541/// Copies both directions between `a` and `b` until both ended, passing
542/// the end of each direction on with [`IpcStream::close_write`]. Returns
543/// the bytes copied from `a` to `b` and from `b` to `a`.
544///
545/// This stacks transports: a relay that accepts on one endpoint and
546/// forwards to another one never parses the protocol.
547pub fn forward(a: IpcStream, b: IpcStream) -> io::Result<(u64, u64)> {
548    let (a2, b2) = (a.clone(), b.clone());
549    let backward = thread::spawn(move || pump(b2, a2));
550    let forward = pump(a.clone(), b.clone());
551    let backward = backward
552        .join()
553        .unwrap_or_else(|_| Err(io::Error::other("relay thread panicked")));
554    a.shutdown();
555    b.shutdown();
556    Ok((forward?, backward?))
557}
558
559fn pump(mut from: IpcStream, mut to: IpcStream) -> io::Result<u64> {
560    let mut buffer = vec![0; 64 * 1024];
561    let mut total = 0;
562    loop {
563        let read = match from.read(&mut buffer) {
564            Ok(0) => break,
565            Ok(read) => read,
566            Err(error) => {
567                trace!("relay {} -> {}: {error}", from.kind(), to.kind());
568                // The other direction cannot go on either.
569                to.shutdown();
570                from.shutdown();
571                return Err(error);
572            }
573        };
574        if let Err(error) = to.write_all(&buffer[..read]).and_then(|()| to.flush()) {
575            trace!("relay {} -> {}: {error}", from.kind(), to.kind());
576            from.shutdown();
577            to.shutdown();
578            return Err(error);
579        }
580        total += read as u64;
581    }
582    trace!(
583        "relay {} -> {}: end after {total} bytes",
584        from.kind(),
585        to.kind()
586    );
587    let _ = to.close_write();
588    Ok(total)
589}
590
591/// Accepts connections on `listener` and forwards each one to a new
592/// connection to `target` (see [`forward`]) until the listener is closed or
593/// exhausted. Waits for the forwarded connections to end before returning.
594pub fn relay(listener: &mut dyn Listener, target: &Endpoint) -> io::Result<()> {
595    let mut connections = Vec::new();
596    loop {
597        let stream = match listener.accept() {
598            Ok(Some(stream)) => stream,
599            Ok(None) => break,
600            Err(error) => {
601                trace!("relay accept on {} failed: {error}", listener.endpoint());
602                // A failing listener must not spin.
603                thread::sleep(Duration::from_millis(10));
604                continue;
605            }
606        };
607        let target = target.clone();
608        connections.push(thread::spawn(move || match connect_endpoint(&target) {
609            Ok(outgoing) => {
610                if let Err(error) = forward(stream, outgoing) {
611                    trace!("relay to {target} ended: {error}");
612                }
613            }
614            Err(error) => {
615                crate::diagnostics::stderr!("clink: cannot forward to {target}: {error}");
616                stream.shutdown();
617            }
618        }));
619        connections.retain(|connection| !connection.is_finished());
620    }
621    for connection in connections {
622        let _ = connection.join();
623    }
624    Ok(())
625}
626
627const TRACE_UNSET: u8 = 0;
628const TRACE_OFF: u8 = 1;
629const TRACE_ON: u8 = 2;
630static TRACE: AtomicU8 = AtomicU8::new(TRACE_UNSET);
631
632/// Turns the `[ipc]` transport log on standard error on or off. It starts
633/// on when the environment variable `CLINK_IPC_TRACE` is `1`.
634pub fn set_trace(enabled: bool) {
635    TRACE.store(
636        if enabled { TRACE_ON } else { TRACE_OFF },
637        Ordering::Relaxed,
638    );
639}
640
641/// Whether the `[ipc]` transport log is on.
642pub fn trace_enabled() -> bool {
643    match TRACE.load(Ordering::Relaxed) {
644        TRACE_ON => true,
645        TRACE_OFF => false,
646        _ => {
647            let enabled = std::env::var("CLINK_IPC_TRACE").is_ok_and(|value| value == "1");
648            set_trace(enabled);
649            enabled
650        }
651    }
652}
653
654macro_rules! trace {
655    ($($argument:tt)*) => {
656        if $crate::protocol::ipc::trace_enabled() {
657            $crate::diagnostics::stderr!("[ipc] {}", ::std::format_args!($($argument)*));
658        }
659    };
660}
661pub(crate) use trace;
662
663/// A fresh identifier of 20 lowercase hexadecimal digits.
664pub(crate) fn random_id() -> String {
665    let [a, b] = random_u64s();
666    format!("{:016x}{:04x}", a, b & 0xffff)
667}
668
669/// Sixteen bytes nobody else can predict cheaply; not cryptographic.
670pub(crate) fn random_token() -> [u8; 16] {
671    let [a, b] = random_u64s();
672    let mut token = [0; 16];
673    token[..8].copy_from_slice(&a.to_le_bytes());
674    token[8..].copy_from_slice(&b.to_le_bytes());
675    token
676}
677
678fn random_u64s() -> [u64; 2] {
679    use std::collections::hash_map::RandomState;
680    use std::hash::{BuildHasher, Hasher};
681    use std::sync::atomic::AtomicU64;
682    static COUNTER: AtomicU64 = AtomicU64::new(0);
683    let count = COUNTER.fetch_add(1, Ordering::Relaxed);
684    let nanos = web_time::SystemTime::now()
685        .duration_since(web_time::UNIX_EPOCH)
686        .map_or(0, |elapsed| elapsed.as_nanos() as u64);
687    let mut values = [0; 2];
688    for (index, value) in values.iter_mut().enumerate() {
689        let mut hasher = RandomState::new().build_hasher();
690        hasher.write_u64(count);
691        hasher.write_u64(nanos);
692        hasher.write_u32(std::process::id());
693        hasher.write_usize(index);
694        *value = hasher.finish();
695    }
696    values
697}
698
699/// Whether the process `pid` is still running.
700pub(crate) fn process_alive(pid: u32) -> bool {
701    #[cfg(unix)]
702    {
703        unix::process_alive(pid)
704    }
705    #[cfg(windows)]
706    {
707        windows::process_alive(pid)
708    }
709    #[cfg(not(any(unix, windows)))]
710    {
711        let _ = pid;
712        true
713    }
714}
715
716/// Watches whether a peer process is alive at most every 100 ms.
717#[derive(Debug)]
718pub(crate) struct PeerWatch {
719    pid: u32,
720    state: Mutex<(web_time::Instant, bool)>,
721}
722
723impl PeerWatch {
724    pub(crate) fn new(pid: u32) -> Self {
725        Self {
726            pid,
727            state: Mutex::new((web_time::Instant::now(), true)),
728        }
729    }
730
731    pub(crate) fn pid(&self) -> u32 {
732        self.pid
733    }
734
735    pub(crate) fn alive(&self) -> bool {
736        let mut state = self
737            .state
738            .lock()
739            .unwrap_or_else(|poisoned| poisoned.into_inner());
740        if state.1 && state.0.elapsed() >= Duration::from_millis(100) {
741            state.1 = process_alive(self.pid);
742            state.0 = web_time::Instant::now();
743        }
744        state.1
745    }
746}
747
748pub(crate) fn hung_up() -> io::Error {
749    io::Error::new(io::ErrorKind::ConnectionReset, "the peer hung up")
750}
751
752pub(crate) fn broken_pipe() -> io::Error {
753    io::Error::new(io::ErrorKind::BrokenPipe, "the peer no longer reads")
754}
755
756pub(crate) fn timed_out() -> io::Error {
757    io::Error::new(io::ErrorKind::TimedOut, "timed out")
758}
759
760#[cfg(test)]
761mod tests;