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}
116
117impl ListenerHandle {
118    /// Verifies `sock` (a listening stream socket of a family net-io serves) and
119    /// records its endpoint.
120    #[cfg_attr(not(unix), allow(dead_code))]
121    pub(crate) fn verified(
122        sock: sys::OwnedSock,
123        name: Option<String>,
124    ) -> Result<ListenerHandle, KindError> {
125        let kind = sys::listener_kind(sys::AsSock::sock(&sock))?;
126        let (kind, local) = endpoint_of(kind)?;
127        Ok(ListenerHandle::new(kind, name, local, sock))
128    }
129
130    pub(crate) fn new(
131        kind: Transport,
132        name: Option<String>,
133        local: Endpoint,
134        sock: sys::OwnedSock,
135    ) -> ListenerHandle {
136        ListenerHandle {
137            kind,
138            name,
139            local,
140            sock,
141        }
142    }
143
144    pub(crate) fn into_sock(self) -> sys::OwnedSock {
145        self.sock
146    }
147
148    /// TCP or Unix.
149    #[must_use]
150    pub fn kind(&self) -> Transport {
151        self.kind
152    }
153
154    /// The name it was given (systemd's `LISTEN_FDNAMES`, a listener's name).
155    #[must_use]
156    pub fn name(&self) -> Option<&str> {
157        self.name.as_deref()
158    }
159
160    /// The address it is bound to.
161    #[must_use]
162    pub fn local(&self) -> &Endpoint {
163        &self.local
164    }
165}
166
167/// The transport and endpoint of a verified socket.
168fn endpoint_of(kind: SockKind) -> Result<(Transport, Endpoint), KindError> {
169    match kind {
170        SockKind::Tcp(a) => Ok((Transport::Tcp, Endpoint::Ip(a))),
171        #[cfg(unix)]
172        SockKind::Unix(path) => {
173            if !cfg!(feature = "local") {
174                return Err(KindError::WrongKind);
175            }
176            let local = UnixPath::new(&path)
177                .filter(|_| !path.is_empty())
178                .map_or(Endpoint::Unnamed, |p| Endpoint::Unix(Arc::new(p)));
179            Ok((Transport::Unix, local))
180        }
181    }
182}
183
184impl fmt::Debug for ListenerHandle {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        f.debug_struct("ListenerHandle")
187            .field("kind", &self.kind)
188            .field("name", &self.name)
189            .field("local", &self.local)
190            .finish()
191    }
192}
193
194#[cfg(unix)]
195impl std::os::fd::AsFd for ListenerHandle {
196    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
197        self.sock.as_fd()
198    }
199}
200
201#[cfg(windows)]
202impl std::os::windows::io::AsSocket for ListenerHandle {
203    fn as_socket(&self) -> std::os::windows::io::BorrowedSocket<'_> {
204        self.sock.as_socket()
205    }
206}
207
208/// Whom `recv_listeners` accepts listeners from. `uid: None` means this
209/// process's own effective user id; `pid: None` accepts any process of that user.
210///
211/// ```
212/// let only_parent = net_io::HandoffPeer { uid: None, pid: Some(1234) };
213/// # let _ = only_parent;
214/// ```
215#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
216pub struct HandoffPeer {
217    /// The sender's user id (`None`: ours).
218    pub uid: Option<u32>,
219    /// The sender's process id (`None`: any).
220    pub pid: Option<u32>,
221}
222
223const MAGIC: [u8; 4] = *b"NIOH";
224const VERSION: u8 = 1;
225const HEADER: usize = 8;
226/// The most listeners one hand-off carries (one `SCM_RIGHTS` message).
227const MAX_LISTENERS: usize = 64;
228/// The longest name carried; longer names are cut at a character boundary.
229const MAX_NAME: usize = 64;
230
231/// One listener as the manifest describes it.
232#[derive(Clone, Debug, PartialEq, Eq)]
233struct Record {
234    kind: SockKind,
235    name: Option<String>,
236}
237
238/// Encodes the manifest for `records`.
239fn encode(records: &[Record]) -> Vec<u8> {
240    let mut out = Vec::with_capacity(HEADER + records.len() * 96 + 4);
241    out.extend_from_slice(&MAGIC);
242    out.push(VERSION);
243    out.push(records.len() as u8);
244    out.extend_from_slice(&[0, 0]); // total length, filled in below
245    for r in records {
246        let mut name = r.name.as_deref().unwrap_or("");
247        if name.len() > MAX_NAME {
248            let mut cut = MAX_NAME;
249            while !name.is_char_boundary(cut) {
250                cut -= 1;
251            }
252            name = &name[..cut];
253        }
254        let mut addr = Vec::with_capacity(32);
255        let kind = match &r.kind {
256            SockKind::Tcp(a) => {
257                match a.ip() {
258                    std::net::IpAddr::V4(ip) => {
259                        addr.push(4);
260                        addr.extend_from_slice(&ip.octets());
261                    }
262                    std::net::IpAddr::V6(ip) => {
263                        addr.push(6);
264                        addr.extend_from_slice(&ip.octets());
265                    }
266                }
267                addr.extend_from_slice(&a.port().to_be_bytes());
268                1u8
269            }
270            #[cfg(unix)]
271            SockKind::Unix(path) => {
272                addr.extend_from_slice(path);
273                2u8
274            }
275        };
276        out.push(kind);
277        out.push(name.len() as u8);
278        out.extend_from_slice(name.as_bytes());
279        out.extend_from_slice(&(addr.len() as u16).to_be_bytes());
280        out.extend_from_slice(&addr);
281    }
282    let total = (out.len() + 4) as u16;
283    out[6..8].copy_from_slice(&total.to_be_bytes());
284    let mut crc = crate::crc32c::Crc32c::new();
285    crc.update(&out);
286    out.extend_from_slice(&crc.finish().to_be_bytes());
287    out
288}
289
290/// Checks the header: magic, version, count, total length.
291fn parse_header(h: &[u8; HEADER]) -> Result<(usize, usize), HandoffError> {
292    if h[..4] != MAGIC {
293        return Err(HandoffError::BadMagic);
294    }
295    if h[4] != VERSION {
296        return Err(HandoffError::BadVersion);
297    }
298    let count = usize::from(h[5]);
299    if count > MAX_LISTENERS {
300        return Err(HandoffError::TooMany {
301            max: MAX_LISTENERS as u8,
302        });
303    }
304    let total = usize::from(u16::from_be_bytes([h[6], h[7]]));
305    if total < HEADER + 4 {
306        return Err(HandoffError::Truncated);
307    }
308    Ok((count, total))
309}
310
311/// Parses a whole manifest (header included).
312fn decode(bytes: &[u8]) -> Result<Vec<Record>, HandoffError> {
313    let header: &[u8; HEADER] = bytes
314        .get(..HEADER)
315        .and_then(|h| h.try_into().ok())
316        .ok_or(HandoffError::Truncated)?;
317    let (count, total) = parse_header(header)?;
318    if bytes.len() != total {
319        return Err(HandoffError::Truncated);
320    }
321    let (body, sum) = bytes.split_at(total - 4);
322    let mut crc = crate::crc32c::Crc32c::new();
323    crc.update(body);
324    if crc.finish().to_be_bytes() != sum {
325        return Err(HandoffError::BadChecksum);
326    }
327    let mut at = HEADER;
328    let mut take = |n: usize| -> Result<&[u8], HandoffError> {
329        let s = body.get(at..at + n).ok_or(HandoffError::Truncated)?;
330        at += n;
331        Ok(s)
332    };
333    let mut records = Vec::with_capacity(count);
334    for i in 0..count {
335        let bad = |why| HandoffError::VerifyFailed {
336            index: i as u8,
337            why,
338        };
339        let kind = take(1)?[0];
340        let name_len = usize::from(take(1)?[0]);
341        if name_len > MAX_NAME {
342            return Err(bad("name longer than 64 bytes"));
343        }
344        let name = std::str::from_utf8(take(name_len)?)
345            .map_err(|_| bad("name is not UTF-8"))?
346            .to_owned();
347        let addr_len = take(2)?;
348        let addr_len = usize::from(u16::from_be_bytes([addr_len[0], addr_len[1]]));
349        let addr = take(addr_len)?;
350        let kind = match (kind, addr) {
351            (1, [4, a, b, c, d, p0, p1]) => SockKind::Tcp(std::net::SocketAddr::from((
352                [*a, *b, *c, *d],
353                u16::from_be_bytes([*p0, *p1]),
354            ))),
355            (1, [6, rest @ ..]) if rest.len() == 18 => {
356                let mut ip = [0u8; 16];
357                ip.copy_from_slice(&rest[..16]);
358                SockKind::Tcp(std::net::SocketAddr::from((
359                    ip,
360                    u16::from_be_bytes([rest[16], rest[17]]),
361                )))
362            }
363            #[cfg(unix)]
364            (2, path) => SockKind::Unix(path.to_vec()),
365            _ => return Err(bad("unknown kind or malformed address")),
366        };
367        records.push(Record {
368            kind,
369            name: (!name.is_empty()).then_some(name),
370        });
371    }
372    if at != body.len() {
373        return Err(HandoffError::Truncated);
374    }
375    Ok(records)
376}
377
378/// The fuzz target's entry: decoding never panics, and an accepted manifest
379/// encodes back to the same bytes.
380#[cfg(fuzzing)]
381pub(crate) fn fuzz_manifest(data: &[u8]) {
382    if let Ok(records) = decode(data) {
383        assert_eq!(encode(&records), data);
384    }
385}
386
387/// Sends `listeners` over `channel` in one message: the manifest and every
388/// socket (`SCM_RIGHTS`). The listeners stay open here; the receiver gets its
389/// own copies. At most 64.
390///
391/// # Errors
392///
393/// `TooMany`, `Timeout`, `Os`.
394#[cfg(all(unix, feature = "local"))]
395pub fn send_listeners(
396    channel: &mut crate::local::UnixConnection,
397    listeners: &[&ListenerHandle],
398) -> Result<(), HandoffError> {
399    use std::os::fd::AsFd;
400    if listeners.len() > MAX_LISTENERS {
401        return Err(HandoffError::TooMany {
402            max: MAX_LISTENERS as u8,
403        });
404    }
405    let mut records = Vec::with_capacity(listeners.len());
406    for (i, l) in listeners.iter().enumerate() {
407        let kind = sys::listener_kind(l.as_fd()).map_err(|e| HandoffError::VerifyFailed {
408            index: i as u8,
409            why: why(&e),
410        })?;
411        records.push(Record {
412            kind,
413            name: l.name.clone(),
414        });
415    }
416    let manifest = encode(&records);
417    let fds: Vec<_> = listeners.iter().map(|l| l.as_fd()).collect();
418    channel
419        .send_descriptors(&manifest, &fds)
420        .map_err(handoff_error)
421}
422
423/// Receives listeners from `channel`. The sender's credentials must match
424/// `expect` (by default: the same user); the message must be complete, intact
425/// (magic, version, CRC32C), carry exactly as many sockets as it lists, and
426/// every socket must be a listener bound to the address the manifest names.
427/// All or nothing: on any error every received socket is closed.
428///
429/// # Errors
430///
431/// `PeerMismatch`, `Timeout` (nothing arrived by `deadline`), `Truncated` (the
432/// sender closed mid-message or the control data was cut), `BadMagic`,
433/// `BadVersion`, `BadChecksum`, `CountMismatch`, `TooMany`, `VerifyFailed`, `Os`.
434#[cfg(all(unix, feature = "local"))]
435pub fn recv_listeners(
436    channel: &mut crate::local::UnixConnection,
437    expect: &HandoffPeer,
438    deadline: std::time::Instant,
439) -> Result<Vec<ListenerHandle>, HandoffError> {
440    use crate::local::Descriptors;
441    let creds = channel
442        .peer_credentials()
443        .map_err(|_| HandoffError::PeerMismatch)?;
444    let uid = expect.uid.unwrap_or_else(sys::effective_uid);
445    if creds.uid != Some(uid) || expect.pid.is_some_and(|p| creds.pid != Some(p)) {
446        return Err(HandoffError::PeerMismatch);
447    }
448    channel.set_phase(crate::session::Phase::Receiving);
449    channel.set_exchange_deadline(Some(deadline));
450    let result = receive(channel);
451    channel.set_exchange_deadline(None);
452    let (records, mut fds): (Vec<Record>, Descriptors) = result?;
453    if fds.len() != records.len() {
454        return Err(HandoffError::CountMismatch);
455    }
456    let mut handles = Vec::with_capacity(records.len());
457    for (i, (record, fd)) in records.into_iter().zip(fds.take()).enumerate() {
458        let index = i as u8;
459        let got = sys::listener_kind(std::os::fd::AsFd::as_fd(&fd)).map_err(|e| {
460            HandoffError::VerifyFailed {
461                index,
462                why: why(&e),
463            }
464        })?;
465        if got != record.kind {
466            return Err(HandoffError::VerifyFailed {
467                index,
468                why: "bound to another address than the manifest says",
469            });
470        }
471        let (kind, local) = endpoint_of(got).map_err(|e| HandoffError::VerifyFailed {
472            index,
473            why: why(&e),
474        })?;
475        handles.push(ListenerHandle::new(kind, record.name, local, fd));
476    }
477    Ok(handles)
478}
479
480/// Reads the manifest and its descriptors.
481#[cfg(all(unix, feature = "local"))]
482fn receive(
483    channel: &mut crate::local::UnixConnection,
484) -> Result<(Vec<Record>, crate::local::Descriptors), HandoffError> {
485    use crate::local::Descriptors;
486    let mut fds = Descriptors::new();
487    let mut header = [0u8; HEADER];
488    let mut got = 0;
489    while got < HEADER {
490        // The descriptors travel with the first byte; a later read must bring none.
491        let mut extra = Descriptors::new();
492        let into = if got == 0 { &mut fds } else { &mut extra };
493        let n = channel
494            .recv_descriptors(&mut header[got..], into)
495            .map_err(handoff_error)?;
496        if n == 0 {
497            return Err(HandoffError::Truncated);
498        }
499        if !extra.is_empty() {
500            return Err(HandoffError::CountMismatch);
501        }
502        got += n;
503    }
504    let (_, total) = parse_header(&header)?;
505    let mut manifest = vec![0u8; total];
506    manifest[..HEADER].copy_from_slice(&header);
507    let mut at = HEADER;
508    while at < total {
509        let mut extra = Descriptors::new();
510        let n = channel
511            .recv_descriptors(&mut manifest[at..], &mut extra)
512            .map_err(handoff_error)?;
513        if n == 0 {
514            return Err(HandoffError::Truncated);
515        }
516        if !extra.is_empty() {
517            return Err(HandoffError::CountMismatch);
518        }
519        at += n;
520    }
521    let records = decode(&manifest)?;
522    Ok((records, fds))
523}
524
525#[cfg(feature = "local")]
526fn handoff_error(e: crate::error::NetError) -> HandoffError {
527    use crate::error::NetError;
528    match e {
529        NetError::TimedOut { .. } => HandoffError::Timeout,
530        NetError::Handoff(h) => h,
531        NetError::Closed => HandoffError::Truncated,
532        other => HandoffError::Os(io::Error::from(other)),
533    }
534}
535
536fn why(e: &KindError) -> &'static str {
537    match e {
538        KindError::NotASocket => "not a socket",
539        KindError::NotListening => "not listening",
540        KindError::WrongKind => "not a TCP or Unix stream listener",
541        KindError::Os(_) => "could not be inspected",
542    }
543}
544
545/// Listeners described for one process, ready to go over a pipe once.
546///
547/// ```no_run
548/// use net_io::{PipeConnection, share_listeners};
549/// # fn f(handles: Vec<net_io::ListenerHandle>, pid: u32, mut pipe: PipeConnection)
550/// #     -> Result<(), net_io::HandoffError> {
551/// let shared = share_listeners(&handles.iter().collect::<Vec<_>>(), pid)?;
552/// shared.write_to(&mut pipe)?;
553/// # Ok(())
554/// # }
555/// ```
556#[cfg(all(windows, feature = "local"))]
557#[cfg_attr(docsrs, doc(cfg(windows)))]
558pub struct SharedListeners {
559    frame: Vec<u8>,
560}
561
562#[cfg(all(windows, feature = "local"))]
563impl std::fmt::Debug for SharedListeners {
564    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565        f.debug_struct("SharedListeners").finish_non_exhaustive()
566    }
567}
568
569#[cfg(all(windows, feature = "local"))]
570const NONCE: usize = 16;
571
572/// Nonces this process has accepted. Windows lets a description be used twice and
573/// returns the same socket; this makes it once.
574#[cfg(all(windows, feature = "local"))]
575static ACCEPTED: std::sync::Mutex<Vec<[u8; NONCE]>> = std::sync::Mutex::new(Vec::new());
576
577/// Describes `listeners` for the process `target_pid`. Each description works in that
578/// process alone. Send them over a pipe with an owner-only security descriptor, which
579/// is what [`PipeListener::create`](crate::PipeListener::create) makes.
580///
581/// # Errors
582///
583/// `TooMany`, `VerifyFailed`, `Os`.
584#[cfg(all(windows, feature = "local"))]
585#[cfg_attr(docsrs, doc(cfg(windows)))]
586pub fn share_listeners(
587    listeners: &[&ListenerHandle],
588    target_pid: u32,
589) -> Result<SharedListeners, HandoffError> {
590    use std::os::windows::io::AsSocket;
591    if listeners.len() > MAX_LISTENERS {
592        return Err(HandoffError::TooMany {
593            max: MAX_LISTENERS as u8,
594        });
595    }
596    let mut records = Vec::with_capacity(listeners.len());
597    let mut tail = vec![0u8; NONCE];
598    sys::random_bytes(&mut tail).map_err(HandoffError::Os)?;
599    for (i, l) in listeners.iter().enumerate() {
600        let kind = sys::listener_kind(l.as_socket()).map_err(|e| HandoffError::VerifyFailed {
601            index: i as u8,
602            why: why(&e),
603        })?;
604        records.push(Record {
605            kind,
606            name: l.name.clone(),
607        });
608        let blob = sys::share_socket(l.as_socket(), target_pid).map_err(HandoffError::Os)?;
609        tail.extend_from_slice(&blob);
610    }
611    let mut crc = crate::crc32c::Crc32c::new();
612    crc.update(&tail);
613    let check = crc.finish().to_be_bytes();
614    let mut frame = encode(&records);
615    frame.extend_from_slice(&tail);
616    frame.extend_from_slice(&check);
617    Ok(SharedListeners { frame })
618}
619
620#[cfg(all(windows, feature = "local"))]
621impl SharedListeners {
622    /// Sends the listeners; consumed, so they go once.
623    ///
624    /// # Errors
625    ///
626    /// `Timeout`, `Truncated`, `Os`.
627    pub fn write_to(self, pipe: &mut crate::pipe::PipeConnection) -> Result<(), HandoffError> {
628        pipe.send_all(&self.frame).map_err(handoff_error)
629    }
630}
631
632/// Receives listeners sent with [`SharedListeners::write_to`]. The process at the
633/// far end of the pipe must run as the same user as this one, must have started
634/// before the pipe connected, and must be `expect.pid` when that is set; it is
635/// checked before anything is read. This holds whichever end created the pipe:
636/// when this process dialed, the pipe's security descriptor is the other side's,
637/// so it does not decide who sends. `expect.uid` has no meaning on Windows. The
638/// message must be intact and never seen before, and every socket a listener bound
639/// to the address the manifest names. All or nothing: on any error every received
640/// socket is closed, also those listed after the one that failed. A description
641/// that names a socket this process already owns (the same one twice, one from an
642/// earlier hand-off, or any other socket that is not inheritable, which every
643/// socket net-io and std make is) is refused and that socket is left as it was,
644/// so no socket gets two owners and none is closed. Received sockets are not
645/// inheritable. Once such a socket is closed, its handle value may name a socket
646/// of a later hand-off, which is taken as any other.
647///
648/// Windows makes each socket in this process when the sender describes it, so a
649/// message that arrives damaged (`Truncated`, `BadChecksum`, or a bad manifest)
650/// leaves the sockets it described open here, unclaimed, until this process
651/// exits: their descriptions cannot be trusted enough to claim them. Only a
652/// process of the same user can cause that; set `expect.pid` to narrow it to the
653/// one expected sender.
654///
655/// # Errors
656///
657/// `PeerMismatch`, `Timeout`, `Truncated`, `BadMagic`, `BadVersion`, `BadChecksum`,
658/// `TooMany`, `VerifyFailed` (also for a message accepted before), `Os`.
659#[cfg(all(windows, feature = "local"))]
660#[cfg_attr(docsrs, doc(cfg(windows)))]
661pub fn receive_shared(
662    pipe: &mut crate::pipe::PipeConnection,
663    expect: &HandoffPeer,
664    deadline: std::time::Instant,
665) -> Result<Vec<ListenerHandle>, HandoffError> {
666    let peer = pipe.peer_pid().map_err(|_| HandoffError::PeerMismatch)?;
667    if expect.pid.is_some_and(|p| p != peer) {
668        return Err(HandoffError::PeerMismatch);
669    }
670    if !same_user_sender(peer, pipe.info().accepted_at) {
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/// Whether process `pid` runs as this process's user and started before the pipe
684/// connected at `connected` (so it is not a later process that took the number
685/// of a sender that has exited). A process this one may not query fails.
686#[cfg(all(windows, feature = "local"))]
687fn same_user_sender(pid: u32, connected: std::time::Instant) -> bool {
688    // System clock adjustments move both readings; a second of slack keeps one of
689    // them from refusing a real sender.
690    const SLACK: std::time::Duration = std::time::Duration::from_secs(1);
691    let Ok(ours) = sys::current_user_sid() else {
692        return false;
693    };
694    let Ok((theirs, started)) = sys::process_user_and_start(pid) else {
695        return false;
696    };
697    let Some(latest) = filetime_at(connected).and_then(|t| t.checked_add(ticks(SLACK))) else {
698        return false;
699    };
700    sender_is(&ours, &theirs, started, latest)
701}
702
703/// The rule `same_user_sender` applies: the same user, started no later than
704/// `latest` (both in `FILETIME` units).
705#[cfg(all(windows, feature = "local"))]
706fn sender_is(ours: &str, theirs: &str, started: u64, latest: u64) -> bool {
707    theirs == ours && started <= latest
708}
709
710/// `at` on the system clock, in `FILETIME` units (100 ns since 1601).
711#[cfg(all(windows, feature = "local"))]
712fn filetime_at(at: std::time::Instant) -> Option<u64> {
713    /// 1601 to 1970 in 100 ns units.
714    const EPOCH: u64 = 116_444_736_000_000_000;
715    let ago = std::time::Instant::now().checked_duration_since(at)?;
716    let then = std::time::SystemTime::now()
717        .checked_sub(ago)?
718        .duration_since(std::time::UNIX_EPOCH)
719        .ok()?;
720    ticks(then).checked_add(EPOCH)
721}
722
723#[cfg(all(windows, feature = "local"))]
724fn ticks(d: std::time::Duration) -> u64 {
725    u64::try_from(d.as_nanos() / 100).unwrap_or(u64::MAX)
726}
727
728#[cfg(all(windows, feature = "local"))]
729fn read_shared(
730    pipe: &mut crate::pipe::PipeConnection,
731) -> Result<(Vec<Record>, Vec<u8>), HandoffError> {
732    let mut header = [0u8; HEADER];
733    pipe.recv_exact(&mut header).map_err(handoff_error)?;
734    let (count, total) = parse_header(&header)?;
735    let mut manifest = vec![0u8; total];
736    manifest[..HEADER].copy_from_slice(&header);
737    pipe.recv_exact(&mut manifest[HEADER..])
738        .map_err(handoff_error)?;
739    let records = decode(&manifest)?;
740    let mut tail = vec![0u8; NONCE + count * sys::SHARED_SOCKET + 4];
741    pipe.recv_exact(&mut tail).map_err(handoff_error)?;
742    let check_at = tail.len() - 4;
743    let mut crc = crate::crc32c::Crc32c::new();
744    crc.update(&tail[..check_at]);
745    if crc.finish().to_be_bytes() != tail[check_at..] {
746        return Err(HandoffError::BadChecksum);
747    }
748    tail.truncate(check_at);
749    Ok((records, tail))
750}
751
752#[cfg(all(windows, feature = "local"))]
753fn adopt_shared(
754    records: Vec<Record>,
755    nonce: [u8; NONCE],
756    blobs: &[u8],
757) -> Result<Vec<ListenerHandle>, HandoffError> {
758    {
759        let mut seen = ACCEPTED
760            .lock()
761            .unwrap_or_else(std::sync::PoisonError::into_inner);
762        if seen.contains(&nonce) {
763            return Err(HandoffError::VerifyFailed {
764                index: 0,
765                why: "this hand-off was already accepted",
766            });
767        }
768        seen.push(nonce);
769    }
770    // Every description is claimed before anything is checked: Windows made the
771    // duplicate in this process when the sender described it, so one never turned
772    // into a socket here stays open with no owner. A failure below drops them all.
773    let mut claimed = Vec::with_capacity(records.len());
774    let mut failed = None;
775    for (i, blob) in blobs.chunks_exact(sys::SHARED_SOCKET).enumerate() {
776        let index = i as u8;
777        let got = <&[u8; sys::SHARED_SOCKET]>::try_from(blob)
778            .map_err(|_| HandoffError::Truncated)
779            .and_then(|blob| {
780                sys::socket_from_shared(blob).map_err(|e| match e.kind() {
781                    io::ErrorKind::AlreadyExists => HandoffError::VerifyFailed {
782                        index,
783                        why: "names a socket this process already owns",
784                    },
785                    _ => HandoffError::Os(e),
786                })
787            });
788        match got {
789            Ok(sock) => claimed.push(sock),
790            Err(e) => {
791                failed.get_or_insert(e);
792            }
793        }
794    }
795    if let Some(e) = failed {
796        return Err(e);
797    }
798    if claimed.len() != records.len() {
799        return Err(HandoffError::CountMismatch);
800    }
801    let mut handles = Vec::with_capacity(records.len());
802    for (i, (record, sock)) in records.into_iter().zip(claimed).enumerate() {
803        let index = i as u8;
804        let got = sys::listener_kind(sys::AsSock::sock(&sock)).map_err(|e| {
805            HandoffError::VerifyFailed {
806                index,
807                why: why(&e),
808            }
809        })?;
810        if got != record.kind {
811            return Err(HandoffError::VerifyFailed {
812                index,
813                why: "bound to another address than the manifest says",
814            });
815        }
816        let (kind, local) = endpoint_of(got).map_err(|e| HandoffError::VerifyFailed {
817            index,
818            why: why(&e),
819        })?;
820        handles.push(ListenerHandle::new(kind, record.name, local, sock));
821    }
822    Ok(handles)
823}
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828
829    fn records() -> Vec<Record> {
830        #[cfg_attr(not(unix), allow(unused_mut))]
831        let mut v = vec![
832            Record {
833                kind: SockKind::Tcp("127.0.0.1:8080".parse().unwrap()),
834                name: Some("web".into()),
835            },
836            Record {
837                kind: SockKind::Tcp("[2001:db8::1]:443".parse().unwrap()),
838                name: None,
839            },
840        ];
841        #[cfg(unix)]
842        v.push(Record {
843            kind: SockKind::Unix(b"/run/app/api.sock".to_vec()),
844            name: Some("api".into()),
845        });
846        v
847    }
848
849    #[test]
850    fn test_manifest_round_trips() {
851        let r = records();
852        assert_eq!(decode(&encode(&r)).unwrap(), r);
853        assert_eq!(decode(&encode(&[])).unwrap(), Vec::new());
854    }
855
856    #[test]
857    fn test_manifest_rejects_damage() {
858        let good = encode(&records());
859        let mut m = good.clone();
860        m[0] = b'X';
861        assert!(matches!(decode(&m), Err(HandoffError::BadMagic)));
862        let mut m = good.clone();
863        m[4] = 2;
864        assert!(matches!(decode(&m), Err(HandoffError::BadVersion)));
865        let mut m = good.clone();
866        let mid = m.len() / 2;
867        m[mid] ^= 1;
868        assert!(matches!(decode(&m), Err(HandoffError::BadChecksum)));
869        assert!(matches!(
870            decode(&good[..good.len() - 1]),
871            Err(HandoffError::Truncated)
872        ));
873        let mut m = good.clone();
874        m[5] = 65;
875        assert!(matches!(decode(&m), Err(HandoffError::TooMany { max: 64 })));
876        assert!(matches!(decode(&good[..3]), Err(HandoffError::Truncated)));
877    }
878
879    #[test]
880    fn test_long_names_are_cut_at_a_character_boundary() {
881        let r = [Record {
882            kind: SockKind::Tcp("127.0.0.1:1".parse().unwrap()),
883            name: Some("é".repeat(40)),
884        }];
885        let back = decode(&encode(&r)).unwrap();
886        let name = back[0].name.clone().unwrap();
887        assert_eq!(name.len(), 64);
888        assert!(name.chars().all(|c| c == 'é'));
889    }
890
891    /// A connected channel pair in a fresh directory: (sender, receiver).
892    #[cfg(all(unix, feature = "local"))]
893    fn channel(
894        tag: &str,
895    ) -> (
896        crate::local::UnixConnection,
897        crate::local::UnixConnection,
898        std::path::PathBuf,
899    ) {
900        let dir = std::env::temp_dir().join(format!("nio-ho-{}-{tag}", std::process::id()));
901        let _ = std::fs::remove_dir_all(&dir);
902        std::fs::create_dir(&dir).unwrap();
903        let l = crate::local::UnixListener::bind(dir.join("c.sock")).unwrap();
904        let tx = crate::local::UnixConnection::connect(dir.join("c.sock")).unwrap();
905        let (rx, _) = l.accept().unwrap();
906        (tx, rx, dir)
907    }
908
909    #[cfg(all(unix, feature = "local"))]
910    #[test]
911    fn test_count_mismatch_truncation_timeout_and_peer() {
912        use std::os::fd::AsFd;
913        use std::time::{Duration, Instant};
914        let soon = || Instant::now() + Duration::from_secs(5);
915        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
916        let r = Record {
917            kind: SockKind::Tcp(l.local_addr().unwrap()),
918            name: None,
919        };
920        // Edge case 83: the manifest lists two, one socket came.
921        let (mut tx, mut rx, d1) = channel("count");
922        tx.send_descriptors(&encode(&[r.clone(), r.clone()]), &[l.as_fd()])
923            .unwrap();
924        assert!(matches!(
925            recv_listeners(&mut rx, &HandoffPeer::default(), soon()),
926            Err(HandoffError::CountMismatch)
927        ));
928        // Edge case 103: the sender dies mid-message: nothing adopted.
929        let (mut tx, mut rx, d2) = channel("dies");
930        let m = encode(std::slice::from_ref(&r));
931        tx.send_descriptors(&m[..m.len() / 2], &[l.as_fd()])
932            .unwrap();
933        drop(tx);
934        assert!(matches!(
935            recv_listeners(&mut rx, &HandoffPeer::default(), soon()),
936            Err(HandoffError::Truncated)
937        ));
938        // Edge case 102: nothing arrives in time.
939        let (_tx, mut rx, d3) = channel("timeout");
940        let started = Instant::now();
941        assert!(matches!(
942            recv_listeners(
943                &mut rx,
944                &HandoffPeer::default(),
945                Instant::now() + Duration::from_millis(200)
946            ),
947            Err(HandoffError::Timeout)
948        ));
949        assert!(started.elapsed() < Duration::from_secs(3));
950        // The wrong sender.
951        let (_tx, mut rx, d4) = channel("peer");
952        let other = HandoffPeer {
953            uid: Some(sys::effective_uid().wrapping_add(1)),
954            pid: None,
955        };
956        assert!(matches!(
957            recv_listeners(&mut rx, &other, soon()),
958            Err(HandoffError::PeerMismatch)
959        ));
960        let wrong_pid = HandoffPeer {
961            uid: None,
962            pid: Some(1),
963        };
964        assert!(matches!(
965            recv_listeners(&mut rx, &wrong_pid, soon()),
966            Err(HandoffError::PeerMismatch)
967        ));
968        for d in [d1, d2, d3, d4] {
969            let _ = std::fs::remove_dir_all(d);
970        }
971    }
972
973    /// A socket bound elsewhere than the manifest says is refused.
974    #[cfg(all(unix, feature = "local"))]
975    #[test]
976    fn test_address_must_match_the_manifest() {
977        use std::os::fd::AsFd;
978        use std::time::{Duration, Instant};
979        let a = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
980        let b = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
981        let (mut tx, mut rx, dir) = channel("addr");
982        let lie = Record {
983            kind: SockKind::Tcp(b.local_addr().unwrap()),
984            name: None,
985        };
986        tx.send_descriptors(&encode(&[lie]), &[a.as_fd()]).unwrap();
987        assert!(matches!(
988            recv_listeners(
989                &mut rx,
990                &HandoffPeer::default(),
991                Instant::now() + Duration::from_secs(5)
992            ),
993            Err(HandoffError::VerifyFailed { index: 0, .. })
994        ));
995        let _ = std::fs::remove_dir_all(dir);
996    }
997
998    #[test]
999    fn test_handle_verifies_its_socket() {
1000        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1001        let addr = l.local_addr().unwrap();
1002        let h = ListenerHandle::verified(sys::OwnedSock::from(l), Some("x".into())).unwrap();
1003        assert_eq!(h.kind(), Transport::Tcp);
1004        assert_eq!(h.local().socket_addr(), Some(addr));
1005        assert_eq!(h.name(), Some("x"));
1006        let u = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1007        assert!(matches!(
1008            ListenerHandle::verified(sys::OwnedSock::from(u), None),
1009            Err(KindError::WrongKind)
1010        ));
1011    }
1012
1013    /// Edge case 104: the same message twice is refused before any `WSASocketW`.
1014    #[cfg(all(windows, feature = "local"))]
1015    #[test]
1016    fn test_a_hand_off_works_once() {
1017        use std::net::TcpListener as Std;
1018        use std::time::{Duration, Instant};
1019        let std = Std::bind("127.0.0.1:0").unwrap();
1020        let addr = std.local_addr().unwrap();
1021        let handle =
1022            ListenerHandle::verified(sys::OwnedSock::from(std), Some("a".to_owned())).unwrap();
1023        let name = format!("net-io-handoff-{}", std::process::id());
1024        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1025        let mut tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1026        let (mut rx, _) = listener.accept().unwrap();
1027        let shared = share_listeners(&[&handle], std::process::id()).unwrap();
1028        let frame = shared.frame.clone();
1029        tx.send_all(&frame).unwrap();
1030        tx.send_all(&frame).unwrap();
1031        let until = Instant::now() + Duration::from_secs(5);
1032        let peer = HandoffPeer {
1033            uid: None,
1034            pid: Some(std::process::id()),
1035        };
1036        let got = receive_shared(&mut rx, &peer, until).unwrap();
1037        assert_eq!(got[0].name(), Some("a"));
1038        assert_eq!(got[0].local().socket_addr(), Some(addr));
1039        assert!(matches!(
1040            receive_shared(&mut rx, &peer, until),
1041            Err(HandoffError::VerifyFailed { .. })
1042        ));
1043    }
1044
1045    #[cfg(all(windows, feature = "local"))]
1046    #[test]
1047    fn test_wrong_peer_and_bad_checksum() {
1048        use std::net::TcpListener as Std;
1049        use std::time::{Duration, Instant};
1050        let std = Std::bind("127.0.0.1:0").unwrap();
1051        let handle = ListenerHandle::verified(sys::OwnedSock::from(std), None).unwrap();
1052        let name = format!("net-io-handoff-b-{}", std::process::id());
1053        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1054        let mut tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1055        let (mut rx, _) = listener.accept().unwrap();
1056        let until = Instant::now() + Duration::from_secs(5);
1057        let wrong = HandoffPeer {
1058            uid: None,
1059            pid: Some(1),
1060        };
1061        assert!(matches!(
1062            receive_shared(&mut rx, &wrong, until),
1063            Err(HandoffError::PeerMismatch)
1064        ));
1065        let mut frame = share_listeners(&[&handle], std::process::id())
1066            .unwrap()
1067            .frame;
1068        let last = frame.len() - 1;
1069        frame[last] ^= 1;
1070        tx.send_all(&frame).unwrap();
1071        assert!(matches!(
1072            receive_shared(&mut rx, &HandoffPeer::default(), until),
1073            Err(HandoffError::BadChecksum)
1074        ));
1075    }
1076
1077    /// A pipe pair for one test, (sender, receiver).
1078    #[cfg(all(windows, feature = "local"))]
1079    fn pipe_pair(tag: &str) -> (crate::pipe::PipeConnection, crate::pipe::PipeConnection) {
1080        use std::time::Duration;
1081        let name = format!("net-io-handoff-{tag}-{}", std::process::id());
1082        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1083        let tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1084        let (rx, _) = listener.accept().unwrap();
1085        (tx, rx)
1086    }
1087
1088    /// A frame as `share_listeners` builds it, from any records and descriptions.
1089    #[cfg(all(windows, feature = "local"))]
1090    fn frame(records: &[Record], blobs: &[[u8; sys::SHARED_SOCKET]]) -> Vec<u8> {
1091        let mut tail = vec![0u8; NONCE];
1092        sys::random_bytes(&mut tail).unwrap();
1093        for b in blobs {
1094            tail.extend_from_slice(b);
1095        }
1096        let mut crc = crate::crc32c::Crc32c::new();
1097        crc.update(&tail);
1098        let mut out = encode(records);
1099        out.extend_from_slice(&tail);
1100        out.extend_from_slice(&crc.finish().to_be_bytes());
1101        out
1102    }
1103
1104    #[cfg(all(windows, feature = "local"))]
1105    fn tcp_record(addr: std::net::SocketAddr) -> Record {
1106        Record {
1107            kind: SockKind::Tcp(addr),
1108            name: None,
1109        }
1110    }
1111
1112    /// The sockets a failed hand-off received, also those after the one that
1113    /// failed, are closed: none keeps listening here.
1114    #[cfg(all(windows, feature = "local"))]
1115    #[test]
1116    fn test_a_failed_hand_off_leaves_no_socket_open() {
1117        use std::net::{TcpListener as Std, TcpStream};
1118        use std::os::windows::io::AsSocket;
1119        use std::time::{Duration, Instant};
1120        let (a, b) = (
1121            Std::bind("127.0.0.1:0").unwrap(),
1122            Std::bind("127.0.0.1:0").unwrap(),
1123        );
1124        let addr_b = b.local_addr().unwrap();
1125        let me = std::process::id();
1126        let blobs = [
1127            sys::share_socket(a.as_socket(), me).unwrap(),
1128            sys::share_socket(b.as_socket(), me).unwrap(),
1129        ];
1130        // The first record names the wrong address.
1131        let records = [tcp_record(addr_b), tcp_record(addr_b)];
1132        let (mut tx, mut rx) = pipe_pair("leak");
1133        tx.send_all(&frame(&records, &blobs)).unwrap();
1134        let until = Instant::now() + Duration::from_secs(5);
1135        assert!(matches!(
1136            receive_shared(&mut rx, &HandoffPeer::default(), until),
1137            Err(HandoffError::VerifyFailed { index: 0, .. })
1138        ));
1139        drop((a, b));
1140        assert!(
1141            TcpStream::connect_timeout(&addr_b, Duration::from_secs(1)).is_err(),
1142            "the second socket still listens in this process"
1143        );
1144    }
1145
1146    /// Fails the test without closing handles that may have two owners.
1147    #[cfg(all(windows, feature = "local"))]
1148    fn refused(got: Result<Vec<ListenerHandle>, HandoffError>) -> HandoffError {
1149        match got {
1150            Ok(handles) => {
1151                std::mem::forget(handles);
1152                panic!("one socket was adopted twice");
1153            }
1154            Err(e) => e,
1155        }
1156    }
1157
1158    /// One description twice in a frame, or again in a later frame with a fresh
1159    /// nonce, would give one socket two owners: refused.
1160    #[cfg(all(windows, feature = "local"))]
1161    #[test]
1162    fn test_a_socket_is_never_adopted_twice() {
1163        use std::net::TcpListener as Std;
1164        use std::os::windows::io::AsSocket;
1165        use std::time::{Duration, Instant};
1166        let a = Std::bind("127.0.0.1:0").unwrap();
1167        let addr = a.local_addr().unwrap();
1168        let me = std::process::id();
1169        let until = Instant::now() + Duration::from_secs(5);
1170        let (mut tx, mut rx) = pipe_pair("twice");
1171
1172        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1173        let records = [tcp_record(addr), tcp_record(addr)];
1174        tx.send_all(&frame(&records, &[blob, blob])).unwrap();
1175        assert!(matches!(
1176            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1177            HandoffError::VerifyFailed { index: 1, .. }
1178        ));
1179
1180        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1181        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1182        let first = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1183        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1184        assert!(matches!(
1185            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1186            HandoffError::VerifyFailed { index: 0, .. }
1187        ));
1188        // Once that socket is closed, a new description of the listener works.
1189        drop(first);
1190        let blob = sys::share_socket(a.as_socket(), me).unwrap();
1191        tx.send_all(&frame(&records[..1], &[blob])).unwrap();
1192        let again = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1193        assert_eq!(again[0].local().socket_addr(), Some(addr));
1194    }
1195
1196    /// A socket taken by a hand-off and later closed by its new owner frees its
1197    /// handle value: a genuine hand-off whose socket gets that value again is taken.
1198    #[cfg(all(windows, feature = "local"))]
1199    #[test]
1200    fn test_a_value_freed_after_a_hand_off_can_be_taken_again() {
1201        use std::net::TcpListener as Std;
1202        use std::os::windows::io::{AsRawSocket, AsSocket};
1203        use std::time::{Duration, Instant};
1204        let (mut tx, mut rx) = pipe_pair("reuse");
1205        let me = std::process::id();
1206        let mut seen = std::collections::HashSet::new();
1207        let mut reused = 0;
1208        for round in 0..32 {
1209            let a = Std::bind("127.0.0.1:0").unwrap();
1210            let addr = a.local_addr().unwrap();
1211            let blob = sys::share_socket(a.as_socket(), me).unwrap();
1212            tx.send_all(&frame(&[tcp_record(addr)], &[blob])).unwrap();
1213            let until = Instant::now() + Duration::from_secs(5);
1214            let mut got = match receive_shared(&mut rx, &HandoffPeer::default(), until) {
1215                Ok(got) => got,
1216                Err(e) => panic!("round {round} ({reused} values reused): {e}"),
1217            };
1218            // As `ListenerSpec::adopt` does: the socket moves to a new owner.
1219            let sock = got.remove(0).into_sock();
1220            if !seen.insert(sock.as_raw_socket()) {
1221                reused += 1;
1222            }
1223            drop(sock);
1224        }
1225        eprintln!("{reused} handle values came back");
1226    }
1227
1228    /// A received listener is not inherited by processes this one starts.
1229    #[cfg(all(windows, feature = "local"))]
1230    #[test]
1231    fn test_received_sockets_are_not_inheritable() {
1232        use std::net::TcpListener as Std;
1233        use std::os::windows::io::AsSocket;
1234        use std::time::{Duration, Instant};
1235        let a = Std::bind("127.0.0.1:0").unwrap();
1236        let addr = a.local_addr().unwrap();
1237        let (mut tx, mut rx) = pipe_pair("inherit");
1238        let blob = sys::share_socket(a.as_socket(), std::process::id()).unwrap();
1239        tx.send_all(&frame(&[tcp_record(addr)], &[blob])).unwrap();
1240        let until = Instant::now() + Duration::from_secs(5);
1241        let got = receive_shared(&mut rx, &HandoffPeer::default(), until).unwrap();
1242        assert!(!sys::is_inheritable(got[0].as_socket()).unwrap());
1243    }
1244
1245    /// A description from `share_socket` with the handle value it names here
1246    /// changed to `to`.
1247    #[cfg(all(windows, feature = "local"))]
1248    fn naming(to: usize) -> [u8; sys::SHARED_SOCKET] {
1249        use std::os::windows::io::AsSocket;
1250        let decoy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1251        let mut blob = sys::share_socket(decoy.as_socket(), std::process::id()).unwrap();
1252        // `dwProviderReserved`: the socket's handle value in the receiving process.
1253        blob[112..116].copy_from_slice(&u32::try_from(to).unwrap().to_ne_bytes());
1254        blob
1255    }
1256
1257    /// A description that names a socket this process made itself is refused, and
1258    /// that socket is neither taken nor closed.
1259    #[cfg(all(windows, feature = "local"))]
1260    #[test]
1261    fn test_a_description_naming_a_socket_owned_here_is_refused() {
1262        use std::os::windows::io::AsRawSocket;
1263        let victim = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1264        let raw = usize::try_from(victim.as_raw_socket()).unwrap();
1265        match sys::socket_from_shared(&naming(raw)) {
1266            Ok(sock) => {
1267                let same = sock.as_raw_socket() == victim.as_raw_socket();
1268                std::mem::forget(sock);
1269                panic!("adopted a socket owned here (same handle: {same})");
1270            }
1271            Err(e) => assert_eq!(e.kind(), io::ErrorKind::AlreadyExists),
1272        }
1273        let addr = victim.local_addr().unwrap();
1274        let _c = std::net::TcpStream::connect(addr).expect("the socket still listens");
1275        assert!(victim.accept().is_ok());
1276    }
1277
1278    /// Through `receive_shared`: a frame that names the receiver's own listener at
1279    /// its real address is refused, and one whose check would fail does not close
1280    /// that listener.
1281    #[cfg(all(windows, feature = "local"))]
1282    #[test]
1283    fn test_a_forged_hand_off_neither_adopts_nor_closes_a_listener_here() {
1284        use std::os::windows::io::AsRawSocket;
1285        use std::time::{Duration, Instant};
1286        let victim = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1287        let addr = victim.local_addr().unwrap();
1288        let raw = usize::try_from(victim.as_raw_socket()).unwrap();
1289        let until = Instant::now() + Duration::from_secs(5);
1290        let (mut tx, mut rx) = pipe_pair("forged");
1291        tx.send_all(&frame(&[tcp_record(addr)], &[naming(raw)]))
1292            .unwrap();
1293        assert!(matches!(
1294            refused(receive_shared(&mut rx, &HandoffPeer::default(), until)),
1295            HandoffError::VerifyFailed { index: 0, .. }
1296        ));
1297        let wrong: std::net::SocketAddr = "127.0.0.1:1".parse().unwrap();
1298        tx.send_all(&frame(&[tcp_record(wrong)], &[naming(raw)]))
1299            .unwrap();
1300        assert!(receive_shared(&mut rx, &HandoffPeer::default(), until).is_err());
1301        let _c = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(2))
1302            .expect("the listener survived");
1303        assert!(victim.accept().is_ok());
1304    }
1305
1306    /// Descriptions naming handles that are not sockets (a file, the channel's own
1307    /// pipe) leave those handles working.
1308    #[cfg(all(windows, feature = "local"))]
1309    #[test]
1310    fn test_a_forged_hand_off_leaves_other_handles_alone() {
1311        use std::io::{Read, Seek};
1312        use std::os::windows::io::AsRawHandle;
1313        use std::time::{Duration, Instant};
1314        let mut file = std::fs::File::open(std::env::current_exe().unwrap()).unwrap();
1315        let (mut tx, mut rx) = pipe_pair("others");
1316        let channel = rx.raw_handle() as usize;
1317        let any: std::net::SocketAddr = "127.0.0.1:1".parse().unwrap();
1318        let blobs = [naming(file.as_raw_handle() as usize), naming(channel)];
1319        tx.send_all(&frame(&[tcp_record(any), tcp_record(any)], &blobs))
1320            .unwrap();
1321        let until = Instant::now() + Duration::from_secs(5);
1322        assert!(receive_shared(&mut rx, &HandoffPeer::default(), until).is_err());
1323        let mut buf = [0u8; 2];
1324        file.rewind().unwrap();
1325        assert!(file.read(&mut buf).is_ok(), "the file was closed");
1326        tx.send_all(b"hi").unwrap();
1327        rx.recv_exact(&mut buf).expect("the channel was closed");
1328        assert_eq!(&buf, b"hi");
1329    }
1330
1331    /// The sender must run as this user and must have started before the pipe
1332    /// connected.
1333    #[cfg(all(windows, feature = "local"))]
1334    #[test]
1335    fn test_only_a_sender_of_this_user_that_was_already_running_is_accepted() {
1336        use std::time::{Duration, Instant};
1337        assert!(same_user_sender(std::process::id(), Instant::now()));
1338        // The system process runs as another account.
1339        assert!(!same_user_sender(4, Instant::now()));
1340        // A connection time in the future cannot be placed on the clock: refused.
1341        assert!(!same_user_sender(
1342            std::process::id(),
1343            Instant::now() + Duration::from_secs(60)
1344        ));
1345        // A process that started after the pipe connected took a number that
1346        // belonged to someone else. (No child process here: one started while
1347        // another test holds a fresh, still inheritable duplicate would keep it.)
1348        let me = sys::current_user_sid().unwrap();
1349        assert!(sender_is(&me, &me, 100, 100));
1350        assert!(!sender_is(&me, &me, 101, 100));
1351        assert!(!sender_is(&me, "S-1-5-18", 100, 100));
1352        let now = filetime_at(Instant::now()).unwrap();
1353        let earlier = filetime_at(Instant::now().checked_sub(Duration::from_secs(5)).unwrap());
1354        assert!(earlier.unwrap() < now);
1355    }
1356
1357    #[cfg(all(windows, feature = "local"))]
1358    #[test]
1359    fn test_nothing_arrives_by_the_deadline() {
1360        use std::time::{Duration, Instant};
1361        let name = format!("net-io-handoff-c-{}", std::process::id());
1362        let listener = crate::pipe::PipeListener::create(&name).unwrap();
1363        let _tx = crate::pipe::PipeConnection::connect(&name, Duration::from_secs(1)).unwrap();
1364        let (mut rx, _) = listener.accept().unwrap();
1365        let until = Instant::now() + Duration::from_millis(50);
1366        assert!(matches!(
1367            receive_shared(&mut rx, &HandoffPeer::default(), until),
1368            Err(HandoffError::Timeout)
1369        ));
1370    }
1371}