Skip to main content

raw_ether/
stamped.rs

1//! Frames of one ethertype sent and received with the times the
2//! interface's hardware put on them, as gPTP needs: when each received
3//! frame crossed the wire in, and when each sent one went out, by the
4//! interface's PTP hardware clock. The kernel adds and removes the
5//! Ethernet header, as for a [`crate::socket::Socket`].
6//!
7//! [`enable`] turns the interface's time stamping on, for every frame
8//! received and for the frames sent that ask for it; programs such as
9//! ptp4l do the same. Only the frames sent with
10//! [`StampedSocket::send_stamped`] ask, gPTP's event messages, so their
11//! times are the ones that come back. Linux only; elsewhere opening fails
12//! as unsupported.
13
14use std::io;
15#[cfg(any(target_os = "linux", test))]
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::time::Duration;
18
19use crate::MacAddress;
20
21/// A frame received on a [`StampedSocket`].
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Received {
24    pub source: MacAddress,
25    /// Octets of payload written to the buffer, after the Ethernet header.
26    pub length: usize,
27    /// When it crossed the wire in, by the interface's hardware clock,
28    /// when the interface stamped it.
29    pub time: Option<Duration>,
30}
31
32/// Sends and receives the payloads of Ethernet frames of one ethertype on
33/// one interface, with hardware time stamps.
34pub struct StampedSocket {
35    inner: platform::StampedSocket,
36}
37
38impl StampedSocket {
39    /// Opens `interface` for frames of `ethertype`, stamping each frame
40    /// received. On Linux this needs `CAP_NET_RAW`.
41    pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
42        Ok(Self {
43            inner: platform::StampedSocket::open(interface, ethertype)?,
44        })
45    }
46
47    /// Receives frames sent to `group` as well.
48    pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
49        self.inner.join_multicast(group)
50    }
51
52    /// Sends `payload` to `destination`, unstamped.
53    pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
54        self.inner.send(destination, payload)
55    }
56
57    /// Sends `payload` to `destination` and has the interface stamp it;
58    /// when it has gone out, [`transmit_time`](Self::transmit_time) gives
59    /// the time. Times of frames sent before that came too late for
60    /// `transmit_time` are dropped first, so the next it gives is this
61    /// frame's.
62    pub fn send_stamped(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
63        self.inner.send_stamped(destination, payload)
64    }
65
66    /// The time the last frame sent with
67    /// [`send_stamped`](Self::send_stamped) went out, by the interface's
68    /// hardware clock, waiting up to `timeout` for the interface to say.
69    /// `None` when it did not say in time. Where the kernel numbers the
70    /// times sent (`SOF_TIMESTAMPING_OPT_ID`), one come too late for an
71    /// earlier frame is dropped, never taken for this one.
72    pub fn transmit_time(&self, timeout: Duration) -> io::Result<Option<Duration>> {
73        self.inner.transmit_time(timeout)
74    }
75
76    /// Writes the next frame's payload to `buffer`, waiting up to
77    /// `timeout` (forever when `None`) for one.
78    pub fn receive(
79        &self,
80        buffer: &mut [u8],
81        timeout: Option<Duration>,
82    ) -> io::Result<Option<Received>> {
83        self.inner.receive(buffer, timeout)
84    }
85}
86
87/// Waits up to `timeout` (forever when `None`) for a frame on any of
88/// `sockets`: the positions of those with one to receive, none when the
89/// time ran out. Times that came too late for
90/// [`StampedSocket::transmit_time`] are dropped meanwhile.
91pub fn wait_any(sockets: &[&StampedSocket], timeout: Option<Duration>) -> io::Result<Vec<usize>> {
92    let inner: Vec<&platform::StampedSocket> = sockets.iter().map(|socket| &socket.inner).collect();
93    platform::wait_any(&inner, timeout)
94}
95
96/// As [`wait_any`], waking also when `also` has something to read, such as
97/// [`LinkChanges`](crate::interfaces::LinkChanges): the positions of the
98/// sockets with one to receive, and whether `also` has.
99#[cfg(target_os = "linux")]
100pub fn wait_any_or(
101    sockets: &[&StampedSocket],
102    also: std::os::fd::BorrowedFd<'_>,
103    timeout: Option<Duration>,
104) -> io::Result<(Vec<usize>, bool)> {
105    let inner: Vec<&platform::StampedSocket> = sockets.iter().map(|socket| &socket.inner).collect();
106    platform::wait_any_or(&inner, Some(also), timeout)
107}
108
109/// Has `interface` stamp every frame it receives and the frames sent that
110/// ask for it, as a gPTP program needs. This changes the interface for
111/// every program, and needs `CAP_NET_ADMIN`; an interface already set so,
112/// by ptp4l say, is left as it is, as setting it again can lose a time
113/// the other program waits for.
114pub fn enable(interface: &str) -> io::Result<()> {
115    platform::enable(interface)
116}
117
118/// The control message of SO_TIMESTAMPING's three times: the raw hardware
119/// time, the last, when it is there.
120#[cfg(any(target_os = "linux", test))]
121fn raw_hardware(stamps: [(i64, i64); 3]) -> Option<Duration> {
122    let (seconds, nanoseconds) = stamps[2];
123    (seconds > 0 || nanoseconds > 0).then(|| Duration::new(seconds as u64, nanoseconds as u32))
124}
125
126/// What a time sent that came back is, against the number `wanted`, that
127/// of the last frame sent asking for one.
128#[cfg(any(target_os = "linux", test))]
129#[derive(Debug, PartialEq, Eq)]
130enum Taken {
131    /// The last frame's time, or one taken in order.
132    Wanted,
133    /// An earlier frame's, come too late: no time for the last one.
134    Late,
135    /// A number past the count, as when a send failed after the kernel
136    /// numbered its frame: the last frame's all the same, and the count
137    /// goes on from it.
138    Ahead(u32),
139}
140
141/// Pairs a time sent, numbered `number` by the kernel if it numbers them,
142/// with the last frame sent, numbered `wanted`; `numbered` remembers that
143/// the kernel does, once a number other than 0 came back.
144#[cfg(any(target_os = "linux", test))]
145fn taken(number: Option<u32>, wanted: u32, numbered: &AtomicBool) -> Taken {
146    let Some(number) = number else {
147        return Taken::Wanted;
148    };
149    if number != 0 {
150        numbered.store(true, Ordering::Relaxed);
151    }
152    if !numbered.load(Ordering::Relaxed) || number == wanted {
153        return Taken::Wanted;
154    }
155    // Earlier numbers are behind `wanted` by less than half the range.
156    if wanted.wrapping_sub(number) < 1 << 31 {
157        Taken::Late
158    } else {
159        Taken::Ahead(number)
160    }
161}
162
163#[cfg(target_os = "linux")]
164#[allow(unsafe_code)]
165mod platform {
166    use std::io;
167    use std::mem::{size_of, size_of_val, zeroed};
168    use std::os::fd::{AsRawFd, OwnedFd};
169    use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
170    use std::time::Duration;
171
172    use super::{Received, Taken, taken};
173    use crate::MacAddress;
174
175    /// From Linux's headers, which libc lacks for Linux.
176    const SO_TIMESTAMPING: libc::c_int = 37;
177    const SIOCSHWTSTAMP: libc::c_ulong = 0x89b0;
178    const SIOCGHWTSTAMP: libc::c_ulong = 0x89b1;
179    const HWTSTAMP_TX_ON: libc::c_int = 1;
180    const HWTSTAMP_FILTER_ALL: libc::c_int = 1;
181    const SOF_TIMESTAMPING_TX_HARDWARE: u32 = 1 << 0;
182    const SOF_TIMESTAMPING_RX_HARDWARE: u32 = 1 << 2;
183    const SOF_TIMESTAMPING_RAW_HARDWARE: u32 = 1 << 6;
184    /// Each frame sent that asks for a time is numbered, from 0, and its
185    /// time comes back with that number.
186    const SOF_TIMESTAMPING_OPT_ID: u32 = 1 << 7;
187    /// Only the time comes back on the error queue, not the frame.
188    const SOF_TIMESTAMPING_OPT_TSONLY: u32 = 1 << 11;
189    /// The control message a time sent comes back in on a packet socket,
190    /// a sock_extended_err (linux/if_packet.h, linux/errqueue.h).
191    const PACKET_TX_TIMESTAMP: libc::c_int = 16;
192    const SO_EE_ORIGIN_TIMESTAMPING: u8 = 4;
193
194    /// struct sock_extended_err, from linux/errqueue.h, whole for its
195    /// layout though only two fields are read.
196    #[repr(C)]
197    #[derive(Clone, Copy)]
198    #[allow(dead_code)]
199    struct ExtendedError {
200        errno: u32,
201        origin: u8,
202        kind: u8,
203        code: u8,
204        pad: u8,
205        info: u32,
206        data: u32,
207    }
208
209    /// struct hwtstamp_config, from linux/net_tstamp.h.
210    #[repr(C)]
211    struct HardwareConfig {
212        flags: libc::c_int,
213        tx_type: libc::c_int,
214        rx_filter: libc::c_int,
215    }
216
217    pub fn enable(interface: &str) -> io::Result<()> {
218        let fd = crate::broker::open(crate::broker::Kind::Datagram)?;
219        let mut config = HardwareConfig {
220            flags: 0,
221            tx_type: 0,
222            rx_filter: 0,
223        };
224        if configure(&fd, interface, SIOCGHWTSTAMP, &mut config).is_ok()
225            && config.tx_type == HWTSTAMP_TX_ON
226            && config.rx_filter == HWTSTAMP_FILTER_ALL
227        {
228            return Ok(());
229        }
230        config = HardwareConfig {
231            flags: 0,
232            tx_type: HWTSTAMP_TX_ON,
233            rx_filter: HWTSTAMP_FILTER_ALL,
234        };
235        configure(&fd, interface, SIOCSHWTSTAMP, &mut config)
236    }
237
238    /// Gets or sets `interface`'s time stamping with `request`, through
239    /// `config`.
240    fn configure(
241        fd: &OwnedFd,
242        interface: &str,
243        request_code: libc::c_ulong,
244        config: &mut HardwareConfig,
245    ) -> io::Result<()> {
246        // SAFETY: ifreq is plain data, valid when zeroed.
247        let mut request: libc::ifreq = unsafe { zeroed() };
248        let name = interface.as_bytes();
249        if name.len() >= request.ifr_name.len() {
250            return Err(io::Error::new(
251                io::ErrorKind::InvalidInput,
252                "interface name too long",
253            ));
254        }
255        for (slot, octet) in request.ifr_name.iter_mut().zip(name) {
256            *slot = *octet as libc::c_char;
257        }
258        request.ifr_ifru.ifru_data = std::ptr::from_mut(config).cast();
259        // SAFETY: `request` names the interface and points at `config`,
260        // both living through the call.
261        if unsafe { libc::ioctl(fd.as_raw_fd(), request_code as _, &raw mut request) } < 0 {
262            return Err(io::Error::last_os_error());
263        }
264        Ok(())
265    }
266
267    pub struct StampedSocket {
268        fd: OwnedFd,
269        index: i32,
270        ethertype: u16,
271        /// How many frames asking for a time were sent, so the number the
272        /// next time sent should come back with.
273        stamped: AtomicU32,
274        /// Whether the kernel numbers this socket's times. Until a number
275        /// other than 0 comes back they are taken in order, as a kernel
276        /// that does not number them leaves every one 0.
277        numbered: AtomicBool,
278    }
279
280    fn timeout_ms(timeout: Option<Duration>) -> libc::c_int {
281        match timeout {
282            // Round up, so a short wait does not become a busy loop.
283            Some(timeout) => timeout.as_nanos().div_ceil(1_000_000).min(i32::MAX as u128) as i32,
284            None => -1,
285        }
286    }
287
288    /// Waits up to `timeout` for `events` on `fd`: whether they came.
289    fn wait(fd: &OwnedFd, events: libc::c_short, timeout: Option<Duration>) -> io::Result<bool> {
290        let mut poll = libc::pollfd {
291            fd: fd.as_raw_fd(),
292            events,
293            revents: 0,
294        };
295        // SAFETY: one valid pollfd, which lives through the call.
296        let ready = unsafe { libc::poll(&raw mut poll, 1, timeout_ms(timeout)) };
297        if ready < 0 {
298            let error = io::Error::last_os_error();
299            return match error.kind() {
300                io::ErrorKind::Interrupted => Ok(false),
301                _ => Err(error),
302            };
303        }
304        Ok(ready > 0 && poll.revents & (events | libc::POLLERR) != 0)
305    }
306
307    pub fn wait_any(
308        sockets: &[&StampedSocket],
309        timeout: Option<Duration>,
310    ) -> io::Result<Vec<usize>> {
311        wait_any_or(sockets, None, timeout).map(|(readable, _)| readable)
312    }
313
314    pub fn wait_any_or(
315        sockets: &[&StampedSocket],
316        also: Option<std::os::fd::BorrowedFd<'_>>,
317        timeout: Option<Duration>,
318    ) -> io::Result<(Vec<usize>, bool)> {
319        let deadline = timeout.map(|timeout| std::time::Instant::now() + timeout);
320        let mut polls: Vec<libc::pollfd> = sockets
321            .iter()
322            .map(|socket| socket.fd.as_raw_fd())
323            .chain(also.map(|also| also.as_raw_fd()))
324            .map(|fd| libc::pollfd {
325                fd,
326                events: libc::POLLIN,
327                revents: 0,
328            })
329            .collect();
330        loop {
331            let left = deadline
332                .map(|deadline| deadline.saturating_duration_since(std::time::Instant::now()));
333            // SAFETY: `polls` holds one valid pollfd per socket, and lives
334            // through the call.
335            let ready = unsafe {
336                libc::poll(
337                    polls.as_mut_ptr(),
338                    polls.len() as libc::nfds_t,
339                    timeout_ms(left),
340                )
341            };
342            if ready < 0 {
343                let error = io::Error::last_os_error();
344                if error.kind() == io::ErrorKind::Interrupted {
345                    continue;
346                }
347                return Err(error);
348            }
349            let readable: Vec<usize> = polls[..sockets.len()]
350                .iter()
351                .enumerate()
352                .filter(|(_, poll)| poll.revents & libc::POLLIN != 0)
353                .map(|(position, _)| position)
354                .collect();
355            let also_ready = polls[sockets.len()..]
356                .iter()
357                .any(|poll| poll.revents & (libc::POLLIN | libc::POLLERR) != 0);
358            // A time on the error queue that no one waited for would wake
359            // every poll until taken.
360            for (socket, poll) in sockets.iter().zip(&polls) {
361                if poll.revents & libc::POLLERR != 0 {
362                    socket.drop_late_times()?;
363                }
364            }
365            if !readable.is_empty()
366                || also_ready
367                || ready == 0
368                || left.is_some_and(|left| left.is_zero())
369            {
370                return Ok((readable, also_ready));
371            }
372        }
373    }
374
375    /// One message received: its length, its raw hardware time and, for a
376    /// time sent, the number of the frame it was sent for.
377    struct Message {
378        length: usize,
379        time: Option<Duration>,
380        number: Option<u32>,
381    }
382
383    /// Receives one message on `fd` with `flags` into `buffer`, its
384    /// source into `address`.
385    fn receive_message(
386        fd: &OwnedFd,
387        buffer: &mut [u8],
388        address: &mut libc::sockaddr_ll,
389        flags: libc::c_int,
390    ) -> io::Result<Option<Message>> {
391        let mut control = [0u64; 64];
392        let mut part = libc::iovec {
393            iov_base: buffer.as_mut_ptr().cast(),
394            iov_len: buffer.len(),
395        };
396        // SAFETY: msghdr is plain data, valid when zeroed.
397        let mut message: libc::msghdr = unsafe { zeroed() };
398        message.msg_name = std::ptr::from_mut(address).cast();
399        message.msg_namelen = size_of::<libc::sockaddr_ll>() as libc::socklen_t;
400        message.msg_iov = &raw mut part;
401        message.msg_iovlen = 1;
402        message.msg_control = control.as_mut_ptr().cast();
403        message.msg_controllen = size_of_val(&control) as _;
404        // SAFETY: every buffer the message points to lives through the
405        // call, with its length given.
406        let length =
407            unsafe { libc::recvmsg(fd.as_raw_fd(), &raw mut message, flags | libc::MSG_DONTWAIT) };
408        if length < 0 {
409            let error = io::Error::last_os_error();
410            return match error.kind() {
411                io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => Ok(None),
412                _ => Err(error),
413            };
414        }
415        let mut time = None;
416        let mut number = None;
417        // SAFETY: the kernel wrote the control messages within `control`,
418        // and msg_controllen says how far; CMSG_FIRSTHDR and CMSG_NXTHDR
419        // stay within it.
420        let mut header = unsafe { libc::CMSG_FIRSTHDR(&raw const message) };
421        while !header.is_null() {
422            // SAFETY: a header the kernel wrote, its data after it.
423            let (level, kind, data) = unsafe {
424                (
425                    (*header).cmsg_level,
426                    (*header).cmsg_type,
427                    libc::CMSG_DATA(header),
428                )
429            };
430            if level == libc::SOL_SOCKET && kind == SO_TIMESTAMPING {
431                // SAFETY: SCM_TIMESTAMPING carries three timespecs.
432                let stamps: [libc::timespec; 3] = unsafe { std::ptr::read_unaligned(data.cast()) };
433                time = super::raw_hardware(stamps.map(|stamp| (stamp.tv_sec, stamp.tv_nsec)));
434            }
435            if level == libc::SOL_PACKET && kind == PACKET_TX_TIMESTAMP {
436                // SAFETY: PACKET_TX_TIMESTAMP carries a sock_extended_err.
437                let error: ExtendedError = unsafe { std::ptr::read_unaligned(data.cast()) };
438                if error.origin == SO_EE_ORIGIN_TIMESTAMPING {
439                    number = Some(error.data);
440                }
441            }
442            // SAFETY: as above.
443            header = unsafe { libc::CMSG_NXTHDR(&raw const message, header) };
444        }
445        Ok(Some(Message {
446            length: length as usize,
447            time,
448            number,
449        }))
450    }
451
452    impl StampedSocket {
453        pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
454            let index = crate::interfaces::index_of(interface).ok_or_else(|| {
455                io::Error::new(
456                    io::ErrorKind::NotFound,
457                    format!("no interface named {interface}"),
458                )
459            })?;
460            let fd = crate::broker::open(crate::broker::Kind::Datagram)?;
461            // Frames sent ask for a time one by one, in send_stamped: asked
462            // here, every frame sent would leave one, follow ups too.
463            let flags = SOF_TIMESTAMPING_RX_HARDWARE
464                | SOF_TIMESTAMPING_RAW_HARDWARE
465                | SOF_TIMESTAMPING_OPT_ID
466                | SOF_TIMESTAMPING_OPT_TSONLY;
467            let value = flags as libc::c_int;
468            // SAFETY: `value` is a valid c_int that lives through the call,
469            // and the length passed is its size.
470            let set = unsafe {
471                libc::setsockopt(
472                    fd.as_raw_fd(),
473                    libc::SOL_SOCKET,
474                    SO_TIMESTAMPING,
475                    (&raw const value).cast(),
476                    size_of::<libc::c_int>() as libc::socklen_t,
477                )
478            };
479            if set < 0 {
480                return Err(io::Error::last_os_error());
481            }
482            let socket = Self {
483                fd,
484                index,
485                ethertype,
486                stamped: AtomicU32::new(0),
487                numbered: AtomicBool::new(false),
488            };
489            let address = socket.address(None);
490            // SAFETY: `address` is a valid sockaddr_ll that lives through the
491            // call, and the length passed is its size.
492            let bound = unsafe {
493                libc::bind(
494                    socket.fd.as_raw_fd(),
495                    (&raw const address).cast(),
496                    size_of::<libc::sockaddr_ll>() as libc::socklen_t,
497                )
498            };
499            if bound < 0 {
500                return Err(io::Error::last_os_error());
501            }
502            Ok(socket)
503        }
504
505        fn address(&self, destination: Option<MacAddress>) -> libc::sockaddr_ll {
506            // SAFETY: sockaddr_ll is plain data, valid when zeroed.
507            let mut address: libc::sockaddr_ll = unsafe { zeroed() };
508            address.sll_family = libc::AF_PACKET as u16;
509            address.sll_protocol = self.ethertype.to_be();
510            address.sll_ifindex = self.index;
511            if let Some(destination) = destination {
512                address.sll_halen = 6;
513                address.sll_addr[..6].copy_from_slice(&destination.0);
514            }
515            address
516        }
517
518        pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
519            // SAFETY: packet_mreq is plain data, valid when zeroed.
520            let mut request: libc::packet_mreq = unsafe { zeroed() };
521            request.mr_ifindex = self.index;
522            request.mr_type = libc::PACKET_MR_MULTICAST as u16;
523            request.mr_alen = 6;
524            request.mr_address[..6].copy_from_slice(&group.0);
525            // SAFETY: `request` is a valid packet_mreq that lives through the
526            // call, and the length passed is its size.
527            let joined = unsafe {
528                libc::setsockopt(
529                    self.fd.as_raw_fd(),
530                    libc::SOL_PACKET,
531                    libc::PACKET_ADD_MEMBERSHIP,
532                    (&raw const request).cast(),
533                    size_of::<libc::packet_mreq>() as libc::socklen_t,
534                )
535            };
536            if joined < 0 {
537                return Err(io::Error::last_os_error());
538            }
539            Ok(())
540        }
541
542        pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
543            let address = self.address(Some(destination));
544            // SAFETY: `payload` and `address` are valid for the lengths
545            // passed and live through the call.
546            let sent = unsafe {
547                libc::sendto(
548                    self.fd.as_raw_fd(),
549                    payload.as_ptr().cast(),
550                    payload.len(),
551                    0,
552                    (&raw const address).cast(),
553                    size_of::<libc::sockaddr_ll>() as libc::socklen_t,
554                )
555            };
556            if sent < 0 {
557                return Err(io::Error::last_os_error());
558            }
559            Ok(())
560        }
561
562        fn drop_late_times(&self) -> io::Result<()> {
563            // SAFETY: plain data, valid when zeroed.
564            let mut stale: libc::sockaddr_ll = unsafe { zeroed() };
565            let mut buffer = [0u8; 64];
566            while receive_message(&self.fd, &mut buffer, &mut stale, libc::MSG_ERRQUEUE)?.is_some()
567            {
568            }
569            Ok(())
570        }
571
572        pub fn send_stamped(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
573            self.drop_late_times()?;
574            let mut address = self.address(Some(destination));
575            let mut part = libc::iovec {
576                iov_base: payload.as_ptr().cast_mut().cast(),
577                iov_len: payload.len(),
578            };
579            let mut control = [0u64; 4];
580            // SAFETY: msghdr is plain data, valid when zeroed.
581            let mut message: libc::msghdr = unsafe { zeroed() };
582            message.msg_name = (&raw mut address).cast();
583            message.msg_namelen = size_of::<libc::sockaddr_ll>() as libc::socklen_t;
584            message.msg_iov = &raw mut part;
585            message.msg_iovlen = 1;
586            message.msg_control = control.as_mut_ptr().cast();
587            // SAFETY: CMSG_SPACE only works out a length.
588            message.msg_controllen = unsafe { libc::CMSG_SPACE(size_of::<u32>() as u32) } as _;
589            // SAFETY: `control` has room for one control message carrying a
590            // u32, as msg_controllen says, so CMSG_FIRSTHDR points into it.
591            unsafe {
592                let header = libc::CMSG_FIRSTHDR(&raw const message);
593                (*header).cmsg_level = libc::SOL_SOCKET;
594                (*header).cmsg_type = SO_TIMESTAMPING;
595                (*header).cmsg_len = libc::CMSG_LEN(size_of::<u32>() as u32) as _;
596                std::ptr::write_unaligned(
597                    libc::CMSG_DATA(header).cast::<u32>(),
598                    SOF_TIMESTAMPING_TX_HARDWARE,
599                );
600            }
601            // SAFETY: every buffer the message points to lives through the
602            // call, with its length given.
603            if unsafe { libc::sendmsg(self.fd.as_raw_fd(), &raw const message, 0) } < 0 {
604                return Err(io::Error::last_os_error());
605            }
606            self.stamped.fetch_add(1, Ordering::Relaxed);
607            Ok(())
608        }
609
610        pub fn transmit_time(&self, timeout: Duration) -> io::Result<Option<Duration>> {
611            let deadline = std::time::Instant::now() + timeout;
612            let wanted = self.stamped.load(Ordering::Relaxed).wrapping_sub(1);
613            loop {
614                // SAFETY: plain data, valid when zeroed.
615                let mut address: libc::sockaddr_ll = unsafe { zeroed() };
616                let mut buffer = [0u8; 64];
617                if let Some(message) =
618                    receive_message(&self.fd, &mut buffer, &mut address, libc::MSG_ERRQUEUE)?
619                {
620                    match taken(message.number, wanted, &self.numbered) {
621                        Taken::Late => continue,
622                        Taken::Ahead(number) => {
623                            self.stamped
624                                .store(number.wrapping_add(1), Ordering::Relaxed);
625                        }
626                        Taken::Wanted => {}
627                    }
628                    return Ok(message.time);
629                }
630                let left = deadline.saturating_duration_since(std::time::Instant::now());
631                if left.is_zero() || !wait(&self.fd, 0, Some(left))? {
632                    return Ok(None);
633                }
634            }
635        }
636
637        pub fn receive(
638            &self,
639            buffer: &mut [u8],
640            timeout: Option<Duration>,
641        ) -> io::Result<Option<Received>> {
642            if !wait(&self.fd, libc::POLLIN, timeout)? {
643                return Ok(None);
644            }
645            // SAFETY: plain data, valid when zeroed.
646            let mut address: libc::sockaddr_ll = unsafe { zeroed() };
647            loop {
648                let Some(Message { length, time, .. }) =
649                    receive_message(&self.fd, buffer, &mut address, 0)?
650                else {
651                    return Ok(None);
652                };
653                // Frames this computer sends come back as outgoing.
654                if address.sll_pkttype == libc::PACKET_OUTGOING {
655                    continue;
656                }
657                let mut source = [0; 6];
658                source.copy_from_slice(&address.sll_addr[..6]);
659                return Ok(Some(Received {
660                    source: MacAddress(source),
661                    length: length.min(buffer.len()),
662                    time,
663                }));
664            }
665        }
666    }
667}
668
669#[cfg(not(target_os = "linux"))]
670mod platform {
671    use std::io;
672    use std::time::Duration;
673
674    use super::Received;
675    use crate::MacAddress;
676
677    fn unsupported() -> io::Error {
678        io::Error::new(
679            io::ErrorKind::Unsupported,
680            "hardware time stamps are not supported on this system yet",
681        )
682    }
683
684    pub fn enable(_interface: &str) -> io::Result<()> {
685        Err(unsupported())
686    }
687
688    pub fn wait_any(
689        _sockets: &[&StampedSocket],
690        _timeout: Option<Duration>,
691    ) -> io::Result<Vec<usize>> {
692        Err(unsupported())
693    }
694
695    pub struct StampedSocket;
696
697    impl StampedSocket {
698        pub fn open(_interface: &str, _ethertype: u16) -> io::Result<Self> {
699            Err(unsupported())
700        }
701
702        pub fn join_multicast(&self, _group: MacAddress) -> io::Result<()> {
703            Err(unsupported())
704        }
705
706        pub fn send(&self, _destination: MacAddress, _payload: &[u8]) -> io::Result<()> {
707            Err(unsupported())
708        }
709
710        pub fn send_stamped(&self, _destination: MacAddress, _payload: &[u8]) -> io::Result<()> {
711            Err(unsupported())
712        }
713
714        pub fn transmit_time(&self, _timeout: Duration) -> io::Result<Option<Duration>> {
715            Err(unsupported())
716        }
717
718        pub fn receive(
719            &self,
720            _buffer: &mut [u8],
721            _timeout: Option<Duration>,
722        ) -> io::Result<Option<Received>> {
723            Err(unsupported())
724        }
725    }
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731
732    #[cfg(target_os = "linux")]
733    #[test]
734    fn a_wait_wakes_for_the_other_too() {
735        use std::os::fd::AsFd;
736        use std::os::unix::net::UnixDatagram;
737        let (near, far) = UnixDatagram::pair().expect("pair");
738        let started = std::time::Instant::now();
739        let none = wait_any_or(&[], near.as_fd(), Some(Duration::from_millis(20))).expect("wait");
740        assert_eq!(none, (Vec::new(), false));
741        far.send(b"changed").expect("send");
742        let woken = wait_any_or(&[], near.as_fd(), Some(Duration::from_secs(5))).expect("wait");
743        assert_eq!(woken, (Vec::new(), true));
744        assert!(started.elapsed() < Duration::from_secs(1));
745    }
746
747    #[test]
748    fn a_time_sent_pairs_by_its_number_once_the_kernel_numbers_them() {
749        let numbered = AtomicBool::new(false);
750        assert_eq!(taken(None, 7, &numbered), Taken::Wanted);
751        // The first frame is 0 either way; 0 again says nothing yet.
752        assert_eq!(taken(Some(0), 0, &numbered), Taken::Wanted);
753        assert_eq!(taken(Some(0), 1, &numbered), Taken::Wanted);
754        assert_eq!(taken(Some(2), 2, &numbered), Taken::Wanted);
755        assert_eq!(taken(Some(1), 2, &numbered), Taken::Late);
756        assert_eq!(taken(Some(4), 3, &numbered), Taken::Ahead(4));
757        assert_eq!(taken(Some(u32::MAX), 0, &numbered), Taken::Late);
758        assert_eq!(taken(Some(0), u32::MAX, &numbered), Taken::Ahead(0));
759    }
760
761    #[test]
762    fn a_kernel_that_numbers_nothing_has_its_times_taken_in_order() {
763        let numbered = AtomicBool::new(false);
764        for wanted in 0..5 {
765            assert_eq!(taken(Some(0), wanted, &numbered), Taken::Wanted);
766        }
767    }
768
769    #[test]
770    fn the_raw_hardware_time_is_the_last_of_three() {
771        assert_eq!(
772            raw_hardware([(1_793_300_000, 5), (0, 0), (265_258, 495_597_656)]),
773            Some(Duration::new(265_258, 495_597_656))
774        );
775        assert_eq!(raw_hardware([(1_793_300_000, 5), (0, 0), (0, 0)]), None);
776    }
777}