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 of the pipe must run as the same user as this one, must have started
643/// before the pipe connected, and must be `expect.pid` when that is set; it is
644/// checked before anything is read. This holds whichever end created the pipe:
645/// when this process dialed, the pipe's security descriptor is the other side's,
646/// so it does not decide who sends. `expect.uid` has no meaning on Windows. The
647/// message must be intact and never seen before, and every socket a listener bound
648/// to the address the manifest names. All or nothing: on any error every received
649/// socket is closed, also those listed after the one that failed. A description
650/// that names a socket this process already owns (the same one twice, one from an
651/// earlier hand-off, or one this process made or adopted any other way) is
652/// refused and that socket is left as it was, so no socket gets two owners and
653/// none is closed. Received sockets are not inheritable.
654///
655/// Windows makes each socket in this process when the sender describes it, so a
656/// message that arrives damaged (`Truncated`, `BadChecksum`, or a bad manifest)
657/// leaves the sockets it described open here, unclaimed, until this process
658/// exits: their descriptions cannot be trusted enough to claim them. Only a
659/// process of the same user can cause that; set `expect.pid` to narrow it to the
660/// one expected sender.
661///
662/// # Errors
663///
664/// `PeerMismatch`, `Timeout`, `Truncated`, `BadMagic`, `BadVersion`, `BadChecksum`,
665/// `TooMany`, `VerifyFailed` (also for a message accepted before), `Os`.
666#[cfg(all(windows, feature = "local"))]
667#[cfg_attr(docsrs, doc(cfg(windows)))]
668pub fn receive_shared(
669    pipe: &mut crate::pipe::PipeConnection,
670    expect: &HandoffPeer,
671    deadline: std::time::Instant,
672) -> Result<Vec<ListenerHandle>, HandoffError> {
673    let peer = pipe.peer_pid().map_err(|_| HandoffError::PeerMismatch)?;
674    if expect.pid.is_some_and(|p| p != peer) {
675        return Err(HandoffError::PeerMismatch);
676    }
677    if !same_user_sender(peer, pipe.info().accepted_at) {
678        return Err(HandoffError::PeerMismatch);
679    }
680    pipe.set_phase(crate::session::Phase::Receiving);
681    pipe.set_exchange_deadline(Some(deadline));
682    let result = read_shared(pipe);
683    pipe.set_exchange_deadline(None);
684    let (records, tail) = result?;
685    let (nonce, blobs) = tail.split_at(NONCE);
686    let nonce: [u8; NONCE] = nonce.try_into().map_err(|_| HandoffError::Truncated)?;
687    adopt_shared(records, nonce, blobs)
688}
689
690/// Whether process `pid` runs as this process's user and started before the pipe
691/// connected at `connected` (so it is not a later process that took the number
692/// of a sender that has exited). A process this one may not query fails.
693#[cfg(all(windows, feature = "local"))]
694fn same_user_sender(pid: u32, connected: std::time::Instant) -> bool {
695    // System clock adjustments move both readings; a second of slack keeps one of
696    // them from refusing a real sender.
697    const SLACK: std::time::Duration = std::time::Duration::from_secs(1);
698    let Ok(ours) = sys::current_user_sid() else {
699        return false;
700    };
701    let Ok((theirs, started)) = sys::process_user_and_start(pid) else {
702        return false;
703    };
704    let Some(latest) = filetime_at(connected).and_then(|t| t.checked_add(ticks(SLACK))) else {
705        return false;
706    };
707    sender_is(&ours, &theirs, started, latest)
708}
709
710/// The rule `same_user_sender` applies: the same user, started no later than
711/// `latest` (both in `FILETIME` units).
712#[cfg(all(windows, feature = "local"))]
713fn sender_is(ours: &str, theirs: &str, started: u64, latest: u64) -> bool {
714    theirs == ours && started <= latest
715}
716
717/// `at` on the system clock, in `FILETIME` units (100 ns since 1601).
718#[cfg(all(windows, feature = "local"))]
719fn filetime_at(at: std::time::Instant) -> Option<u64> {
720    /// 1601 to 1970 in 100 ns units.
721    const EPOCH: u64 = 116_444_736_000_000_000;
722    let ago = std::time::Instant::now().checked_duration_since(at)?;
723    let then = std::time::SystemTime::now()
724        .checked_sub(ago)?
725        .duration_since(std::time::UNIX_EPOCH)
726        .ok()?;
727    ticks(then).checked_add(EPOCH)
728}
729
730#[cfg(all(windows, feature = "local"))]
731fn ticks(d: std::time::Duration) -> u64 {
732    u64::try_from(d.as_nanos() / 100).unwrap_or(u64::MAX)
733}
734
735#[cfg(all(windows, feature = "local"))]
736fn read_shared(
737    pipe: &mut crate::pipe::PipeConnection,
738) -> Result<(Vec<Record>, Vec<u8>), HandoffError> {
739    let mut header = [0u8; HEADER];
740    pipe.recv_exact(&mut header).map_err(handoff_error)?;
741    let (count, total) = parse_header(&header)?;
742    let mut manifest = vec![0u8; total];
743    manifest[..HEADER].copy_from_slice(&header);
744    pipe.recv_exact(&mut manifest[HEADER..])
745        .map_err(handoff_error)?;
746    let records = decode(&manifest)?;
747    let mut tail = vec![0u8; NONCE + count * sys::SHARED_SOCKET + 4];
748    pipe.recv_exact(&mut tail).map_err(handoff_error)?;
749    let check_at = tail.len() - 4;
750    let mut crc = crate::crc32c::Crc32c::new();
751    crc.update(&tail[..check_at]);
752    if crc.finish().to_be_bytes() != tail[check_at..] {
753        return Err(HandoffError::BadChecksum);
754    }
755    tail.truncate(check_at);
756    Ok((records, tail))
757}
758
759#[cfg(all(windows, feature = "local"))]
760fn adopt_shared(
761    records: Vec<Record>,
762    nonce: [u8; NONCE],
763    blobs: &[u8],
764) -> Result<Vec<ListenerHandle>, HandoffError> {
765    {
766        let mut seen = ACCEPTED
767            .lock()
768            .unwrap_or_else(std::sync::PoisonError::into_inner);
769        if seen.contains(&nonce) {
770            return Err(HandoffError::VerifyFailed {
771                index: 0,
772                why: "this hand-off was already accepted",
773            });
774        }
775        seen.push(nonce);
776    }
777    // Every description is claimed before anything is checked: Windows made the
778    // duplicate in this process when the sender described it, so one never turned
779    // into a socket here stays open with no owner. A failure below drops them all.
780    let mut claimed = Vec::with_capacity(records.len());
781    let mut failed = None;
782    for (i, blob) in blobs.chunks_exact(sys::SHARED_SOCKET).enumerate() {
783        let index = i as u8;
784        let got = <&[u8; sys::SHARED_SOCKET]>::try_from(blob)
785            .map_err(|_| HandoffError::Truncated)
786            .and_then(|blob| {
787                sys::socket_from_shared(blob).map_err(|e| match e.kind() {
788                    io::ErrorKind::AlreadyExists => HandoffError::VerifyFailed {
789                        index,
790                        why: "names a socket this process already owns",
791                    },
792                    _ => HandoffError::Os(e),
793                })
794            });
795        match got {
796            Ok(sock) => claimed.push(sock),
797            Err(e) => {
798                failed.get_or_insert(e);
799            }
800        }
801    }
802    if let Some(e) = failed {
803        return Err(e);
804    }
805    if claimed.len() != records.len() {
806        return Err(HandoffError::CountMismatch);
807    }
808    let mut handles = Vec::with_capacity(records.len());
809    for (i, (record, (sock, adoption))) in records.into_iter().zip(claimed).enumerate() {
810        let index = i as u8;
811        let got = sys::listener_kind(sys::AsSock::sock(&sock)).map_err(|e| {
812            HandoffError::VerifyFailed {
813                index,
814                why: why(&e),
815            }
816        })?;
817        if got != record.kind {
818            return Err(HandoffError::VerifyFailed {
819                index,
820                why: "bound to another address than the manifest says",
821            });
822        }
823        let (kind, local) = endpoint_of(got).map_err(|e| HandoffError::VerifyFailed {
824            index,
825            why: why(&e),
826        })?;
827        let mut handle = ListenerHandle::new(kind, record.name, local, sock);
828        handle.adopted = Some(adoption);
829        handles.push(handle);
830    }
831    Ok(handles)
832}
833
834#[cfg(test)]
835mod tests {
836    use super::*;
837
838    fn records() -> Vec<Record> {
839        #[cfg_attr(not(unix), allow(unused_mut))]
840        let mut v = vec![
841            Record {
842                kind: SockKind::Tcp("127.0.0.1:8080".parse().unwrap()),
843                name: Some("web".into()),
844            },
845            Record {
846                kind: SockKind::Tcp("[2001:db8::1]:443".parse().unwrap()),
847                name: None,
848            },
849        ];
850        #[cfg(unix)]
851        v.push(Record {
852            kind: SockKind::Unix(b"/run/app/api.sock".to_vec()),
853            name: Some("api".into()),
854        });
855        v
856    }
857
858    #[test]
859    fn test_manifest_round_trips() {
860        let r = records();
861        assert_eq!(decode(&encode(&r)).unwrap(), r);
862        assert_eq!(decode(&encode(&[])).unwrap(), Vec::new());
863    }
864
865    #[test]
866    fn test_manifest_rejects_damage() {
867        let good = encode(&records());
868        let mut m = good.clone();
869        m[0] = b'X';
870        assert!(matches!(decode(&m), Err(HandoffError::BadMagic)));
871        let mut m = good.clone();
872        m[4] = 2;
873        assert!(matches!(decode(&m), Err(HandoffError::BadVersion)));
874        let mut m = good.clone();
875        let mid = m.len() / 2;
876        m[mid] ^= 1;
877        assert!(matches!(decode(&m), Err(HandoffError::BadChecksum)));
878        assert!(matches!(
879            decode(&good[..good.len() - 1]),
880            Err(HandoffError::Truncated)
881        ));
882        let mut m = good.clone();
883        m[5] = 65;
884        assert!(matches!(decode(&m), Err(HandoffError::TooMany { max: 64 })));
885        assert!(matches!(decode(&good[..3]), Err(HandoffError::Truncated)));
886    }
887
888    #[test]
889    fn test_long_names_are_cut_at_a_character_boundary() {
890        let r = [Record {
891            kind: SockKind::Tcp("127.0.0.1:1".parse().unwrap()),
892            name: Some("é".repeat(40)),
893        }];
894        let back = decode(&encode(&r)).unwrap();
895        let name = back[0].name.clone().unwrap();
896        assert_eq!(name.len(), 64);
897        assert!(name.chars().all(|c| c == 'é'));
898    }
899
900    /// A connected channel pair in a fresh directory: (sender, receiver).
901    #[cfg(all(unix, feature = "local"))]
902    fn channel(
903        tag: &str,
904    ) -> (
905        crate::local::UnixConnection,
906        crate::local::UnixConnection,
907        std::path::PathBuf,
908    ) {
909        let dir = std::env::temp_dir().join(format!("nio-ho-{}-{tag}", std::process::id()));
910        let _ = std::fs::remove_dir_all(&dir);
911        std::fs::create_dir(&dir).unwrap();
912        let l = crate::local::UnixListener::bind(dir.join("c.sock")).unwrap();
913        let tx = crate::local::UnixConnection::connect(dir.join("c.sock")).unwrap();
914        let (rx, _) = l.accept().unwrap();
915        (tx, rx, dir)
916    }
917
918    #[cfg(all(unix, feature = "local"))]
919    #[test]
920    fn test_count_mismatch_truncation_timeout_and_peer() {
921        use std::os::fd::AsFd;
922        use std::time::{Duration, Instant};
923        let soon = || Instant::now() + Duration::from_secs(5);
924        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
925        let r = Record {
926            kind: SockKind::Tcp(l.local_addr().unwrap()),
927            name: None,
928        };
929        // Edge case 83: the manifest lists two, one socket came.
930        let (mut tx, mut rx, d1) = channel("count");
931        tx.send_descriptors(&encode(&[r.clone(), r.clone()]), &[l.as_fd()])
932            .unwrap();
933        assert!(matches!(
934            recv_listeners(&mut rx, &HandoffPeer::default(), soon()),
935            Err(HandoffError::CountMismatch)
936        ));
937        // Edge case 103: the sender dies mid-message: nothing adopted.
938        let (mut tx, mut rx, d2) = channel("dies");
939        let m = encode(std::slice::from_ref(&r));
940        tx.send_descriptors(&m[..m.len() / 2], &[l.as_fd()])
941            .unwrap();
942        drop(tx);
943        assert!(matches!(
944            recv_listeners(&mut rx, &HandoffPeer::default(), soon()),
945            Err(HandoffError::Truncated)
946        ));
947        // Edge case 102: nothing arrives in time.
948        let (_tx, mut rx, d3) = channel("timeout");
949        let started = Instant::now();
950        assert!(matches!(
951            recv_listeners(
952                &mut rx,
953                &HandoffPeer::default(),
954                Instant::now() + Duration::from_millis(200)
955            ),
956            Err(HandoffError::Timeout)
957        ));
958        assert!(started.elapsed() < Duration::from_secs(3));
959        // The wrong sender.
960        let (_tx, mut rx, d4) = channel("peer");
961        let other = HandoffPeer {
962            uid: Some(sys::effective_uid().wrapping_add(1)),
963            pid: None,
964        };
965        assert!(matches!(
966            recv_listeners(&mut rx, &other, soon()),
967            Err(HandoffError::PeerMismatch)
968        ));
969        let wrong_pid = HandoffPeer {
970            uid: None,
971            pid: Some(1),
972        };
973        assert!(matches!(
974            recv_listeners(&mut rx, &wrong_pid, soon()),
975            Err(HandoffError::PeerMismatch)
976        ));
977        for d in [d1, d2, d3, d4] {
978            let _ = std::fs::remove_dir_all(d);
979        }
980    }
981
982    /// A socket bound elsewhere than the manifest says is refused.
983    #[cfg(all(unix, feature = "local"))]
984    #[test]
985    fn test_address_must_match_the_manifest() {
986        use std::os::fd::AsFd;
987        use std::time::{Duration, Instant};
988        let a = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
989        let b = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
990        let (mut tx, mut rx, dir) = channel("addr");
991        let lie = Record {
992            kind: SockKind::Tcp(b.local_addr().unwrap()),
993            name: None,
994        };
995        tx.send_descriptors(&encode(&[lie]), &[a.as_fd()]).unwrap();
996        assert!(matches!(
997            recv_listeners(
998                &mut rx,
999                &HandoffPeer::default(),
1000                Instant::now() + Duration::from_secs(5)
1001            ),
1002            Err(HandoffError::VerifyFailed { index: 0, .. })
1003        ));
1004        let _ = std::fs::remove_dir_all(dir);
1005    }
1006
1007    #[test]
1008    fn test_handle_verifies_its_socket() {
1009        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1010        let addr = l.local_addr().unwrap();
1011        let h = ListenerHandle::verified(sys::OwnedSock::from(l), Some("x".into())).unwrap();
1012        assert_eq!(h.kind(), Transport::Tcp);
1013        assert_eq!(h.local().socket_addr(), Some(addr));
1014        assert_eq!(h.name(), Some("x"));
1015        let u = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1016        assert!(matches!(
1017            ListenerHandle::verified(sys::OwnedSock::from(u), None),
1018            Err(KindError::WrongKind)
1019        ));
1020    }
1021
1022    /// Edge case 104: the same message twice is refused before any `WSASocketW`.
1023    #[cfg(all(windows, feature = "local"))]
1024    #[test]
1025    fn test_a_hand_off_works_once() {
1026        use std::net::TcpListener as Std;
1027        use std::time::{Duration, Instant};
1028        let std = Std::bind("127.0.0.1:0").unwrap();
1029        let addr = std.local_addr().unwrap();
1030        let handle =
1031            ListenerHandle::verified(sys::OwnedSock::from(std), Some("a".to_owned())).unwrap();
1032        let name = format!("net-io-handoff-{}", std::process::id());
1033        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1034        let mut tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1035        let (mut rx, _) = listener.accept().unwrap();
1036        let shared = share_listeners(&[&handle], std::process::id()).unwrap();
1037        let frame = shared.frame.clone();
1038        tx.send_all(&frame).unwrap();
1039        tx.send_all(&frame).unwrap();
1040        let until = Instant::now() + Duration::from_secs(5);
1041        let peer = HandoffPeer {
1042            uid: None,
1043            pid: Some(std::process::id()),
1044        };
1045        let got = receive_shared(&mut rx, &peer, until).unwrap();
1046        assert_eq!(got[0].name(), Some("a"));
1047        assert_eq!(got[0].local().socket_addr(), Some(addr));
1048        assert!(matches!(
1049            receive_shared(&mut rx, &peer, until),
1050            Err(HandoffError::VerifyFailed { .. })
1051        ));
1052    }
1053
1054    #[cfg(all(windows, feature = "local"))]
1055    #[test]
1056    fn test_wrong_peer_and_bad_checksum() {
1057        use std::net::TcpListener as Std;
1058        use std::time::{Duration, Instant};
1059        let std = Std::bind("127.0.0.1:0").unwrap();
1060        let handle = ListenerHandle::verified(sys::OwnedSock::from(std), None).unwrap();
1061        let name = format!("net-io-handoff-b-{}", std::process::id());
1062        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1063        let mut tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1064        let (mut rx, _) = listener.accept().unwrap();
1065        let until = Instant::now() + Duration::from_secs(5);
1066        let wrong = HandoffPeer {
1067            uid: None,
1068            pid: Some(1),
1069        };
1070        assert!(matches!(
1071            receive_shared(&mut rx, &wrong, until),
1072            Err(HandoffError::PeerMismatch)
1073        ));
1074        let mut frame = share_listeners(&[&handle], std::process::id())
1075            .unwrap()
1076            .frame;
1077        let last = frame.len() - 1;
1078        frame[last] ^= 1;
1079        tx.send_all(&frame).unwrap();
1080        assert!(matches!(
1081            receive_shared(&mut rx, &HandoffPeer::default(), until),
1082            Err(HandoffError::BadChecksum)
1083        ));
1084    }
1085
1086    /// A pipe pair for one test, (sender, receiver).
1087    #[cfg(all(windows, feature = "local"))]
1088    fn pipe_pair(tag: &str) -> (crate::pipe::PipeConnection, crate::pipe::PipeConnection) {
1089        use std::time::Duration;
1090        let name = format!("net-io-handoff-{tag}-{}", std::process::id());
1091        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1092        let tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1093        let (rx, _) = listener.accept().unwrap();
1094        (tx, rx)
1095    }
1096
1097    /// A frame as `share_listeners` builds it, from any records and descriptions.
1098    #[cfg(all(windows, feature = "local"))]
1099    fn frame(records: &[Record], blobs: &[[u8; sys::SHARED_SOCKET]]) -> Vec<u8> {
1100        let mut tail = vec![0u8; NONCE];
1101        sys::random_bytes(&mut tail).unwrap();
1102        for b in blobs {
1103            tail.extend_from_slice(b);
1104        }
1105        let mut crc = crate::crc32c::Crc32c::new();
1106        crc.update(&tail);
1107        let mut out = encode(records);
1108        out.extend_from_slice(&tail);
1109        out.extend_from_slice(&crc.finish().to_be_bytes());
1110        out
1111    }
1112
1113    #[cfg(all(windows, feature = "local"))]
1114    fn tcp_record(addr: std::net::SocketAddr) -> Record {
1115        Record {
1116            kind: SockKind::Tcp(addr),
1117            name: None,
1118        }
1119    }
1120
1121    /// The sockets a failed hand-off received, also those after the one that
1122    /// failed, are closed: none keeps listening here.
1123    #[cfg(all(windows, feature = "local"))]
1124    #[test]
1125    fn test_a_failed_hand_off_leaves_no_socket_open() {
1126        use std::net::{TcpListener as Std, TcpStream};
1127        use std::os::windows::io::AsSocket;
1128        use std::time::{Duration, Instant};
1129        let (a, b) = (
1130            Std::bind("127.0.0.1:0").unwrap(),
1131            Std::bind("127.0.0.1:0").unwrap(),
1132        );
1133        let addr_b = b.local_addr().unwrap();
1134        let me = std::process::id();
1135        let blobs = [
1136            sys::share_socket(a.as_socket(), me).unwrap(),
1137            sys::share_socket(b.as_socket(), me).unwrap(),
1138        ];
1139        // The first record names the wrong address.
1140        let records = [tcp_record(addr_b), tcp_record(addr_b)];
1141        let (mut tx, mut rx) = pipe_pair("leak");
1142        tx.send_all(&frame(&records, &blobs)).unwrap();
1143        let until = Instant::now() + Duration::from_secs(5);
1144        assert!(matches!(
1145            receive_shared(&mut rx, &HandoffPeer::default(), until),
1146            Err(HandoffError::VerifyFailed { index: 0, .. })
1147        ));
1148        drop((a, b));
1149        assert!(
1150            TcpStream::connect_timeout(&addr_b, Duration::from_secs(1)).is_err(),
1151            "the second socket still listens in this process"
1152        );
1153    }
1154
1155    /// Fails the test without closing handles that may have two owners.
1156    #[cfg(all(windows, feature = "local"))]
1157    fn refused(got: Result<Vec<ListenerHandle>, HandoffError>) -> HandoffError {
1158        match got {
1159            Ok(handles) => {
1160                std::mem::forget(handles);
1161                panic!("one socket was adopted twice");
1162            }
1163            Err(e) => e,
1164        }
1165    }
1166
1167    /// One description twice in a frame, or again in a later frame with a fresh
1168    /// nonce, would give one socket two owners: refused.
1169    #[cfg(all(windows, feature = "local"))]
1170    #[test]
1171    fn test_a_socket_is_never_adopted_twice() {
1172        use std::net::TcpListener as Std;
1173        use std::os::windows::io::AsSocket;
1174        use std::time::{Duration, Instant};
1175        let a = Std::bind("127.0.0.1:0").unwrap();
1176        let addr = a.local_addr().unwrap();
1177        let me = std::process::id();
1178        let until = Instant::now() + Duration::from_secs(5);
1179        let (mut tx, mut rx) = pipe_pair("twice");
1180
1181        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1182        let records = [tcp_record(addr), tcp_record(addr)];
1183        tx.send_all(&frame(&records, &[blob, blob])).unwrap();
1184        assert!(matches!(
1185            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1186            HandoffError::VerifyFailed { index: 1, .. }
1187        ));
1188
1189        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1190        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1191        let first = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1192        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1193        assert!(matches!(
1194            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1195            HandoffError::VerifyFailed { index: 0, .. }
1196        ));
1197        // Once that socket is closed, a new description of the listener works.
1198        drop(first);
1199        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1200        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1201        let again = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1202        assert_eq!(again[0].local().socket_addr(), Some(addr));
1203    }
1204
1205    /// A received listener is not inherited by processes this one starts.
1206    #[cfg(all(windows, feature = "local"))]
1207    #[test]
1208    fn test_received_sockets_are_not_inheritable() {
1209        use std::net::TcpListener as Std;
1210        use std::os::windows::io::AsSocket;
1211        use std::time::{Duration, Instant};
1212        let a = Std::bind("127.0.0.1:0").unwrap();
1213        let addr = a.local_addr().unwrap();
1214        let (mut tx, mut rx) = pipe_pair("inherit");
1215        let blob = sys::share_socket(a.as_socket(), std::process::id()).unwrap();
1216        tx.send_all(&frame(&[tcp_record(addr)], &[blob])).unwrap();
1217        let until = Instant::now() + Duration::from_secs(5);
1218        let got = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1219        assert!(!sys::is_inheritable(got[0].as_socket()).unwrap());
1220    }
1221
1222    /// A description from `share_socket` with the handle value it names here
1223    /// changed to `to`.
1224    #[cfg(all(windows, feature = "local"))]
1225    fn naming(to: usize) -> [u8; sys::SHARED_SOCKET] {
1226        use std::os::windows::io::AsSocket;
1227        let decoy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1228        let mut blob = sys::share_socket(decoy.as_socket(), std::process::id()).unwrap();
1229        // `dwProviderReserved`: the socket's handle value in the receiving process.
1230        blob[112..116].copy_from_slice(&u32::try_from(to).unwrap().to_ne_bytes());
1231        blob
1232    }
1233
1234    /// A description that names a socket this process made itself is refused, and
1235    /// that socket is neither taken nor closed.
1236    #[cfg(all(windows, feature = "local"))]
1237    #[test]
1238    fn test_a_description_naming_a_socket_owned_here_is_refused() {
1239        use std::os::windows::io::AsRawSocket;
1240        let victim = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1241        let raw = usize::try_from(victim.as_raw_socket()).unwrap();
1242        match sys::socket_from_shared(&naming(raw)) {
1243            Ok((sock, adoption)) => {
1244                let same = sock.as_raw_socket() == victim.as_raw_socket();
1245                std::mem::forget((sock, adoption));
1246                panic!("adopted a socket owned here (same handle: {same})");
1247            }
1248            Err(e) => assert_eq!(e.kind(), io::ErrorKind::AlreadyExists),
1249        }
1250        let addr = victim.local_addr().unwrap();
1251        let _c = std::net::TcpStream::connect(addr).expect("the socket still listens");
1252        assert!(victim.accept().is_ok());
1253    }
1254
1255    /// Through `receive_shared`: a frame that names the receiver's own listener at
1256    /// its real address is refused, and one whose check would fail does not close
1257    /// that listener.
1258    #[cfg(all(windows, feature = "local"))]
1259    #[test]
1260    fn test_a_forged_hand_off_neither_adopts_nor_closes_a_listener_here() {
1261        use std::os::windows::io::AsRawSocket;
1262        use std::time::{Duration, Instant};
1263        let victim = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1264        let addr = victim.local_addr().unwrap();
1265        let raw = usize::try_from(victim.as_raw_socket()).unwrap();
1266        let until = Instant::now() + Duration::from_secs(5);
1267        let (mut tx, mut rx) = pipe_pair("forged");
1268        tx.send_all(&frame(&[tcp_record(addr)], &[naming(raw)]))
1269            .unwrap();
1270        assert!(matches!(
1271            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1272            HandoffError::VerifyFailed { index: 0, .. }
1273        ));
1274        let wrong: std::net::SocketAddr = "127.0.0.1:1".parse().unwrap();
1275        tx.send_all(&frame(&[tcp_record(wrong)], &[naming(raw)]))
1276            .unwrap();
1277        assert!(receive_shared(&mut rx, &HandoffPeer::default(), until).is_err());
1278        let _c = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(2))
1279            .expect("the listener survived");
1280        assert!(victim.accept().is_ok());
1281    }
1282
1283    /// Descriptions naming handles that are not sockets (a file, the channel's own
1284    /// pipe) leave those handles working.
1285    #[cfg(all(windows, feature = "local"))]
1286    #[test]
1287    fn test_a_forged_hand_off_leaves_other_handles_alone() {
1288        use std::io::{Read, Seek};
1289        use std::os::windows::io::AsRawHandle;
1290        use std::time::{Duration, Instant};
1291        let mut file = std::fs::File::open(std::env::current_exe().unwrap()).unwrap();
1292        let (mut tx, mut rx) = pipe_pair("others");
1293        let channel = rx.raw_handle() as usize;
1294        let any: std::net::SocketAddr = "127.0.0.1:1".parse().unwrap();
1295        let blobs = [naming(file.as_raw_handle() as usize), naming(channel)];
1296        tx.send_all(&frame(&[tcp_record(any), tcp_record(any)], &blobs))
1297            .unwrap();
1298        let until = Instant::now() + Duration::from_secs(5);
1299        assert!(receive_shared(&mut rx, &HandoffPeer::default(), until).is_err());
1300        let mut buf = [0u8; 2];
1301        file.rewind().unwrap();
1302        assert!(file.read(&mut buf).is_ok(), "the file was closed");
1303        tx.send_all(b"hi").unwrap();
1304        rx.recv_exact(&mut buf).expect("the channel was closed");
1305        assert_eq!(&buf, b"hi");
1306    }
1307
1308    /// The sender must run as this user and must have started before the pipe
1309    /// connected.
1310    #[cfg(all(windows, feature = "local"))]
1311    #[test]
1312    fn test_only_a_sender_of_this_user_that_was_already_running_is_accepted() {
1313        use std::time::{Duration, Instant};
1314        assert!(same_user_sender(std::process::id(), Instant::now()));
1315        // The system process runs as another account.
1316        assert!(!same_user_sender(4, Instant::now()));
1317        // A connection time in the future cannot be placed on the clock: refused.
1318        assert!(!same_user_sender(
1319            std::process::id(),
1320            Instant::now() + Duration::from_secs(60)
1321        ));
1322        // A process that started after the pipe connected took a number that
1323        // belonged to someone else. (No child process here: one started while
1324        // another test holds a fresh, still inheritable duplicate would keep it.)
1325        let me = sys::current_user_sid().unwrap();
1326        assert!(sender_is(&me, &me, 100, 100));
1327        assert!(!sender_is(&me, &me, 101, 100));
1328        assert!(!sender_is(&me, "S-1-5-18", 100, 100));
1329        let now = filetime_at(Instant::now()).unwrap();
1330        let earlier = filetime_at(Instant::now().checked_sub(Duration::from_secs(5)).unwrap());
1331        assert!(earlier.unwrap() < now);
1332    }
1333
1334    #[cfg(all(windows, feature = "local"))]
1335    #[test]
1336    fn test_nothing_arrives_by_the_deadline() {
1337        use std::time::{Duration, Instant};
1338        let name = format!("net-io-handoff-c-{}", std::process::id());
1339        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1340        let _tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1341        let (mut rx, _) = listener.accept().unwrap();
1342        let until = Instant::now() + Duration::from_millis(50);
1343        assert!(matches!(
1344            receive_shared(&mut rx, &HandoffPeer::default(), until),
1345            Err(HandoffError::Timeout)
1346        ));
1347    }
1348}