1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Received {
24 pub source: MacAddress,
25 pub length: usize,
27 pub time: Option<Duration>,
30}
31
32pub struct StampedSocket {
35 inner: platform::StampedSocket,
36}
37
38impl StampedSocket {
39 pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
42 Ok(Self {
43 inner: platform::StampedSocket::open(interface, ethertype)?,
44 })
45 }
46
47 pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
49 self.inner.join_multicast(group)
50 }
51
52 pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
54 self.inner.send(destination, payload)
55 }
56
57 pub fn send_stamped(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
63 self.inner.send_stamped(destination, payload)
64 }
65
66 pub fn transmit_time(&self, timeout: Duration) -> io::Result<Option<Duration>> {
73 self.inner.transmit_time(timeout)
74 }
75
76 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
87pub 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#[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
109pub fn enable(interface: &str) -> io::Result<()> {
115 platform::enable(interface)
116}
117
118#[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#[cfg(any(target_os = "linux", test))]
129#[derive(Debug, PartialEq, Eq)]
130enum Taken {
131 Wanted,
133 Late,
135 Ahead(u32),
139}
140
141#[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 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 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 const SOF_TIMESTAMPING_OPT_ID: u32 = 1 << 7;
187 const SOF_TIMESTAMPING_OPT_TSONLY: u32 = 1 << 11;
189 const PACKET_TX_TIMESTAMP: libc::c_int = 16;
192 const SO_EE_ORIGIN_TIMESTAMPING: u8 = 4;
193
194 #[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 #[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 fn configure(
241 fd: &OwnedFd,
242 interface: &str,
243 request_code: libc::c_ulong,
244 config: &mut HardwareConfig,
245 ) -> io::Result<()> {
246 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 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 stamped: AtomicU32,
274 numbered: AtomicBool,
278 }
279
280 fn timeout_ms(timeout: Option<Duration>) -> libc::c_int {
281 match timeout {
282 Some(timeout) => timeout.as_nanos().div_ceil(1_000_000).min(i32::MAX as u128) as i32,
284 None => -1,
285 }
286 }
287
288 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 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 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 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 struct Message {
378 length: usize,
379 time: Option<Duration>,
380 number: Option<u32>,
381 }
382
383 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 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 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 let mut header = unsafe { libc::CMSG_FIRSTHDR(&raw const message) };
421 while !header.is_null() {
422 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 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 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 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 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 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 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 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 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 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 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 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 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 message.msg_controllen = unsafe { libc::CMSG_SPACE(size_of::<u32>() as u32) } as _;
589 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 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 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 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 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 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}