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