Skip to main content

rusty_time_clock/
net.rs

1//! Socket readiness — the poll-before-recv seam.
2//!
3//! Two reasons this exists, both structural:
4//!
5//! 1. The daemon's event loop (M3+) multiplexes sockets and timers; readiness
6//!    polling is the primitive it is built on.
7//! 2. Simulation rigs that virtualize time (clknetsim) advance the simulated
8//!    clock while a process blocks in `poll`/`select` — a plain blocking `recv`
9//!    returns `EWOULDBLOCK` there and can never see a packet. Discovered by the
10//!    TIMECORP interception probe (`tools/corpus/wsl_interception_probe.sh`).
11//!
12//! On Windows the blocking-`recv` + `SO_RCVTIMEO` path is sound and WSAPoll adds
13//! nothing, so `wait_readable` reports ready immediately and the socket timeout
14//! governs.
15
16use crate::ClockError;
17use std::net::UdpSocket;
18use std::time::Duration;
19
20/// Wait until `socket` has data to read, or the timeout passes. Returns
21/// `Ok(true)` if readable, `Ok(false)` on timeout.
22#[cfg(unix)]
23pub fn wait_readable(socket: &UdpSocket, timeout: Duration) -> Result<bool, ClockError> {
24    use std::os::fd::AsRawFd;
25
26    let mut pfd = libc::pollfd {
27        fd: socket.as_raw_fd(),
28        events: libc::POLLIN,
29        revents: 0,
30    };
31    let timeout_ms = timeout.as_millis().min(i32::MAX as u128) as libc::c_int;
32    loop {
33        // SAFETY: pfd is a valid, exclusively-owned pollfd array of length 1 for
34        // the duration of the call.
35        let rc = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
36        if rc > 0 {
37            return Ok(pfd.revents & (libc::POLLIN | libc::POLLERR | libc::POLLHUP) != 0);
38        }
39        if rc == 0 {
40            return Ok(false);
41        }
42        let err = std::io::Error::last_os_error();
43        if err.kind() == std::io::ErrorKind::Interrupted {
44            continue;
45        }
46        return Err(ClockError {
47            op: "poll",
48            detail: err.to_string(),
49        });
50    }
51}
52
53#[cfg(windows)]
54pub fn wait_readable(_socket: &UdpSocket, _timeout: Duration) -> Result<bool, ClockError> {
55    // SO_RCVTIMEO on the socket governs; recv itself blocks correctly here.
56    Ok(true)
57}
58
59/// One received datagram: how many bytes, from whom, and — where the kernel
60/// provides it — when it actually arrived.
61#[derive(Clone, Copy, Debug)]
62pub struct Received {
63    pub len: usize,
64    pub peer: std::net::SocketAddr,
65    /// Kernel receive timestamp in Unix seconds, when `SO_TIMESTAMPING` is
66    /// enabled and the stack supplied one.
67    ///
68    /// This is the timestamp that matters for accuracy: it is taken when the
69    /// packet reaches the kernel, not when userspace happens to be scheduled
70    /// to read it. The gap between those two is scheduling latency, and on a
71    /// busy machine it is the single largest error in an otherwise good
72    /// exchange.
73    pub kernel_rx_s: Option<f64>,
74}
75
76/// Ask the kernel to attach receive timestamps to datagrams on this socket.
77///
78/// Requests hardware timestamps too; the kernel simply does not supply them
79/// where the NIC cannot, and `Received::kernel_rx_s` is `None` then. Failure is
80/// not fatal — the caller falls back to reading the clock after `recv`, which
81/// is what every implementation did before this existed.
82#[cfg(target_os = "linux")]
83pub fn enable_rx_timestamps(socket: &UdpSocket) -> Result<(), ClockError> {
84    use std::os::fd::AsRawFd;
85
86    // SOF_TIMESTAMPING_* bits. Named here rather than pulled from a binding
87    // crate because the set we want is small and fixed.
88    const RX_HARDWARE: libc::c_int = 1 << 0;
89    const RX_SOFTWARE: libc::c_int = 1 << 3;
90    const SOFTWARE: libc::c_int = 1 << 4;
91    const RAW_HARDWARE: libc::c_int = 1 << 6;
92
93    let flags: libc::c_int = RX_SOFTWARE | SOFTWARE | RX_HARDWARE | RAW_HARDWARE;
94    // SAFETY: setsockopt with a valid fd, level, name, and a pointer to an
95    // int of the declared length.
96    let rc = unsafe {
97        libc::setsockopt(
98            socket.as_raw_fd(),
99            libc::SOL_SOCKET,
100            libc::SO_TIMESTAMPING,
101            (&raw const flags).cast::<libc::c_void>(),
102            core::mem::size_of::<libc::c_int>() as libc::socklen_t,
103        )
104    };
105    if rc != 0 {
106        return Err(ClockError {
107            op: "setsockopt(SO_TIMESTAMPING)",
108            detail: std::io::Error::last_os_error().to_string(),
109        });
110    }
111    Ok(())
112}
113
114#[cfg(not(target_os = "linux"))]
115pub fn enable_rx_timestamps(_socket: &UdpSocket) -> Result<(), ClockError> {
116    // Windows has SIO_TIMESTAMPING (Win10 2004+) and macOS has SO_TIMESTAMP;
117    // neither is wired yet, and the caller's fallback is correct meanwhile.
118    Err(ClockError {
119        op: "enable_rx_timestamps",
120        detail: "kernel receive timestamps are not implemented on this platform".into(),
121    })
122}
123
124/// Adopt a listening socket the service manager already opened, if there is one.
125///
126/// systemd's socket activation passes descriptors starting at fd 3, which lets
127/// the socket be bound by systemd (as root, on port 123) while the daemon runs
128/// unprivileged — the only thing rtimed would otherwise need root for besides
129/// the clock itself.
130///
131/// Lives in this crate rather than the daemon because adopting a raw descriptor
132/// is a platform-seam operation, and this is the one crate permitted `unsafe`.
133pub fn activated_udp_socket() -> Option<UdpSocket> {
134    #[cfg(target_os = "linux")]
135    {
136        use std::os::fd::FromRawFd;
137
138        if !should_adopt_activated(
139            std::env::var("LISTEN_PID").ok().as_deref(),
140            std::env::var("LISTEN_FDS").ok().as_deref(),
141            std::process::id(),
142        ) {
143            return None;
144        }
145        // SAFETY: fd 3 is the first activated descriptor per systemd's
146        // protocol, and the check above confirmed the set was passed to this
147        // process. Ownership is taken exactly once, here.
148        Some(unsafe { UdpSocket::from_raw_fd(3) })
149    }
150    #[cfg(not(target_os = "linux"))]
151    {
152        None
153    }
154}
155
156/// Should we adopt the activated descriptor set?
157///
158/// Pure, so the decision is tested with explicit inputs rather than by mutating
159/// the process environment — which is `unsafe` in edition 2024 and races with
160/// every other test in the binary.
161///
162/// `LISTEN_PID` is the load-bearing check: a descriptor inherited from a parent
163/// sits at fd 3 just as an activated one does, and adopting it would hijack
164/// whatever the parent had open there.
165pub fn should_adopt_activated(
166    listen_pid: Option<&str>,
167    listen_fds: Option<&str>,
168    our_pid: u32,
169) -> bool {
170    let for_us = listen_pid
171        .and_then(|p| p.parse::<u32>().ok())
172        .map(|pid| pid == our_pid)
173        .unwrap_or(false);
174    let count = listen_fds.and_then(|n| n.parse::<i32>().ok()).unwrap_or(0);
175    for_us && count >= 1
176}
177
178/// Datagrams a single batch may collect. Past a few dozen the syscall saving
179/// per message is already amortised, and the buffer stops fitting in cache.
180pub const BATCH_SIZE: usize = 32;
181
182/// Reusable working memory for `recv_batch`.
183///
184/// The kernel needs an array of headers, one address slot and one control
185/// block per datagram. None of it carries information between calls -- it is
186/// all overwritten by the next `recvmmsg` -- so it is allocated once by the
187/// caller and reused, exactly as the packet buffers already are, instead of
188/// being built and thrown away on every receive.
189#[cfg(target_os = "linux")]
190#[derive(Default)]
191pub struct BatchScratch {
192    /// Whether to ask the kernel for control data (receive timestamps).
193    ///
194    /// Only worth paying for if the caller reads `Received::kernel_rx_s`. The
195    /// server does not — it stamps the batch itself — so it asks for none, and
196    /// the kernel skips the control-message machinery for every datagram.
197    want_control: bool,
198    iovecs: Vec<libc::iovec>,
199    addrs: Vec<libc::sockaddr_storage>,
200    msgs: Vec<libc::mmsghdr>,
201    controls: Vec<[u8; CONTROL_LEN]>,
202}
203
204#[cfg(target_os = "linux")]
205impl BatchScratch {
206    /// Scratch that collects kernel receive timestamps.
207    pub fn new() -> Self {
208        let mut scratch = BatchScratch {
209            want_control: true,
210            ..BatchScratch::default()
211        };
212        scratch.ensure(BATCH_SIZE);
213        scratch
214    }
215
216    /// Scratch for a caller that does not read `Received::kernel_rx_s`.
217    pub fn without_timestamps() -> Self {
218        let mut scratch = BatchScratch::default();
219        scratch.ensure(BATCH_SIZE);
220        scratch
221    }
222
223    /// Grow to hold `count` datagrams. After the first call this does nothing.
224    fn ensure(&mut self, count: usize) {
225        if self.msgs.len() >= count {
226            return;
227        }
228        // SAFETY: every one of these is a plain-old-data C struct for which an
229        // all-zero bit pattern is a valid, inert value; each is fully
230        // initialised before the kernel sees it.
231        self.iovecs
232            .resize(count, unsafe { core::mem::zeroed::<libc::iovec>() });
233        self.addrs.resize(count, unsafe {
234            core::mem::zeroed::<libc::sockaddr_storage>()
235        });
236        self.msgs
237            .resize(count, unsafe { core::mem::zeroed::<libc::mmsghdr>() });
238        self.controls.resize(count, [0u8; CONTROL_LEN]);
239    }
240}
241
242/// Non-Linux placeholder, so callers have one shape on every platform.
243#[cfg(not(target_os = "linux"))]
244#[derive(Default)]
245pub struct BatchScratch;
246
247#[cfg(not(target_os = "linux"))]
248impl BatchScratch {
249    pub fn new() -> Self {
250        BatchScratch
251    }
252
253    /// Same shape as the Linux constructor. There is no control-message
254    /// machinery to decline here, so the two are identical — the method exists
255    /// so callers compile unchanged on every platform.
256    pub fn without_timestamps() -> Self {
257        BatchScratch
258    }
259}
260
261/// Receive up to `bufs.len()` datagrams in **one** syscall on Linux
262/// (`recvmmsg`), falling back to a single `recv_from` elsewhere.
263///
264/// This is the server-throughput lever the mission plan calls out: a
265/// one-request-per-syscall server spends most of its CPU crossing the kernel
266/// boundary, not answering NTP. The scalar path is kept as the oracle — both
267/// must produce identical results, and the batch tests assert that.
268#[cfg(target_os = "linux")]
269pub fn recv_batch(
270    socket: &UdpSocket,
271    bufs: &mut [[u8; 1024]],
272    scratch: &mut BatchScratch,
273    out: &mut Vec<Received>,
274) -> Result<usize, ClockError> {
275    use std::os::fd::AsRawFd;
276
277    out.clear();
278    let count = bufs.len().min(BATCH_SIZE);
279    if count == 0 {
280        return Ok(0);
281    }
282    scratch.ensure(count);
283
284    // Point each header at this call's buffers and reset the two lengths the
285    // kernel writes back. Nothing is allocated and nothing is zeroed: the
286    // kernel reports how many bytes it put in the address and the control
287    // block, so stale bytes beyond those lengths are never read.
288    //
289    // The previous form built all four arrays per call -- two of them with
290    // `vec![zeroed; 32]`, which is ~4 KiB of sockaddr and 4 KiB of control
291    // buffer memset on every `recvmmsg`, plus four allocations -- to hand the
292    // kernel scratch space it immediately overwrites.
293    let BatchScratch {
294        want_control,
295        iovecs,
296        addrs,
297        msgs,
298        controls,
299    } = scratch;
300    for i in 0..count {
301        iovecs[i] = libc::iovec {
302            iov_base: bufs[i].as_mut_ptr().cast::<libc::c_void>(),
303            iov_len: bufs[i].len(),
304        };
305    }
306    for i in 0..count {
307        let hdr = &mut msgs[i].msg_hdr;
308        hdr.msg_name = (&mut addrs[i] as *mut libc::sockaddr_storage).cast::<libc::c_void>();
309        hdr.msg_namelen = core::mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
310        hdr.msg_iov = (&mut iovecs[i]) as *mut libc::iovec;
311        hdr.msg_iovlen = 1;
312        if *want_control {
313            hdr.msg_control = controls[i].as_mut_ptr().cast::<libc::c_void>();
314            hdr.msg_controllen = CONTROL_LEN as _;
315        } else {
316            hdr.msg_control = core::ptr::null_mut();
317            hdr.msg_controllen = 0;
318        }
319        msgs[i].msg_len = 0;
320    }
321
322    // SAFETY: msgs is a valid array of `count` mmsghdr, each pointing at a
323    // live iovec and sockaddr_storage owned by this frame for the duration of
324    // the call. MSG_DONTWAIT keeps this non-blocking; readiness is the
325    // caller's job.
326    let received = unsafe {
327        libc::recvmmsg(
328            socket.as_raw_fd(),
329            msgs.as_mut_ptr(),
330            count as libc::c_uint,
331            // glibc and musl disagree on this parameter's integer type, so let
332            // the cast take whichever the target's signature declares.
333            libc::MSG_DONTWAIT as _,
334            core::ptr::null_mut(),
335        )
336    };
337    if received < 0 {
338        let err = std::io::Error::last_os_error();
339        if matches!(
340            err.kind(),
341            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
342        ) {
343            return Ok(0);
344        }
345        return Err(ClockError {
346            op: "recvmmsg",
347            detail: err.to_string(),
348        });
349    }
350
351    for msg in msgs.iter().take(received as usize) {
352        let len = msg.msg_len as usize;
353        // SAFETY: the kernel filled msg_name with a sockaddr of msg_namelen
354        // bytes; we only read the family and the matching variant.
355        let peer =
356            unsafe { sockaddr_to_rust(&*(msg.msg_hdr.msg_name as *const libc::sockaddr_storage)) };
357        if let Some(peer) = peer {
358            // SAFETY: the kernel filled msg_control with msg_controllen bytes
359            // of well-formed cmsgs, or set the length to zero.
360            let kernel_rx_s = unsafe { kernel_timestamp(&msg.msg_hdr) };
361            out.push(Received {
362                len,
363                peer,
364                kernel_rx_s,
365            });
366        }
367    }
368    Ok(out.len())
369}
370
371/// Bytes reserved per datagram for control messages. One SCM_TIMESTAMPING
372/// carries three timespecs; this leaves room for it and a little slack.
373#[cfg(target_os = "linux")]
374const CONTROL_LEN: usize = 128;
375
376/// Pull the receive timestamp out of a message's control data.
377///
378/// `SCM_TIMESTAMPING` carries three timespecs: [0] software, [1] legacy
379/// hardware (deprecated), [2] raw hardware. Software is preferred when
380/// present because it is already on the system timescale; the raw hardware
381/// stamp is on the NIC's own timescale and needs a PHC correlation before it
382/// means anything, which is why it is not simply used when available.
383///
384/// # Safety
385/// `hdr` must be a msghdr the kernel has just filled, with `msg_control`
386/// pointing at `msg_controllen` valid bytes.
387#[cfg(target_os = "linux")]
388unsafe fn kernel_timestamp(hdr: &libc::msghdr) -> Option<f64> {
389    if hdr.msg_controllen == 0 || hdr.msg_control.is_null() {
390        return None;
391    }
392    // SAFETY: caller's contract; CMSG_FIRSTHDR handles an empty buffer.
393    let mut cmsg = unsafe { libc::CMSG_FIRSTHDR(hdr) };
394    while !cmsg.is_null() {
395        // SAFETY: cmsg came from CMSG_FIRSTHDR/CMSG_NXTHDR and is in range.
396        let header = unsafe { &*cmsg };
397        if header.cmsg_level == libc::SOL_SOCKET && header.cmsg_type == libc::SCM_TIMESTAMPING {
398            // SAFETY: SCM_TIMESTAMPING data is three timespecs.
399            let stamps = unsafe { libc::CMSG_DATA(cmsg).cast::<libc::timespec>() };
400            for index in [0usize, 2] {
401                // SAFETY: index is within the three-element array above.
402                let ts = unsafe { *stamps.add(index) };
403                if ts.tv_sec != 0 || ts.tv_nsec != 0 {
404                    return Some(ts.tv_sec as f64 + ts.tv_nsec as f64 * 1e-9);
405                }
406            }
407        }
408        // SAFETY: as above.
409        cmsg = unsafe { libc::CMSG_NXTHDR(hdr, cmsg) };
410    }
411    None
412}
413
414#[cfg(target_os = "linux")]
415/// Fill a `sockaddr_storage` from a Rust address, returning its length.
416#[cfg(target_os = "linux")]
417fn rust_to_sockaddr(
418    addr: &std::net::SocketAddr,
419    out: &mut libc::sockaddr_storage,
420) -> libc::socklen_t {
421    match addr {
422        std::net::SocketAddr::V4(v4) => {
423            // SAFETY: sockaddr_storage is sized and aligned for sockaddr_in,
424            // which is the whole reason it exists; every field is written.
425            let sin = unsafe { &mut *(out as *mut _ as *mut libc::sockaddr_in) };
426            sin.sin_family = libc::AF_INET as libc::sa_family_t;
427            sin.sin_port = v4.port().to_be();
428            sin.sin_addr.s_addr = u32::from(*v4.ip()).to_be();
429            core::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t
430        }
431        std::net::SocketAddr::V6(v6) => {
432            // SAFETY: as above, for sockaddr_in6.
433            let sin6 = unsafe { &mut *(out as *mut _ as *mut libc::sockaddr_in6) };
434            sin6.sin6_family = libc::AF_INET6 as libc::sa_family_t;
435            sin6.sin6_port = v6.port().to_be();
436            sin6.sin6_addr.s6_addr = v6.ip().octets();
437            sin6.sin6_flowinfo = v6.flowinfo();
438            sin6.sin6_scope_id = v6.scope_id();
439            core::mem::size_of::<libc::sockaddr_in6>() as libc::socklen_t
440        }
441    }
442}
443
444/// Send many datagrams in **one** syscall on Linux (`sendmmsg`).
445///
446/// The receive side has been batched since M5; the send side was not, so a
447/// server that collected up to 32 requests with one `recvmmsg` then answered
448/// them with 32 separate `sendto` calls. Under load the reply path was the
449/// syscall-heavy half of the loop.
450///
451/// It also makes the transmit timestamp *more* honest for interleaved mode
452/// rather than less: the packets genuinely do leave in one syscall, so one
453/// clock reading taken immediately afterwards describes all of them, where the
454/// old loop stamped each reply after its own `sendto` and attributed the
455/// accumulated delay of the whole loop to the last client in the batch.
456///
457/// Returns how many datagrams the kernel accepted.
458#[cfg(target_os = "linux")]
459pub fn send_batch(
460    socket: &UdpSocket,
461    messages: &[(&[u8], std::net::SocketAddr)],
462    scratch: &mut BatchScratch,
463) -> Result<usize, ClockError> {
464    send_batch_by(socket, messages, |m| m.0, |m| m.1, scratch)
465}
466
467/// `send_batch` reading each datagram out of the caller's own items.
468///
469/// The slice form needs a `&[(&[u8], SocketAddr)]`, which a caller holding
470/// replies in some other shape can only produce by building a temporary vector
471/// every batch — an allocation, a copy of every element, and a free, to
472/// describe data it already had. Accessors remove it.
473#[cfg(target_os = "linux")]
474pub fn send_batch_by<T>(
475    socket: &UdpSocket,
476    items: &[T],
477    payload: impl Fn(&T) -> &[u8],
478    peer: impl Fn(&T) -> std::net::SocketAddr,
479    scratch: &mut BatchScratch,
480) -> Result<usize, ClockError> {
481    use std::os::fd::AsRawFd;
482
483    let count = items.len().min(BATCH_SIZE);
484    if count == 0 {
485        return Ok(0);
486    }
487    scratch.ensure(count);
488    let BatchScratch {
489        iovecs,
490        addrs,
491        msgs,
492        ..
493    } = scratch;
494
495    for (i, item) in items.iter().enumerate().take(count) {
496        let bytes = payload(item);
497        iovecs[i] = libc::iovec {
498            iov_base: bytes.as_ptr() as *mut libc::c_void,
499            iov_len: bytes.len(),
500        };
501        let namelen = rust_to_sockaddr(&peer(item), &mut addrs[i]);
502        let hdr = &mut msgs[i].msg_hdr;
503        hdr.msg_name = (&mut addrs[i] as *mut libc::sockaddr_storage).cast::<libc::c_void>();
504        hdr.msg_namelen = namelen;
505        hdr.msg_iov = (&mut iovecs[i]) as *mut libc::iovec;
506        hdr.msg_iovlen = 1;
507        hdr.msg_control = core::ptr::null_mut();
508        hdr.msg_controllen = 0;
509        msgs[i].msg_len = 0;
510    }
511
512    // SAFETY: msgs is a valid array of `count` mmsghdr, each naming a live
513    // iovec and sockaddr owned by `scratch`, which outlives the call. The
514    // payloads are borrowed for the duration of `messages`.
515    let sent = unsafe {
516        libc::sendmmsg(
517            socket.as_raw_fd(),
518            msgs.as_mut_ptr(),
519            count as libc::c_uint,
520            libc::MSG_DONTWAIT as _,
521        )
522    };
523    if sent < 0 {
524        let err = std::io::Error::last_os_error();
525        if matches!(
526            err.kind(),
527            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
528        ) {
529            return Ok(0);
530        }
531        return Err(ClockError {
532            op: "sendmmsg",
533            detail: err.to_string(),
534        });
535    }
536    Ok(sent as usize)
537}
538
539/// Non-Linux fallback: one datagram per call, same shape as the batch path.
540#[cfg(not(target_os = "linux"))]
541pub fn send_batch(
542    socket: &UdpSocket,
543    messages: &[(&[u8], std::net::SocketAddr)],
544    scratch: &mut BatchScratch,
545) -> Result<usize, ClockError> {
546    send_batch_by(socket, messages, |m| m.0, |m| m.1, scratch)
547}
548
549/// Non-Linux fallback: one datagram per call, same shape as the batch path.
550#[cfg(not(target_os = "linux"))]
551pub fn send_batch_by<T>(
552    socket: &UdpSocket,
553    items: &[T],
554    payload: impl Fn(&T) -> &[u8],
555    peer: impl Fn(&T) -> std::net::SocketAddr,
556    _scratch: &mut BatchScratch,
557) -> Result<usize, ClockError> {
558    let mut sent = 0;
559    for item in items {
560        match socket.send_to(payload(item), peer(item)) {
561            Ok(_) => sent += 1,
562            Err(e)
563                if matches!(
564                    e.kind(),
565                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
566                ) =>
567            {
568                break;
569            }
570            Err(e) => {
571                return Err(ClockError {
572                    op: "send_to",
573                    detail: e.to_string(),
574                });
575            }
576        }
577    }
578    Ok(sent)
579}
580
581#[cfg(target_os = "linux")]
582fn sockaddr_to_rust(storage: &libc::sockaddr_storage) -> Option<std::net::SocketAddr> {
583    use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6};
584    match storage.ss_family as libc::c_int {
585        libc::AF_INET => {
586            // SAFETY: family says this is a sockaddr_in.
587            let sin = unsafe { &*(storage as *const _ as *const libc::sockaddr_in) };
588            let ip = Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr));
589            Some(std::net::SocketAddr::V4(SocketAddrV4::new(
590                ip,
591                u16::from_be(sin.sin_port),
592            )))
593        }
594        libc::AF_INET6 => {
595            // SAFETY: family says this is a sockaddr_in6.
596            let sin6 = unsafe { &*(storage as *const _ as *const libc::sockaddr_in6) };
597            let ip = Ipv6Addr::from(sin6.sin6_addr.s6_addr);
598            Some(std::net::SocketAddr::V6(SocketAddrV6::new(
599                ip,
600                u16::from_be(sin6.sin6_port),
601                sin6.sin6_flowinfo,
602                sin6.sin6_scope_id,
603            )))
604        }
605        _ => None,
606    }
607}
608
609/// Non-Linux fallback: one datagram per call, same shape as the batch path so
610/// the server loop above it is identical on every platform.
611#[cfg(not(target_os = "linux"))]
612pub fn recv_batch(
613    socket: &UdpSocket,
614    bufs: &mut [[u8; 1024]],
615    _scratch: &mut BatchScratch,
616    out: &mut Vec<Received>,
617) -> Result<usize, ClockError> {
618    out.clear();
619    let Some(buf) = bufs.first_mut() else {
620        return Ok(0);
621    };
622    match socket.recv_from(buf) {
623        Ok((len, peer)) => {
624            out.push(Received {
625                len,
626                peer,
627                kernel_rx_s: None,
628            });
629            Ok(1)
630        }
631        Err(e)
632            if matches!(
633                e.kind(),
634                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
635            ) =>
636        {
637            Ok(0)
638        }
639        Err(e) => Err(ClockError {
640            op: "recv_from",
641            detail: e.to_string(),
642        }),
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    use super::*;
649
650    #[test]
651    fn timeout_and_readable_paths() {
652        let a = UdpSocket::bind("127.0.0.1:0").expect("bind a");
653        let b = UdpSocket::bind("127.0.0.1:0").expect("bind b");
654        // Nothing pending on Unix: times out quickly. On Windows the shim
655        // reports ready by design; recv's own timeout governs there.
656        let quick = wait_readable(&a, Duration::from_millis(50)).expect("wait");
657        if cfg!(unix) {
658            assert!(!quick, "empty socket reported readable");
659        } else {
660            assert!(quick);
661        }
662        b.send_to(b"x", a.local_addr().expect("addr"))
663            .expect("send");
664        let ready = wait_readable(&a, Duration::from_millis(2000)).expect("wait");
665        assert!(ready, "pending datagram not reported readable");
666    }
667
668    #[test]
669    fn batch_receive_returns_every_datagram_with_its_sender() {
670        let server = UdpSocket::bind("127.0.0.1:0").expect("bind server");
671        let server_addr = server.local_addr().expect("addr");
672        server
673            .set_read_timeout(Some(Duration::from_millis(500)))
674            .expect("timeout");
675
676        let client = UdpSocket::bind("127.0.0.1:0").expect("bind client");
677        let client_addr = client.local_addr().expect("client addr");
678        let sent = 5usize;
679        for i in 0..sent {
680            client.send_to(&[i as u8; 16], server_addr).expect("send");
681        }
682
683        // Collect until we have them all or we stop making progress: the batch
684        // path may return fewer than were sent in one call.
685        let mut bufs = [[0u8; 1024]; BATCH_SIZE];
686        let mut out = Vec::new();
687        let mut total = 0usize;
688        let mut idle = 0;
689        while total < sent && idle < 20 {
690            if !wait_readable(&server, Duration::from_millis(200)).expect("wait") {
691                idle += 1;
692                continue;
693            }
694            let n =
695                recv_batch(&server, &mut bufs, &mut BatchScratch::new(), &mut out).expect("batch");
696            if n == 0 {
697                idle += 1;
698                continue;
699            }
700            for received in out.iter().take(n) {
701                assert_eq!(received.len, 16, "wrong length reported");
702                assert_eq!(
703                    received.peer, client_addr,
704                    "batch reported the wrong sender"
705                );
706            }
707            total += n;
708        }
709        assert_eq!(total, sent, "batch receive lost datagrams");
710    }
711
712    #[test]
713    fn activation_is_refused_unless_the_descriptors_are_ours() {
714        // The happy path: systemd names us and passes one descriptor.
715        assert!(should_adopt_activated(Some("42"), Some("1"), 42));
716        // A descriptor set meant for a different process must never be
717        // adopted — fd 3 inherited from a parent looks identical otherwise.
718        assert!(!should_adopt_activated(Some("41"), Some("1"), 42));
719        // No environment at all: the ordinary case, run from a shell.
720        assert!(!should_adopt_activated(None, None, 42));
721        // Named but nothing passed.
722        assert!(!should_adopt_activated(Some("42"), Some("0"), 42));
723        // Garbage must not be read as consent.
724        assert!(!should_adopt_activated(Some("not-a-pid"), Some("1"), 42));
725        assert!(!should_adopt_activated(Some("42"), Some("many"), 42));
726    }
727
728    #[test]
729    fn batch_receive_on_an_empty_socket_returns_zero_not_an_error() {
730        let s = UdpSocket::bind("127.0.0.1:0").expect("bind");
731        s.set_read_timeout(Some(Duration::from_millis(50)))
732            .expect("timeout");
733        let mut bufs = [[0u8; 1024]; 4];
734        let mut out = Vec::new();
735        assert_eq!(
736            recv_batch(&s, &mut bufs, &mut BatchScratch::new(), &mut out).expect("batch"),
737            0
738        );
739        assert!(out.is_empty());
740    }
741}