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