Skip to main content

net_io/
handoff.rs

1//! Listener hand-off between processes, and the owned listener handle that
2//! inheritance, hand-off, and `Server::release_listeners` produce.
3//!
4//! `send_listeners` and `recv_listeners` are Unix (feature `local`);
5//! `share_listeners` and `receive_shared` are their Windows counterparts. A
6//! `ListenerHandle` and the error type exist in every build.
7//!
8//! Manifest, version 1 (big-endian integers):
9//!
10//! ```text
11//!  "NIOH" | version 1 | count | total length (u16, all bytes including the CRC)
12//!  per listener: kind (1 TCP, 2 Unix) | name length (at most 64) | name
13//!                | address length (u16) | address (TCP: family 4 or 6, IP, port;
14//!                  Unix: the path bytes)
15//!  CRC32C of everything before it (u32)
16//! ```
17//!
18//! On Windows the manifest is followed by a 16-byte nonce, one 628-byte
19//! `WSAPROTOCOL_INFOW` per listener, and a CRC32C of those.
20
21// The manifest is read and written only by the hand-off functions.
22#![cfg_attr(not(feature = "local"), allow(dead_code))]
23
24use std::fmt;
25use std::io;
26#[cfg(unix)]
27use std::sync::Arc;
28
29#[cfg(unix)]
30use crate::info::UnixPath;
31use crate::info::{Endpoint, Transport};
32use crate::sys::{self, KindError, SockKind};
33
34/// Why a listener hand-off failed. Nothing is adopted on any error.
35///
36/// ```
37/// assert_eq!(net_io::HandoffError::BadChecksum.to_string(), "the hand-off manifest checksum does not match");
38/// ```
39#[non_exhaustive]
40#[derive(Debug)]
41pub enum HandoffError {
42    /// The sender is not the expected process or user.
43    PeerMismatch,
44    /// The control message was truncated.
45    Truncated,
46    /// The descriptor count does not match the manifest.
47    CountMismatch,
48    /// The manifest does not start with the expected magic.
49    BadMagic,
50    /// The manifest version is unknown.
51    BadVersion,
52    /// The manifest checksum does not match.
53    BadChecksum,
54    /// More listeners than one hand-off carries.
55    TooMany {
56        /// The maximum.
57        max: u8,
58    },
59    /// A received socket failed verification.
60    VerifyFailed {
61        /// Its position in the manifest.
62        index: u8,
63        /// Which check failed.
64        why: &'static str,
65    },
66    /// The hand-off did not finish in time.
67    Timeout,
68    /// An OS call failed.
69    Os(io::Error),
70}
71
72impl fmt::Display for HandoffError {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        match self {
75            HandoffError::PeerMismatch => {
76                f.write_str("the hand-off sender is not the expected process or user")
77            }
78            HandoffError::Truncated => f.write_str("the hand-off message was truncated"),
79            HandoffError::CountMismatch => {
80                f.write_str("the descriptor count does not match the manifest")
81            }
82            HandoffError::BadMagic => f.write_str("not a hand-off manifest"),
83            HandoffError::BadVersion => f.write_str("unknown hand-off manifest version"),
84            HandoffError::BadChecksum => {
85                f.write_str("the hand-off manifest checksum does not match")
86            }
87            HandoffError::TooMany { max } => write!(f, "more than {max} listeners in one hand-off"),
88            HandoffError::VerifyFailed { index, why } => {
89                write!(f, "received listener {index} failed: {why}")
90            }
91            HandoffError::Timeout => f.write_str("the hand-off did not finish in time"),
92            HandoffError::Os(e) => write!(f, "{e}"),
93        }
94    }
95}
96
97impl std::error::Error for HandoffError {
98    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
99        match self {
100            HandoffError::Os(e) => Some(e),
101            _ => None,
102        }
103    }
104}
105
106/// An owned listening socket with what is known about it: its kind, an
107/// optional name (up to 64 bytes), and its local endpoint. Dropping it closes
108/// the socket. Made by [`crate::systemd`], hand-off, and
109/// `Server::release_listeners`; used by `ListenerSpec::adopt`.
110pub struct ListenerHandle {
111    kind: Transport,
112    name: Option<String>,
113    local: Endpoint,
114    sock: sys::OwnedSock,
115    /// After `sock`, so the socket closes before its value is freed.
116    #[cfg(all(windows, feature = "local"))]
117    adopted: Option<sys::Adoption>,
118}
119
120impl ListenerHandle {
121    /// Verifies `sock` (a listening stream socket of a family net-io serves) and
122    /// records its endpoint.
123    #[cfg_attr(not(unix), allow(dead_code))]
124    pub(crate) fn verified(
125        sock: sys::OwnedSock,
126        name: Option<String>,
127    ) -> Result<ListenerHandle, KindError> {
128        let kind = sys::listener_kind(sys::AsSock::sock(&sock))?;
129        let (kind, local) = endpoint_of(kind)?;
130        Ok(ListenerHandle::new(kind, name, local, sock))
131    }
132
133    pub(crate) fn new(
134        kind: Transport,
135        name: Option<String>,
136        local: Endpoint,
137        sock: sys::OwnedSock,
138    ) -> ListenerHandle {
139        ListenerHandle {
140            kind,
141            name,
142            local,
143            sock,
144            #[cfg(all(windows, feature = "local"))]
145            adopted: None,
146        }
147    }
148
149    pub(crate) fn into_sock(self) -> sys::OwnedSock {
150        #[cfg(all(windows, feature = "local"))]
151        if let Some(adoption) = self.adopted {
152            adoption.keep_for_good();
153        }
154        self.sock
155    }
156
157    /// TCP or Unix.
158    #[must_use]
159    pub fn kind(&self) -> Transport {
160        self.kind
161    }
162
163    /// The name it was given (systemd's `LISTEN_FDNAMES`, a listener's name).
164    #[must_use]
165    pub fn name(&self) -> Option<&str> {
166        self.name.as_deref()
167    }
168
169    /// The address it is bound to.
170    #[must_use]
171    pub fn local(&self) -> &Endpoint {
172        &self.local
173    }
174}
175
176/// The transport and endpoint of a verified socket.
177fn endpoint_of(kind: SockKind) -> Result<(Transport, Endpoint), KindError> {
178    match kind {
179        SockKind::Tcp(a) => Ok((Transport::Tcp, Endpoint::Ip(a))),
180        #[cfg(unix)]
181        SockKind::Unix(path) => {
182            if !cfg!(feature = "local") {
183                return Err(KindError::WrongKind);
184            }
185            let local = UnixPath::new(&path)
186                .filter(|_| !path.is_empty())
187                .map_or(Endpoint::Unnamed, |p| Endpoint::Unix(Arc::new(p)));
188            Ok((Transport::Unix, local))
189        }
190    }
191}
192
193impl fmt::Debug for ListenerHandle {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        f.debug_struct("ListenerHandle")
196            .field("kind", &self.kind)
197            .field("name", &self.name)
198            .field("local", &self.local)
199            .finish()
200    }
201}
202
203#[cfg(unix)]
204impl std::os::fd::AsFd for ListenerHandle {
205    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
206        self.sock.as_fd()
207    }
208}
209
210#[cfg(windows)]
211impl std::os::windows::io::AsSocket for ListenerHandle {
212    fn as_socket(&self) -> std::os::windows::io::BorrowedSocket<'_> {
213        self.sock.as_socket()
214    }
215}
216
217/// Whom `recv_listeners` accepts listeners from. `uid: None` means this
218/// process's own effective user id; `pid: None` accepts any process of that user.
219///
220/// ```
221/// let only_parent = net_io::HandoffPeer { uid: None, pid: Some(1234) };
222/// # let _ = only_parent;
223/// ```
224#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
225pub struct HandoffPeer {
226    /// The sender's user id (`None`: ours).
227    pub uid: Option<u32>,
228    /// The sender's process id (`None`: any).
229    pub pid: Option<u32>,
230}
231
232const MAGIC: [u8; 4] = *b"NIOH";
233const VERSION: u8 = 1;
234const HEADER: usize = 8;
235/// The most listeners one hand-off carries (one `SCM_RIGHTS` message).
236const MAX_LISTENERS: usize = 64;
237/// The longest name carried; longer names are cut at a character boundary.
238const MAX_NAME: usize = 64;
239
240/// One listener as the manifest describes it.
241#[derive(Clone, Debug, PartialEq, Eq)]
242struct Record {
243    kind: SockKind,
244    name: Option<String>,
245}
246
247/// Encodes the manifest for `records`.
248fn encode(records: &[Record]) -> Vec<u8> {
249    let mut out = Vec::with_capacity(HEADER + records.len() * 96 + 4);
250    out.extend_from_slice(&MAGIC);
251    out.push(VERSION);
252    out.push(records.len() as u8);
253    out.extend_from_slice(&[0, 0]); // total length, filled in below
254    for r in records {
255        let mut name = r.name.as_deref().unwrap_or("");
256        if name.len() > MAX_NAME {
257            let mut cut = MAX_NAME;
258            while !name.is_char_boundary(cut) {
259                cut -= 1;
260            }
261            name = &name[..cut];
262        }
263        let mut addr = Vec::with_capacity(32);
264        let kind = match &r.kind {
265            SockKind::Tcp(a) => {
266                match a.ip() {
267                    std::net::IpAddr::V4(ip) => {
268                        addr.push(4);
269                        addr.extend_from_slice(&ip.octets());
270                    }
271                    std::net::IpAddr::V6(ip) => {
272                        addr.push(6);
273                        addr.extend_from_slice(&ip.octets());
274                    }
275                }
276                addr.extend_from_slice(&a.port().to_be_bytes());
277                1u8
278            }
279            #[cfg(unix)]
280            SockKind::Unix(path) => {
281                addr.extend_from_slice(path);
282                2u8
283            }
284        };
285        out.push(kind);
286        out.push(name.len() as u8);
287        out.extend_from_slice(name.as_bytes());
288        out.extend_from_slice(&(addr.len() as u16).to_be_bytes());
289        out.extend_from_slice(&addr);
290    }
291    let total = (out.len() + 4) as u16;
292    out[6..8].copy_from_slice(&total.to_be_bytes());
293    let mut crc = crate::crc32c::Crc32c::new();
294    crc.update(&out);
295    out.extend_from_slice(&crc.finish().to_be_bytes());
296    out
297}
298
299/// Checks the header: magic, version, count, total length.
300fn parse_header(h: &[u8; HEADER]) -> Result<(usize, usize), HandoffError> {
301    if h[..4] != MAGIC {
302        return Err(HandoffError::BadMagic);
303    }
304    if h[4] != VERSION {
305        return Err(HandoffError::BadVersion);
306    }
307    let count = usize::from(h[5]);
308    if count > MAX_LISTENERS {
309        return Err(HandoffError::TooMany {
310            max: MAX_LISTENERS as u8,
311        });
312    }
313    let total = usize::from(u16::from_be_bytes([h[6], h[7]]));
314    if total < HEADER + 4 {
315        return Err(HandoffError::Truncated);
316    }
317    Ok((count, total))
318}
319
320/// Parses a whole manifest (header included).
321fn decode(bytes: &[u8]) -> Result<Vec<Record>, HandoffError> {
322    let header: &[u8; HEADER] = bytes
323        .get(..HEADER)
324        .and_then(|h| h.try_into().ok())
325        .ok_or(HandoffError::Truncated)?;
326    let (count, total) = parse_header(header)?;
327    if bytes.len() != total {
328        return Err(HandoffError::Truncated);
329    }
330    let (body, sum) = bytes.split_at(total - 4);
331    let mut crc = crate::crc32c::Crc32c::new();
332    crc.update(body);
333    if crc.finish().to_be_bytes() != sum {
334        return Err(HandoffError::BadChecksum);
335    }
336    let mut at = HEADER;
337    let mut take = |n: usize| -> Result<&[u8], HandoffError> {
338        let s = body.get(at..at + n).ok_or(HandoffError::Truncated)?;
339        at += n;
340        Ok(s)
341    };
342    let mut records = Vec::with_capacity(count);
343    for i in 0..count {
344        let bad = |why| HandoffError::VerifyFailed {
345            index: i as u8,
346            why,
347        };
348        let kind = take(1)?[0];
349        let name_len = usize::from(take(1)?[0]);
350        if name_len > MAX_NAME {
351            return Err(bad("name longer than 64 bytes"));
352        }
353        let name = std::str::from_utf8(take(name_len)?)
354            .map_err(|_| bad("name is not UTF-8"))?
355            .to_owned();
356        let addr_len = take(2)?;
357        let addr_len = usize::from(u16::from_be_bytes([addr_len[0], addr_len[1]]));
358        let addr = take(addr_len)?;
359        let kind = match (kind, addr) {
360            (1, [4, a, b, c, d, p0, p1]) => SockKind::Tcp(std::net::SocketAddr::from((
361                [*a, *b, *c, *d],
362                u16::from_be_bytes([*p0, *p1]),
363            ))),
364            (1, [6, rest @ ..]) if rest.len() == 18 => {
365                let mut ip = [0u8; 16];
366                ip.copy_from_slice(&rest[..16]);
367                SockKind::Tcp(std::net::SocketAddr::from((
368                    ip,
369                    u16::from_be_bytes([rest[16], rest[17]]),
370                )))
371            }
372            #[cfg(unix)]
373            (2, path) => SockKind::Unix(path.to_vec()),
374            _ => return Err(bad("unknown kind or malformed address")),
375        };
376        records.push(Record {
377            kind,
378            name: (!name.is_empty()).then_some(name),
379        });
380    }
381    if at != body.len() {
382        return Err(HandoffError::Truncated);
383    }
384    Ok(records)
385}
386
387/// The fuzz target's entry: decoding never panics, and an accepted manifest
388/// encodes back to the same bytes.
389#[cfg(fuzzing)]
390pub(crate) fn fuzz_manifest(data: &[u8]) {
391    if let Ok(records) = decode(data) {
392        assert_eq!(encode(&records), data);
393    }
394}
395
396/// Sends `listeners` over `channel` in one message: the manifest and every
397/// socket (`SCM_RIGHTS`). The listeners stay open here; the receiver gets its
398/// own copies. At most 64.
399///
400/// # Errors
401///
402/// `TooMany`, `Timeout`, `Os`.
403#[cfg(all(unix, feature = "local"))]
404pub fn send_listeners(
405    channel: &mut crate::local::UnixConnection,
406    listeners: &[&ListenerHandle],
407) -> Result<(), HandoffError> {
408    use std::os::fd::AsFd;
409    if listeners.len() > MAX_LISTENERS {
410        return Err(HandoffError::TooMany {
411            max: MAX_LISTENERS as u8,
412        });
413    }
414    let mut records = Vec::with_capacity(listeners.len());
415    for (i, l) in listeners.iter().enumerate() {
416        let kind = sys::listener_kind(l.as_fd()).map_err(|e| HandoffError::VerifyFailed {
417            index: i as u8,
418            why: why(&e),
419        })?;
420        records.push(Record {
421            kind,
422            name: l.name.clone(),
423        });
424    }
425    let manifest = encode(&records);
426    let fds: Vec<_> = listeners.iter().map(|l| l.as_fd()).collect();
427    channel
428        .send_descriptors(&manifest, &fds)
429        .map_err(handoff_error)
430}
431
432/// Receives listeners from `channel`. The sender's credentials must match
433/// `expect` (by default: the same user); the message must be complete, intact
434/// (magic, version, CRC32C), carry exactly as many sockets as it lists, and
435/// every socket must be a listener bound to the address the manifest names.
436/// All or nothing: on any error every received socket is closed.
437///
438/// # Errors
439///
440/// `PeerMismatch`, `Timeout` (nothing arrived by `deadline`), `Truncated` (the
441/// sender closed mid-message or the control data was cut), `BadMagic`,
442/// `BadVersion`, `BadChecksum`, `CountMismatch`, `TooMany`, `VerifyFailed`, `Os`.
443#[cfg(all(unix, feature = "local"))]
444pub fn recv_listeners(
445    channel: &mut crate::local::UnixConnection,
446    expect: &HandoffPeer,
447    deadline: std::time::Instant,
448) -> Result<Vec<ListenerHandle>, HandoffError> {
449    use crate::local::Descriptors;
450    let creds = channel
451        .peer_credentials()
452        .map_err(|_| HandoffError::PeerMismatch)?;
453    let uid = expect.uid.unwrap_or_else(sys::effective_uid);
454    if creds.uid != Some(uid) || expect.pid.is_some_and(|p| creds.pid != Some(p)) {
455        return Err(HandoffError::PeerMismatch);
456    }
457    channel.set_phase(crate::session::Phase::Receiving);
458    channel.set_exchange_deadline(Some(deadline));
459    let result = receive(channel);
460    channel.set_exchange_deadline(None);
461    let (records, mut fds): (Vec<Record>, Descriptors) = result?;
462    if fds.len() != records.len() {
463        return Err(HandoffError::CountMismatch);
464    }
465    let mut handles = Vec::with_capacity(records.len());
466    for (i, (record, fd)) in records.into_iter().zip(fds.take()).enumerate() {
467        let index = i as u8;
468        let got = sys::listener_kind(std::os::fd::AsFd::as_fd(&fd)).map_err(|e| {
469            HandoffError::VerifyFailed {
470                index,
471                why: why(&e),
472            }
473        })?;
474        if got != record.kind {
475            return Err(HandoffError::VerifyFailed {
476                index,
477                why: "bound to another address than the manifest says",
478            });
479        }
480        let (kind, local) = endpoint_of(got).map_err(|e| HandoffError::VerifyFailed {
481            index,
482            why: why(&e),
483        })?;
484        handles.push(ListenerHandle::new(kind, record.name, local, fd));
485    }
486    Ok(handles)
487}
488
489/// Reads the manifest and its descriptors.
490#[cfg(all(unix, feature = "local"))]
491fn receive(
492    channel: &mut crate::local::UnixConnection,
493) -> Result<(Vec<Record>, crate::local::Descriptors), HandoffError> {
494    use crate::local::Descriptors;
495    let mut fds = Descriptors::new();
496    let mut header = [0u8; HEADER];
497    let mut got = 0;
498    while got < HEADER {
499        // The descriptors travel with the first byte; a later read must bring none.
500        let mut extra = Descriptors::new();
501        let into = if got == 0 { &mut fds } else { &mut extra };
502        let n = channel
503            .recv_descriptors(&mut header[got..], into)
504            .map_err(handoff_error)?;
505        if n == 0 {
506            return Err(HandoffError::Truncated);
507        }
508        if !extra.is_empty() {
509            return Err(HandoffError::CountMismatch);
510        }
511        got += n;
512    }
513    let (_, total) = parse_header(&header)?;
514    let mut manifest = vec![0u8; total];
515    manifest[..HEADER].copy_from_slice(&header);
516    let mut at = HEADER;
517    while at < total {
518        let mut extra = Descriptors::new();
519        let n = channel
520            .recv_descriptors(&mut manifest[at..], &mut extra)
521            .map_err(handoff_error)?;
522        if n == 0 {
523            return Err(HandoffError::Truncated);
524        }
525        if !extra.is_empty() {
526            return Err(HandoffError::CountMismatch);
527        }
528        at += n;
529    }
530    let records = decode(&manifest)?;
531    Ok((records, fds))
532}
533
534#[cfg(feature = "local")]
535fn handoff_error(e: crate::error::NetError) -> HandoffError {
536    use crate::error::NetError;
537    match e {
538        NetError::TimedOut { .. } => HandoffError::Timeout,
539        NetError::Handoff(h) => h,
540        NetError::Closed => HandoffError::Truncated,
541        other => HandoffError::Os(io::Error::from(other)),
542    }
543}
544
545fn why(e: &KindError) -> &'static str {
546    match e {
547        KindError::NotASocket => "not a socket",
548        KindError::NotListening => "not listening",
549        KindError::WrongKind => "not a TCP or Unix stream listener",
550        KindError::Os(_) => "could not be inspected",
551    }
552}
553
554/// Listeners described for one process, ready to go over a pipe once.
555///
556/// ```no_run
557/// use net_io::{PipeConnection, share_listeners};
558/// # fn f(handles: Vec<net_io::ListenerHandle>, pid: u32, mut pipe: PipeConnection)
559/// #     -> Result<(), net_io::HandoffError> {
560/// let shared = share_listeners(&handles.iter().collect::<Vec<_>>(), pid)?;
561/// shared.write_to(&mut pipe)?;
562/// # Ok(())
563/// # }
564/// ```
565#[cfg(all(windows, feature = "local"))]
566#[cfg_attr(docsrs, doc(cfg(windows)))]
567pub struct SharedListeners {
568    frame: Vec<u8>,
569}
570
571#[cfg(all(windows, feature = "local"))]
572impl std::fmt::Debug for SharedListeners {
573    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
574        f.debug_struct("SharedListeners").finish_non_exhaustive()
575    }
576}
577
578#[cfg(all(windows, feature = "local"))]
579const NONCE: usize = 16;
580
581/// Nonces this process has accepted. Windows lets a description be used twice and
582/// returns the same socket; this makes it once.
583#[cfg(all(windows, feature = "local"))]
584static ACCEPTED: std::sync::Mutex<Vec<[u8; NONCE]>> = std::sync::Mutex::new(Vec::new());
585
586/// Describes `listeners` for the process `target_pid`. Each description works in that
587/// process alone. Send them over a pipe with an owner-only security descriptor, which
588/// is what [`PipeListener::create`](crate::PipeListener::create) makes.
589///
590/// # Errors
591///
592/// `TooMany`, `VerifyFailed`, `Os`.
593#[cfg(all(windows, feature = "local"))]
594#[cfg_attr(docsrs, doc(cfg(windows)))]
595pub fn share_listeners(
596    listeners: &[&ListenerHandle],
597    target_pid: u32,
598) -> Result<SharedListeners, HandoffError> {
599    use std::os::windows::io::AsSocket;
600    if listeners.len() > MAX_LISTENERS {
601        return Err(HandoffError::TooMany {
602            max: MAX_LISTENERS as u8,
603        });
604    }
605    let mut records = Vec::with_capacity(listeners.len());
606    let mut tail = vec![0u8; NONCE];
607    sys::random_bytes(&mut tail).map_err(HandoffError::Os)?;
608    for (i, l) in listeners.iter().enumerate() {
609        let kind = sys::listener_kind(l.as_socket()).map_err(|e| HandoffError::VerifyFailed {
610            index: i as u8,
611            why: why(&e),
612        })?;
613        records.push(Record {
614            kind,
615            name: l.name.clone(),
616        });
617        let blob = sys::share_socket(l.as_socket(), target_pid).map_err(HandoffError::Os)?;
618        tail.extend_from_slice(&blob);
619    }
620    let mut crc = crate::crc32c::Crc32c::new();
621    crc.update(&tail);
622    let check = crc.finish().to_be_bytes();
623    let mut frame = encode(&records);
624    frame.extend_from_slice(&tail);
625    frame.extend_from_slice(&check);
626    Ok(SharedListeners { frame })
627}
628
629#[cfg(all(windows, feature = "local"))]
630impl SharedListeners {
631    /// Sends the listeners; consumed, so they go once.
632    ///
633    /// # Errors
634    ///
635    /// `Timeout`, `Truncated`, `Os`.
636    pub fn write_to(self, pipe: &mut crate::pipe::PipeConnection) -> Result<(), HandoffError> {
637        pipe.send_all(&self.frame).map_err(handoff_error)
638    }
639}
640
641/// Receives listeners sent with [`SharedListeners::write_to`]. The process at the
642/// far end must be `expect.pid` when that is set; `expect.uid` has no meaning here,
643/// since the pipe's security descriptor decides who gets to the pipe. The message
644/// must be intact and never seen before, and every socket a listener bound to the
645/// address the manifest names. All or nothing: on any error every received socket
646/// is closed, also those listed after the one that failed. A description that
647/// names a socket this process already owns (the same one twice, one from an
648/// earlier hand-off, or a forged one) is refused, so no socket gets two owners.
649/// Received sockets are not inheritable.
650///
651/// Windows makes each socket in this process when the sender describes it, so a
652/// message that arrives damaged (`Truncated`, `BadChecksum`, or a bad manifest)
653/// leaves the sockets it described open here, unclaimed, until this process
654/// exits: their descriptions cannot be trusted enough to claim them. Only a
655/// process the pipe's security descriptor admits can cause that; set
656/// `expect.pid` to narrow it to the one expected sender.
657///
658/// # Errors
659///
660/// `PeerMismatch`, `Timeout`, `Truncated`, `BadMagic`, `BadVersion`, `BadChecksum`,
661/// `TooMany`, `VerifyFailed` (also for a message accepted before), `Os`.
662#[cfg(all(windows, feature = "local"))]
663#[cfg_attr(docsrs, doc(cfg(windows)))]
664pub fn receive_shared(
665    pipe: &mut crate::pipe::PipeConnection,
666    expect: &HandoffPeer,
667    deadline: std::time::Instant,
668) -> Result<Vec<ListenerHandle>, HandoffError> {
669    let peer = pipe.peer_pid().map_err(|_| HandoffError::PeerMismatch)?;
670    if expect.pid.is_some_and(|p| p != peer) {
671        return Err(HandoffError::PeerMismatch);
672    }
673    pipe.set_phase(crate::session::Phase::Receiving);
674    pipe.set_exchange_deadline(Some(deadline));
675    let result = read_shared(pipe);
676    pipe.set_exchange_deadline(None);
677    let (records, tail) = result?;
678    let (nonce, blobs) = tail.split_at(NONCE);
679    let nonce: [u8; NONCE] = nonce.try_into().map_err(|_| HandoffError::Truncated)?;
680    adopt_shared(records, nonce, blobs)
681}
682
683#[cfg(all(windows, feature = "local"))]
684fn read_shared(
685    pipe: &mut crate::pipe::PipeConnection,
686) -> Result<(Vec<Record>, Vec<u8>), HandoffError> {
687    let mut header = [0u8; HEADER];
688    pipe.recv_exact(&mut header).map_err(handoff_error)?;
689    let (count, total) = parse_header(&header)?;
690    let mut manifest = vec![0u8; total];
691    manifest[..HEADER].copy_from_slice(&header);
692    pipe.recv_exact(&mut manifest[HEADER..])
693        .map_err(handoff_error)?;
694    let records = decode(&manifest)?;
695    let mut tail = vec![0u8; NONCE + count * sys::SHARED_SOCKET + 4];
696    pipe.recv_exact(&mut tail).map_err(handoff_error)?;
697    let check_at = tail.len() - 4;
698    let mut crc = crate::crc32c::Crc32c::new();
699    crc.update(&tail[..check_at]);
700    if crc.finish().to_be_bytes() != tail[check_at..] {
701        return Err(HandoffError::BadChecksum);
702    }
703    tail.truncate(check_at);
704    Ok((records, tail))
705}
706
707#[cfg(all(windows, feature = "local"))]
708fn adopt_shared(
709    records: Vec<Record>,
710    nonce: [u8; NONCE],
711    blobs: &[u8],
712) -> Result<Vec<ListenerHandle>, HandoffError> {
713    {
714        let mut seen = ACCEPTED
715            .lock()
716            .unwrap_or_else(std::sync::PoisonError::into_inner);
717        if seen.contains(&nonce) {
718            return Err(HandoffError::VerifyFailed {
719                index: 0,
720                why: "this hand-off was already accepted",
721            });
722        }
723        seen.push(nonce);
724    }
725    // Every description is claimed before anything is checked: Windows made the
726    // duplicate in this process when the sender described it, so one never turned
727    // into a socket here stays open with no owner. A failure below drops them all.
728    let mut claimed = Vec::with_capacity(records.len());
729    let mut failed = None;
730    for (i, blob) in blobs.chunks_exact(sys::SHARED_SOCKET).enumerate() {
731        let index = i as u8;
732        let got = <&[u8; sys::SHARED_SOCKET]>::try_from(blob)
733            .map_err(|_| HandoffError::Truncated)
734            .and_then(|blob| {
735                sys::socket_from_shared(blob).map_err(|e| match e.kind() {
736                    io::ErrorKind::AlreadyExists => HandoffError::VerifyFailed {
737                        index,
738                        why: "names a socket this process already owns",
739                    },
740                    _ => HandoffError::Os(e),
741                })
742            });
743        match got {
744            Ok(sock) => claimed.push(sock),
745            Err(e) => {
746                failed.get_or_insert(e);
747            }
748        }
749    }
750    if let Some(e) = failed {
751        return Err(e);
752    }
753    if claimed.len() != records.len() {
754        return Err(HandoffError::CountMismatch);
755    }
756    let mut handles = Vec::with_capacity(records.len());
757    for (i, (record, (sock, adoption))) in records.into_iter().zip(claimed).enumerate() {
758        let index = i as u8;
759        let got = sys::listener_kind(sys::AsSock::sock(&sock)).map_err(|e| {
760            HandoffError::VerifyFailed {
761                index,
762                why: why(&e),
763            }
764        })?;
765        if got != record.kind {
766            return Err(HandoffError::VerifyFailed {
767                index,
768                why: "bound to another address than the manifest says",
769            });
770        }
771        let (kind, local) = endpoint_of(got).map_err(|e| HandoffError::VerifyFailed {
772            index,
773            why: why(&e),
774        })?;
775        let mut handle = ListenerHandle::new(kind, record.name, local, sock);
776        handle.adopted = Some(adoption);
777        handles.push(handle);
778    }
779    Ok(handles)
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    fn records() -> Vec<Record> {
787        #[cfg_attr(not(unix), allow(unused_mut))]
788        let mut v = vec![
789            Record {
790                kind: SockKind::Tcp("127.0.0.1:8080".parse().unwrap()),
791                name: Some("web".into()),
792            },
793            Record {
794                kind: SockKind::Tcp("[2001:db8::1]:443".parse().unwrap()),
795                name: None,
796            },
797        ];
798        #[cfg(unix)]
799        v.push(Record {
800            kind: SockKind::Unix(b"/run/app/api.sock".to_vec()),
801            name: Some("api".into()),
802        });
803        v
804    }
805
806    #[test]
807    fn test_manifest_round_trips() {
808        let r = records();
809        assert_eq!(decode(&encode(&r)).unwrap(), r);
810        assert_eq!(decode(&encode(&[])).unwrap(), Vec::new());
811    }
812
813    #[test]
814    fn test_manifest_rejects_damage() {
815        let good = encode(&records());
816        let mut m = good.clone();
817        m[0] = b'X';
818        assert!(matches!(decode(&m), Err(HandoffError::BadMagic)));
819        let mut m = good.clone();
820        m[4] = 2;
821        assert!(matches!(decode(&m), Err(HandoffError::BadVersion)));
822        let mut m = good.clone();
823        let mid = m.len() / 2;
824        m[mid] ^= 1;
825        assert!(matches!(decode(&m), Err(HandoffError::BadChecksum)));
826        assert!(matches!(
827            decode(&good[..good.len() - 1]),
828            Err(HandoffError::Truncated)
829        ));
830        let mut m = good.clone();
831        m[5] = 65;
832        assert!(matches!(decode(&m), Err(HandoffError::TooMany { max: 64 })));
833        assert!(matches!(decode(&good[..3]), Err(HandoffError::Truncated)));
834    }
835
836    #[test]
837    fn test_long_names_are_cut_at_a_character_boundary() {
838        let r = [Record {
839            kind: SockKind::Tcp("127.0.0.1:1".parse().unwrap()),
840            name: Some("é".repeat(40)),
841        }];
842        let back = decode(&encode(&r)).unwrap();
843        let name = back[0].name.clone().unwrap();
844        assert_eq!(name.len(), 64);
845        assert!(name.chars().all(|c| c == 'é'));
846    }
847
848    /// A connected channel pair in a fresh directory: (sender, receiver).
849    #[cfg(all(unix, feature = "local"))]
850    fn channel(
851        tag: &str,
852    ) -> (
853        crate::local::UnixConnection,
854        crate::local::UnixConnection,
855        std::path::PathBuf,
856    ) {
857        let dir = std::env::temp_dir().join(format!("nio-ho-{}-{tag}", std::process::id()));
858        let _ = std::fs::remove_dir_all(&dir);
859        std::fs::create_dir(&dir).unwrap();
860        let l = crate::local::UnixListener::bind(dir.join("c.sock")).unwrap();
861        let tx = crate::local::UnixConnection::connect(dir.join("c.sock")).unwrap();
862        let (rx, _) = l.accept().unwrap();
863        (tx, rx, dir)
864    }
865
866    #[cfg(all(unix, feature = "local"))]
867    #[test]
868    fn test_count_mismatch_truncation_timeout_and_peer() {
869        use std::os::fd::AsFd;
870        use std::time::{Duration, Instant};
871        let soon = || Instant::now() + Duration::from_secs(5);
872        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
873        let r = Record {
874            kind: SockKind::Tcp(l.local_addr().unwrap()),
875            name: None,
876        };
877        // Edge case 83: the manifest lists two, one socket came.
878        let (mut tx, mut rx, d1) = channel("count");
879        tx.send_descriptors(&encode(&[r.clone(), r.clone()]), &[l.as_fd()])
880            .unwrap();
881        assert!(matches!(
882            recv_listeners(&mut rx, &HandoffPeer::default(), soon()),
883            Err(HandoffError::CountMismatch)
884        ));
885        // Edge case 103: the sender dies mid-message: nothing adopted.
886        let (mut tx, mut rx, d2) = channel("dies");
887        let m = encode(std::slice::from_ref(&r));
888        tx.send_descriptors(&m[..m.len() / 2], &[l.as_fd()])
889            .unwrap();
890        drop(tx);
891        assert!(matches!(
892            recv_listeners(&mut rx, &HandoffPeer::default(), soon()),
893            Err(HandoffError::Truncated)
894        ));
895        // Edge case 102: nothing arrives in time.
896        let (_tx, mut rx, d3) = channel("timeout");
897        let started = Instant::now();
898        assert!(matches!(
899            recv_listeners(
900                &mut rx,
901                &HandoffPeer::default(),
902                Instant::now() + Duration::from_millis(200)
903            ),
904            Err(HandoffError::Timeout)
905        ));
906        assert!(started.elapsed() < Duration::from_secs(3));
907        // The wrong sender.
908        let (_tx, mut rx, d4) = channel("peer");
909        let other = HandoffPeer {
910            uid: Some(sys::effective_uid().wrapping_add(1)),
911            pid: None,
912        };
913        assert!(matches!(
914            recv_listeners(&mut rx, &other, soon()),
915            Err(HandoffError::PeerMismatch)
916        ));
917        let wrong_pid = HandoffPeer {
918            uid: None,
919            pid: Some(1),
920        };
921        assert!(matches!(
922            recv_listeners(&mut rx, &wrong_pid, soon()),
923            Err(HandoffError::PeerMismatch)
924        ));
925        for d in [d1, d2, d3, d4] {
926            let _ = std::fs::remove_dir_all(d);
927        }
928    }
929
930    /// A socket bound elsewhere than the manifest says is refused.
931    #[cfg(all(unix, feature = "local"))]
932    #[test]
933    fn test_address_must_match_the_manifest() {
934        use std::os::fd::AsFd;
935        use std::time::{Duration, Instant};
936        let a = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
937        let b = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
938        let (mut tx, mut rx, dir) = channel("addr");
939        let lie = Record {
940            kind: SockKind::Tcp(b.local_addr().unwrap()),
941            name: None,
942        };
943        tx.send_descriptors(&encode(&[lie]), &[a.as_fd()]).unwrap();
944        assert!(matches!(
945            recv_listeners(
946                &mut rx,
947                &HandoffPeer::default(),
948                Instant::now() + Duration::from_secs(5)
949            ),
950            Err(HandoffError::VerifyFailed { index: 0, .. })
951        ));
952        let _ = std::fs::remove_dir_all(dir);
953    }
954
955    #[test]
956    fn test_handle_verifies_its_socket() {
957        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
958        let addr = l.local_addr().unwrap();
959        let h = ListenerHandle::verified(sys::OwnedSock::from(l), Some("x".into())).unwrap();
960        assert_eq!(h.kind(), Transport::Tcp);
961        assert_eq!(h.local().socket_addr(), Some(addr));
962        assert_eq!(h.name(), Some("x"));
963        let u = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
964        assert!(matches!(
965            ListenerHandle::verified(sys::OwnedSock::from(u), None),
966            Err(KindError::WrongKind)
967        ));
968    }
969
970    /// Edge case 104: the same message twice is refused before any `WSASocketW`.
971    #[cfg(all(windows, feature = "local"))]
972    #[test]
973    fn test_a_hand_off_works_once() {
974        use std::net::TcpListener as Std;
975        use std::time::{Duration, Instant};
976        let std = Std::bind("127.0.0.1:0").unwrap();
977        let addr = std.local_addr().unwrap();
978        let handle =
979            ListenerHandle::verified(sys::OwnedSock::from(std), Some("a".to_owned())).unwrap();
980        let name = format!("net-io-handoff-{}", std::process::id());
981        let listener = crate::pipe::PipeListener::create(&name).unwrap();
982        let mut tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
983        let (mut rx, _) = listener.accept().unwrap();
984        let shared = share_listeners(&[&handle], std::process::id()).unwrap();
985        let frame = shared.frame.clone();
986        tx.send_all(&frame).unwrap();
987        tx.send_all(&frame).unwrap();
988        let until = Instant::now() + Duration::from_secs(5);
989        let peer = HandoffPeer {
990            uid: None,
991            pid: Some(std::process::id()),
992        };
993        let got = receive_shared(&mut rx, &peer, until).unwrap();
994        assert_eq!(got[0].name(), Some("a"));
995        assert_eq!(got[0].local().socket_addr(), Some(addr));
996        assert!(matches!(
997            receive_shared(&mut rx, &peer, until),
998            Err(HandoffError::VerifyFailed { .. })
999        ));
1000    }
1001
1002    #[cfg(all(windows, feature = "local"))]
1003    #[test]
1004    fn test_wrong_peer_and_bad_checksum() {
1005        use std::net::TcpListener as Std;
1006        use std::time::{Duration, Instant};
1007        let std = Std::bind("127.0.0.1:0").unwrap();
1008        let handle = ListenerHandle::verified(sys::OwnedSock::from(std), None).unwrap();
1009        let name = format!("net-io-handoff-b-{}", std::process::id());
1010        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1011        let mut tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1012        let (mut rx, _) = listener.accept().unwrap();
1013        let until = Instant::now() + Duration::from_secs(5);
1014        let wrong = HandoffPeer {
1015            uid: None,
1016            pid: Some(1),
1017        };
1018        assert!(matches!(
1019            receive_shared(&mut rx, &wrong, until),
1020            Err(HandoffError::PeerMismatch)
1021        ));
1022        let mut frame = share_listeners(&[&handle], std::process::id())
1023            .unwrap()
1024            .frame;
1025        let last = frame.len() - 1;
1026        frame[last] ^= 1;
1027        tx.send_all(&frame).unwrap();
1028        assert!(matches!(
1029            receive_shared(&mut rx, &HandoffPeer::default(), until),
1030            Err(HandoffError::BadChecksum)
1031        ));
1032    }
1033
1034    /// A pipe pair for one test, (sender, receiver).
1035    #[cfg(all(windows, feature = "local"))]
1036    fn pipe_pair(tag: &str) -> (crate::pipe::PipeConnection, crate::pipe::PipeConnection) {
1037        use std::time::Duration;
1038        let name = format!("net-io-handoff-{tag}-{}", std::process::id());
1039        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1040        let tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1041        let (rx, _) = listener.accept().unwrap();
1042        (tx, rx)
1043    }
1044
1045    /// A frame as `share_listeners` builds it, from any records and descriptions.
1046    #[cfg(all(windows, feature = "local"))]
1047    fn frame(records: &[Record], blobs: &[[u8; sys::SHARED_SOCKET]]) -> Vec<u8> {
1048        let mut tail = vec![0u8; NONCE];
1049        sys::random_bytes(&mut tail).unwrap();
1050        for b in blobs {
1051            tail.extend_from_slice(b);
1052        }
1053        let mut crc = crate::crc32c::Crc32c::new();
1054        crc.update(&tail);
1055        let mut out = encode(records);
1056        out.extend_from_slice(&tail);
1057        out.extend_from_slice(&crc.finish().to_be_bytes());
1058        out
1059    }
1060
1061    #[cfg(all(windows, feature = "local"))]
1062    fn tcp_record(addr: std::net::SocketAddr) -> Record {
1063        Record {
1064            kind: SockKind::Tcp(addr),
1065            name: None,
1066        }
1067    }
1068
1069    /// The sockets a failed hand-off received, also those after the one that
1070    /// failed, are closed: none keeps listening here.
1071    #[cfg(all(windows, feature = "local"))]
1072    #[test]
1073    fn test_a_failed_hand_off_leaves_no_socket_open() {
1074        use std::net::{TcpListener as Std, TcpStream};
1075        use std::os::windows::io::AsSocket;
1076        use std::time::{Duration, Instant};
1077        let (a, b) = (
1078            Std::bind("127.0.0.1:0").unwrap(),
1079            Std::bind("127.0.0.1:0").unwrap(),
1080        );
1081        let addr_b = b.local_addr().unwrap();
1082        let me = std::process::id();
1083        let blobs = [
1084            sys::share_socket(a.as_socket(), me).unwrap(),
1085            sys::share_socket(b.as_socket(), me).unwrap(),
1086        ];
1087        // The first record names the wrong address.
1088        let records = [tcp_record(addr_b), tcp_record(addr_b)];
1089        let (mut tx, mut rx) = pipe_pair("leak");
1090        tx.send_all(&frame(&records, &blobs)).unwrap();
1091        let until = Instant::now() + Duration::from_secs(5);
1092        assert!(matches!(
1093            receive_shared(&mut rx, &HandoffPeer::default(), until),
1094            Err(HandoffError::VerifyFailed { index: 0, .. })
1095        ));
1096        drop((a, b));
1097        assert!(
1098            TcpStream::connect_timeout(&addr_b, Duration::from_secs(1)).is_err(),
1099            "the second socket still listens in this process"
1100        );
1101    }
1102
1103    /// Fails the test without closing handles that may have two owners.
1104    #[cfg(all(windows, feature = "local"))]
1105    fn refused(got: Result<Vec<ListenerHandle>, HandoffError>) -> HandoffError {
1106        match got {
1107            Ok(handles) => {
1108                std::mem::forget(handles);
1109                panic!("one socket was adopted twice");
1110            }
1111            Err(e) => e,
1112        }
1113    }
1114
1115    /// One description twice in a frame, or again in a later frame with a fresh
1116    /// nonce, would give one socket two owners: refused.
1117    #[cfg(all(windows, feature = "local"))]
1118    #[test]
1119    fn test_a_socket_is_never_adopted_twice() {
1120        use std::net::TcpListener as Std;
1121        use std::os::windows::io::AsSocket;
1122        use std::time::{Duration, Instant};
1123        let a = Std::bind("127.0.0.1:0").unwrap();
1124        let addr = a.local_addr().unwrap();
1125        let me = std::process::id();
1126        let until = Instant::now() + Duration::from_secs(5);
1127        let (mut tx, mut rx) = pipe_pair("twice");
1128
1129        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1130        let records = [tcp_record(addr), tcp_record(addr)];
1131        tx.send_all(&frame(&records, &[blob, blob])).unwrap();
1132        assert!(matches!(
1133            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1134            HandoffError::VerifyFailed { index: 1, .. }
1135        ));
1136
1137        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1138        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1139        let first = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1140        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1141        assert!(matches!(
1142            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1143            HandoffError::VerifyFailed { index: 0, .. }
1144        ));
1145        // Once that socket is closed, a new description of the listener works.
1146        drop(first);
1147        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1148        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1149        let again = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1150        assert_eq!(again[0].local().socket_addr(), Some(addr));
1151    }
1152
1153    /// A received listener is not inherited by processes this one starts.
1154    #[cfg(all(windows, feature = "local"))]
1155    #[test]
1156    fn test_received_sockets_are_not_inheritable() {
1157        use std::net::TcpListener as Std;
1158        use std::os::windows::io::AsSocket;
1159        use std::time::{Duration, Instant};
1160        let a = Std::bind("127.0.0.1:0").unwrap();
1161        let addr = a.local_addr().unwrap();
1162        let (mut tx, mut rx) = pipe_pair("inherit");
1163        let blob = sys::share_socket(a.as_socket(), std::process::id()).unwrap();
1164        tx.send_all(&frame(&[tcp_record(addr)], &[blob])).unwrap();
1165        let until = Instant::now() + Duration::from_secs(5);
1166        let got = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1167        assert!(!sys::is_inheritable(got[0].as_socket()).unwrap());
1168    }
1169
1170    #[cfg(all(windows, feature = "local"))]
1171    #[test]
1172    fn test_nothing_arrives_by_the_deadline() {
1173        use std::time::{Duration, Instant};
1174        let name = format!("net-io-handoff-c-{}", std::process::id());
1175        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1176        let _tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1177        let (mut rx, _) = listener.accept().unwrap();
1178        let until = Instant::now() + Duration::from_millis(50);
1179        assert!(matches!(
1180            receive_shared(&mut rx, &HandoffPeer::default(), until),
1181            Err(HandoffError::Timeout)
1182        ));
1183    }
1184}