Skip to main content

raw_ether/
interfaces.rs

1//! The Ethernet interfaces of this computer and what each can do.
2
3use crate::MacAddress;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Interface {
7    pub name: String,
8    pub mac: MacAddress,
9    /// The link is up.
10    pub up: bool,
11    /// Link speed in Mb/s, when the driver reports it.
12    pub speed: Option<u32>,
13    /// Backed by hardware, not a bridge, tunnel or other virtual device.
14    pub physical: bool,
15    pub wireless: bool,
16    /// Index of the PTP hardware clock, on interfaces that timestamp in
17    /// hardware.
18    pub hardware_clock: Option<u32>,
19}
20
21/// The Ethernet interfaces, physical and up first, then by name.
22pub fn interfaces() -> Vec<Interface> {
23    let mut found = platform::interfaces();
24    found.sort_by(|left, right| {
25        (!left.physical, !left.up, &left.name).cmp(&(!right.physical, !right.up, &right.name))
26    });
27    found
28}
29
30/// The MAC address of the interface named `name`.
31pub fn mac_of(name: &str) -> Option<MacAddress> {
32    platform::interfaces()
33        .into_iter()
34        .find(|interface| interface.name == name)
35        .map(|interface| interface.mac)
36}
37
38/// The kernel's index for the interface named `name`.
39#[cfg(target_os = "linux")]
40pub fn index_of(name: &str) -> Option<i32> {
41    if name.contains('/') {
42        return None;
43    }
44    std::fs::read_to_string(format!("/sys/class/net/{name}/ifindex"))
45        .ok()?
46        .trim()
47        .parse()
48        .ok()
49}
50
51/// What an interface does about Energy-Efficient Ethernet and PAUSE, as
52/// its driver reports it. The AVB Lite profile asks endpoints to keep both
53/// off their own link.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55pub struct LinkPower {
56    /// EEE is enabled, so the interface advertises it and its link may
57    /// sleep between frames.
58    pub eee: bool,
59    /// The interface sends PAUSE or acts on it, or offers to when it
60    /// negotiates.
61    pub pause: bool,
62}
63
64/// What the interface named `name` does about EEE and PAUSE, read without
65/// privileges. What the driver does not support reads as off.
66#[cfg(target_os = "linux")]
67pub fn link_power(name: &str) -> std::io::Result<LinkPower> {
68    ethtool::link_power(name)
69}
70
71/// Whether the interface named `name` drops VLAN-tagged frames in hardware
72/// unless their VLAN is registered with it, as Intel's igb and igc do with
73/// `rx-vlan-filter` on, read without privileges. A packet socket hears a
74/// stream's tagged frames there only with the interface promiscuous, which
75/// turns the filter off.
76#[cfg(target_os = "linux")]
77pub fn filters_vlans(name: &str) -> std::io::Result<bool> {
78    ethtool::filters_vlans(name)
79}
80
81/// Word from Linux, by netlink, that a link changed: came up, went down,
82/// or joined or left a bridge. It says only that something changed, so
83/// what did is read as before, and read at once rather than at the next
84/// look.
85#[cfg(target_os = "linux")]
86pub struct LinkChanges {
87    fd: std::os::fd::OwnedFd,
88}
89
90#[cfg(target_os = "linux")]
91#[allow(unsafe_code)]
92impl LinkChanges {
93    /// Listens for links changing, which needs no privileges.
94    pub fn open() -> std::io::Result<Self> {
95        use std::io;
96        use std::mem::{size_of, zeroed};
97        use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
98
99        // SAFETY: socket(2) takes no memory.
100        let fd = unsafe {
101            libc::socket(
102                libc::AF_NETLINK,
103                libc::SOCK_RAW | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
104                libc::NETLINK_ROUTE,
105            )
106        };
107        if fd < 0 {
108            return Err(io::Error::last_os_error());
109        }
110        // SAFETY: `fd` is a new socket nothing else owns.
111        let fd = unsafe { OwnedFd::from_raw_fd(fd) };
112        // SAFETY: sockaddr_nl is plain data, valid when zeroed.
113        let mut address: libc::sockaddr_nl = unsafe { zeroed() };
114        address.nl_family = libc::AF_NETLINK as libc::sa_family_t;
115        address.nl_groups = libc::RTMGRP_LINK as u32;
116        // SAFETY: `address` is a sockaddr_nl of the length given.
117        let bound = unsafe {
118            libc::bind(
119                fd.as_raw_fd(),
120                std::ptr::from_ref(&address).cast(),
121                size_of::<libc::sockaddr_nl>() as libc::socklen_t,
122            )
123        };
124        if bound < 0 {
125            return Err(io::Error::last_os_error());
126        }
127        Ok(Self { fd })
128    }
129
130    /// Takes all the word waiting, without blocking: whether any came. A
131    /// queue that overflowed lost some, so it says yes.
132    pub fn take(&self) -> std::io::Result<bool> {
133        use std::io;
134        use std::os::fd::AsRawFd;
135
136        let mut buffer = [0u8; 8192];
137        let mut changed = false;
138        loop {
139            // SAFETY: `buffer` is writable for its length.
140            let length = unsafe {
141                libc::recv(
142                    self.fd.as_raw_fd(),
143                    buffer.as_mut_ptr().cast(),
144                    buffer.len(),
145                    libc::MSG_DONTWAIT,
146                )
147            };
148            if length > 0 {
149                changed = true;
150                continue;
151            }
152            if length == 0 {
153                return Ok(changed);
154            }
155            let error = io::Error::last_os_error();
156            match error.raw_os_error() {
157                Some(libc::EAGAIN) => return Ok(changed),
158                Some(libc::EINTR) => {}
159                Some(libc::ENOBUFS) => changed = true,
160                _ => return Err(error),
161            }
162        }
163    }
164}
165
166#[cfg(target_os = "linux")]
167impl std::os::fd::AsFd for LinkChanges {
168    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
169        self.fd.as_fd()
170    }
171}
172
173#[cfg(target_os = "linux")]
174#[allow(unsafe_code)]
175mod ethtool {
176    use std::io;
177    use std::mem::zeroed;
178    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
179
180    use super::LinkPower;
181
182    /// The ethtool commands read here (linux/ethtool.h).
183    const GET_PAUSE: u32 = 0x12;
184    const GET_STRINGS: u32 = 0x1b;
185    const GET_SSET_INFO: u32 = 0x37;
186    const GET_FEATURES: u32 = 0x3a;
187    const GET_EEE: u32 = 0x44;
188    /// `ETH_SS_FEATURES`, the string set naming the netdev features.
189    const FEATURE_NAMES: u32 = 4;
190    /// `ETH_GSTRING_LEN`, each name's room in a string set.
191    const NAME_LENGTH: usize = 32;
192    /// The feature that drops tagged frames of VLANs not registered.
193    const VLAN_FILTER: &[u8] = b"rx-vlan-filter";
194
195    /// `struct ethtool_pauseparam`.
196    #[repr(C)]
197    #[derive(Default)]
198    struct Pause {
199        cmd: u32,
200        autoneg: u32,
201        rx_pause: u32,
202        tx_pause: u32,
203    }
204
205    /// `struct ethtool_eee`.
206    #[repr(C)]
207    #[derive(Default)]
208    struct Eee {
209        cmd: u32,
210        supported: u32,
211        advertised: u32,
212        lp_advertised: u32,
213        eee_active: u32,
214        eee_enabled: u32,
215        tx_lpi_enabled: u32,
216        tx_lpi_timer: u32,
217        reserved: [u32; 2],
218    }
219
220    /// `struct ethtool_sset_info`, with room for the one count asked.
221    #[repr(C)]
222    #[derive(Default)]
223    struct SetInfo {
224        cmd: u32,
225        reserved: u32,
226        mask: u64,
227        count: u32,
228    }
229
230    pub fn link_power(name: &str) -> io::Result<LinkPower> {
231        let socket = control(name)?;
232        let bytes = name.as_bytes();
233        let mut pause = Pause {
234            cmd: GET_PAUSE,
235            ..Pause::default()
236        };
237        let mut eee = Eee {
238            cmd: GET_EEE,
239            ..Eee::default()
240        };
241        let pause = match ask(&socket, bytes, (&raw mut pause).cast()) {
242            // Negotiating PAUSE while sending and taking none advertises
243            // none, so it stays off.
244            Ok(()) => pause.rx_pause != 0 || pause.tx_pause != 0,
245            Err(error) if unsupported(&error) => false,
246            Err(error) => return Err(error),
247        };
248        let eee = match ask(&socket, bytes, (&raw mut eee).cast()) {
249            Ok(()) => eee.eee_enabled != 0,
250            Err(error) if unsupported(&error) => false,
251            Err(error) => return Err(error),
252        };
253        Ok(LinkPower { eee, pause })
254    }
255
256    pub fn filters_vlans(name: &str) -> io::Result<bool> {
257        let socket = control(name)?;
258        let bytes = name.as_bytes();
259        let mut info = SetInfo {
260            cmd: GET_SSET_INFO,
261            mask: 1 << FEATURE_NAMES,
262            ..SetInfo::default()
263        };
264        match ask(&socket, bytes, (&raw mut info).cast()) {
265            Ok(()) => {}
266            Err(error) if unsupported(&error) => return Ok(false),
267            Err(error) => return Err(error),
268        }
269        let count = info.count as usize;
270        // `struct ethtool_gstrings`: the command, the set and the count,
271        // then each name in its room.
272        let mut names = vec![0u32; 3 + count * NAME_LENGTH / 4];
273        names[..3].copy_from_slice(&[GET_STRINGS, FEATURE_NAMES, info.count]);
274        ask(&socket, bytes, names.as_mut_ptr().cast())?;
275        let text: Vec<u8> = names[3..]
276            .iter()
277            .flat_map(|word| word.to_ne_bytes())
278            .collect();
279        let Some(index) = text
280            .chunks(NAME_LENGTH)
281            .position(|room| room.split(|&byte| byte == 0).next() == Some(VLAN_FILTER))
282        else {
283            return Ok(false);
284        };
285        // `struct ethtool_gfeatures`: the command and the block count, then
286        // for each 32 features what is available, requested, active and
287        // never changed.
288        let blocks = count.div_ceil(32);
289        let mut features = vec![0u32; 2 + blocks * 4];
290        features[..2].copy_from_slice(&[GET_FEATURES, blocks as u32]);
291        ask(&socket, bytes, features.as_mut_ptr().cast())?;
292        let active = features[2 + index / 32 * 4 + 2];
293        Ok(active & (1 << (index % 32)) != 0)
294    }
295
296    /// A socket to hand the driver of the interface named `name` ethtool
297    /// commands through.
298    fn control(name: &str) -> io::Result<OwnedFd> {
299        let bytes = name.as_bytes();
300        if bytes.is_empty() || bytes.len() >= libc::IFNAMSIZ || bytes.contains(&0) {
301            return Err(io::Error::new(
302                io::ErrorKind::InvalidInput,
303                "no such interface name",
304            ));
305        }
306        // SAFETY: socket takes plain integers; the result is checked.
307        let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) };
308        if fd < 0 {
309            return Err(io::Error::last_os_error());
310        }
311        // SAFETY: fd is a new socket nothing else owns.
312        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
313    }
314
315    fn unsupported(error: &io::Error) -> bool {
316        matches!(error.raw_os_error(), Some(libc::EOPNOTSUPP | libc::EINVAL))
317    }
318
319    /// Hands the interface's driver the ethtool command `data` points to.
320    fn ask(socket: &OwnedFd, name: &[u8], data: *mut libc::c_char) -> io::Result<()> {
321        // SAFETY: ifreq is plain data, valid when zeroed.
322        let mut request: libc::ifreq = unsafe { zeroed() };
323        for (place, &byte) in request.ifr_name.iter_mut().zip(name) {
324            *place = byte as libc::c_char;
325        }
326        request.ifr_ifru.ifru_data = data;
327        // SAFETY: `request` is a valid ifreq whose data points to an ethtool
328        // command struct of the size its command reads, both living through
329        // the call.
330        if unsafe { libc::ioctl(socket.as_raw_fd(), libc::SIOCETHTOOL, &raw mut request) } < 0 {
331            return Err(io::Error::last_os_error());
332        }
333        Ok(())
334    }
335}
336
337#[cfg(target_os = "linux")]
338mod platform {
339    use std::fs;
340    use std::path::Path;
341
342    use super::Interface;
343
344    /// `ARPHRD_ETHER`, the link type of Ethernet and Wi-Fi interfaces.
345    const LINK_TYPE_ETHERNET: u32 = 1;
346
347    pub fn interfaces() -> Vec<Interface> {
348        let Ok(entries) = fs::read_dir("/sys/class/net") else {
349            return Vec::new();
350        };
351        entries
352            .flatten()
353            .filter_map(|entry| read(&entry.path(), entry.file_name().to_str()?))
354            .collect()
355    }
356
357    fn read(dir: &Path, name: &str) -> Option<Interface> {
358        let value = |file: &str| fs::read_to_string(dir.join(file)).ok();
359        let link_type: u32 = value("type")?.trim().parse().ok()?;
360        if link_type != LINK_TYPE_ETHERNET {
361            return None;
362        }
363        let mac = value("address")?.trim().parse().ok()?;
364        Some(Interface {
365            name: name.to_owned(),
366            mac,
367            up: value("operstate").is_some_and(|state| state.trim() == "up"),
368            // Negative or unreadable while the link is down.
369            speed: value("speed").and_then(|speed| speed.trim().parse().ok()),
370            physical: dir.join("device").exists(),
371            wireless: dir.join("wireless").exists() || dir.join("phy80211").exists(),
372            hardware_clock: hardware_clock(dir),
373        })
374    }
375
376    /// The `ptpN` the driver registered for the interface, as `ethtool -T`
377    /// reports: under the PCI device for most drivers (igb, igc, mlx5),
378    /// under the interface itself for some (atlantic).
379    pub(super) fn hardware_clock(dir: &Path) -> Option<u32> {
380        let clocks = |folder: std::path::PathBuf| {
381            fs::read_dir(folder)
382                .into_iter()
383                .flatten()
384                .flatten()
385                .filter_map(|entry| {
386                    entry
387                        .file_name()
388                        .to_str()?
389                        .strip_prefix("ptp")?
390                        .parse::<u32>()
391                        .ok()
392                })
393        };
394        clocks(dir.join("device/ptp"))
395            .chain(clocks(dir.to_path_buf()))
396            .min()
397    }
398}
399
400#[cfg(target_os = "macos")]
401#[allow(unsafe_code)]
402mod platform {
403    use std::ffi::CStr;
404    use std::mem::{offset_of, size_of, zeroed};
405    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
406
407    use super::Interface;
408    use crate::MacAddress;
409
410    /// `IFT_ETHER`, the link type of Ethernet and Wi-Fi interfaces.
411    const LINK_TYPE_ETHERNET: u8 = 6;
412    /// The network type in a media word (`IFM_NMASK`), and its values for
413    /// Ethernet and Wi-Fi.
414    const MEDIA_NETWORK: i32 = 0xe0;
415    const MEDIA_WIFI: i32 = 0x80;
416    /// The media status word says whether the link is up (`IFM_AVALID`),
417    /// and that it is (`IFM_ACTIVE`).
418    const MEDIA_STATUS_VALID: i32 = 0x01;
419    const MEDIA_ACTIVE: i32 = 0x02;
420
421    /// `struct ifmediareq`, for `SIOCGIFMEDIA`, packed to four octets as
422    /// macOS declares it.
423    #[derive(Clone, Copy)]
424    #[repr(C, packed(4))]
425    struct MediaRequest {
426        name: [libc::c_char; libc::IFNAMSIZ],
427        current: i32,
428        mask: i32,
429        status: i32,
430        active: i32,
431        count: i32,
432        list: *mut i32,
433    }
434
435    pub fn interfaces() -> Vec<Interface> {
436        let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
437        // SAFETY: getifaddrs fills `head` with a list freed below.
438        if unsafe { libc::getifaddrs(&raw mut head) } != 0 {
439            return Vec::new();
440        }
441        // A socket to ask each interface about its media on.
442        // SAFETY: plain system call with integer arguments.
443        let raw = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) };
444        // SAFETY: `raw`, when valid, is a socket this function owns.
445        let query = (raw >= 0).then(|| unsafe { OwnedFd::from_raw_fd(raw) });
446        let mut found = Vec::new();
447        let mut entry = head;
448        while !entry.is_null() {
449            // SAFETY: each entry of the list getifaddrs made is valid until
450            // it is freed.
451            let address = unsafe { &*entry };
452            entry = address.ifa_next;
453            if let Some(interface) = read(address, query.as_ref()) {
454                found.push(interface);
455            }
456        }
457        // SAFETY: `head` came from getifaddrs and is freed once.
458        unsafe { libc::freeifaddrs(head) };
459        found
460    }
461
462    /// The interface an `AF_LINK` entry describes, when it is Ethernet.
463    fn read(address: &libc::ifaddrs, query: Option<&OwnedFd>) -> Option<Interface> {
464        if address.ifa_addr.is_null() {
465            return None;
466        }
467        // SAFETY: a non-null address points at a sockaddr at least as long
468        // as its header.
469        if i32::from(unsafe { (*address.ifa_addr).sa_family }) != libc::AF_LINK {
470            return None;
471        }
472        // SAFETY: an AF_LINK address is a sockaddr_dl.
473        let link = unsafe { &*address.ifa_addr.cast::<libc::sockaddr_dl>() };
474        if link.sdl_type != LINK_TYPE_ETHERNET || link.sdl_alen != 6 {
475            return None;
476        }
477        // The address follows the name in `sdl_data`, within `sdl_len`.
478        let start = offset_of!(libc::sockaddr_dl, sdl_data) + usize::from(link.sdl_nlen);
479        if start + 6 > usize::from(link.sdl_len) {
480            return None;
481        }
482        let mut mac = [0; 6];
483        // SAFETY: the six octets lie within the address, as checked.
484        unsafe {
485            std::ptr::copy_nonoverlapping(
486                (link as *const libc::sockaddr_dl).cast::<u8>().add(start),
487                mac.as_mut_ptr(),
488                6,
489            );
490        }
491        // SAFETY: the name is a NUL-terminated string in the entry.
492        let bsd_name = unsafe { CStr::from_ptr(address.ifa_name) };
493        let name = bsd_name.to_string_lossy().into_owned();
494        let speed = (!address.ifa_data.is_null())
495            .then(|| {
496                // SAFETY: an AF_LINK entry's data is its if_data.
497                unsafe { (*address.ifa_data.cast::<libc::if_data>()).ifi_baudrate }
498            })
499            .filter(|&bits| bits > 0)
500            .map(|bits| bits / 1_000_000);
501        let media = query.and_then(|query| media(query, &name));
502        let flags = address.ifa_flags as i32;
503        let up = flags & libc::IFF_UP != 0
504            && match media {
505                Some(media) if media.status & MEDIA_STATUS_VALID != 0 => {
506                    media.status & MEDIA_ACTIVE != 0
507                }
508                _ => flags & libc::IFF_RUNNING != 0,
509            };
510        Some(Interface {
511            // macOS names its Ethernet and Wi-Fi ports enN; anpi, ap, awdl,
512            // llw and the like are its own, and so are some enN.
513            physical: name.starts_with("en") && !without_port(bsd_name),
514            wireless: media.is_some_and(|media| media.current & MEDIA_NETWORK == MEDIA_WIFI),
515            name,
516            mac: MacAddress(mac),
517            up,
518            speed: speed.filter(|_| up),
519            hardware_clock: None,
520        })
521    }
522
523    /// Whether the interface named `name` has no Ethernet port of its
524    /// own, as its controller shows: Thunderbolt Bridge's IP over
525    /// Thunderbolt, or a USB-C port being a USB network device for another
526    /// computer.
527    fn without_port(name: &CStr) -> bool {
528        const CONTROLLERS: [&CStr; 2] = [c"AppleThunderboltIPPort", c"AppleUSBDeviceNCMData"];
529        // SAFETY: IOServiceGetMatchingService takes the matching dictionary
530        // IOBSDNameMatching made, and each object found is released once.
531        unsafe {
532            let matching = iokit::IOBSDNameMatching(iokit::MAIN_PORT, 0, name.as_ptr());
533            if matching.is_null() {
534                return false;
535            }
536            let interface = iokit::IOServiceGetMatchingService(iokit::MAIN_PORT, matching);
537            if interface == 0 {
538                return false;
539            }
540            let mut controller = 0;
541            let found = iokit::IORegistryEntryGetParentEntry(
542                interface,
543                c"IOService".as_ptr(),
544                &raw mut controller,
545            ) == 0;
546            iokit::IOObjectRelease(interface);
547            if !found {
548                return false;
549            }
550            let without = CONTROLLERS
551                .iter()
552                .any(|class| iokit::IOObjectConformsTo(controller, class.as_ptr()) != 0);
553            iokit::IOObjectRelease(controller);
554            without
555        }
556    }
557
558    /// The few IOKit calls that look up an interface's controller.
559    mod iokit {
560        use std::ffi::{c_char, c_void};
561
562        /// `kIOMainPortDefault`.
563        pub const MAIN_PORT: u32 = 0;
564
565        #[link(name = "IOKit", kind = "framework")]
566        unsafe extern "C" {
567            pub fn IOBSDNameMatching(port: u32, options: u32, name: *const c_char) -> *mut c_void;
568            pub fn IOServiceGetMatchingService(port: u32, matching: *mut c_void) -> u32;
569            pub fn IORegistryEntryGetParentEntry(
570                entry: u32,
571                plane: *const c_char,
572                parent: *mut u32,
573            ) -> i32;
574            pub fn IOObjectConformsTo(object: u32, class: *const c_char) -> u32;
575            pub fn IOObjectRelease(object: u32) -> i32;
576        }
577    }
578
579    /// What `SIOCGIFMEDIA` says of the interface named `name`.
580    fn media(query: &OwnedFd, name: &str) -> Option<MediaRequest> {
581        // SAFETY: MediaRequest is plain data, valid when zeroed.
582        let mut request: MediaRequest = unsafe { zeroed() };
583        let bytes = name.as_bytes();
584        if bytes.len() >= request.name.len() {
585            return None;
586        }
587        for (place, &byte) in request.name.iter_mut().zip(bytes) {
588            *place = byte as libc::c_char;
589        }
590        // _IOWR('i', 56, struct ifmediareq)
591        let code = 0xc000_0000
592            | ((size_of::<MediaRequest>() as libc::c_ulong & 0x1fff) << 16)
593            | (libc::c_ulong::from(b'i') << 8)
594            | 56;
595        // SAFETY: `request` is a valid ifmediareq, with no list to fill,
596        // that lives through the call.
597        let result = unsafe { libc::ioctl(query.as_raw_fd(), code, &raw mut request) };
598        (result == 0).then_some(request)
599    }
600}
601
602/// The capture device Npcap knows the interface named `name` by.
603#[cfg(windows)]
604pub(crate) fn device_of(name: &str) -> Option<String> {
605    platform::adapters()
606        .into_iter()
607        .find(|(interface, _)| interface.name == name)
608        .map(|(_, guid)| format!("\\Device\\NPF_{guid}"))
609}
610
611#[cfg(windows)]
612#[allow(unsafe_code)]
613mod platform {
614    use windows_sys::Win32::NetworkManagement::IpHelper::{
615        GAA_FLAG_SKIP_ANYCAST, GAA_FLAG_SKIP_DNS_SERVER, GAA_FLAG_SKIP_MULTICAST,
616        GAA_FLAG_SKIP_UNICAST, GetAdaptersAddresses, GetIfEntry2, IF_TYPE_ETHERNET_CSMACD,
617        IF_TYPE_IEEE80211, IP_ADAPTER_ADDRESSES_LH, MIB_IF_ROW2,
618    };
619    use windows_sys::Win32::NetworkManagement::Ndis::IfOperStatusUp;
620
621    use super::Interface;
622    use crate::MacAddress;
623
624    /// `ERROR_BUFFER_OVERFLOW`, when the list outgrew the room given.
625    const BUFFER_OVERFLOW: u32 = 111;
626    /// The interface flag set when a connector is present, which is to
627    /// say a network adapter is (`ConnectorPresent`).
628    const CONNECTOR_PRESENT: u8 = 1 << 2;
629
630    pub fn interfaces() -> Vec<Interface> {
631        adapters()
632            .into_iter()
633            .map(|(interface, _)| interface)
634            .collect()
635    }
636
637    /// The Ethernet and Wi-Fi adapters, each with the GUID that names its
638    /// device.
639    pub fn adapters() -> Vec<(Interface, String)> {
640        let flags = GAA_FLAG_SKIP_UNICAST
641            | GAA_FLAG_SKIP_ANYCAST
642            | GAA_FLAG_SKIP_MULTICAST
643            | GAA_FLAG_SKIP_DNS_SERVER;
644        // Room for a few adapters first, then as much as Windows asks for.
645        let mut size: u32 = 16 * 1024;
646        let mut buffer: Vec<u64> = Vec::new();
647        for _ in 0..4 {
648            buffer = vec![0; (size as usize).div_ceil(8)];
649            // SAFETY: the buffer, eight-octet aligned, holds `size` octets
650            // and lives through the call.
651            let result = unsafe {
652                GetAdaptersAddresses(
653                    0,
654                    flags,
655                    std::ptr::null(),
656                    buffer.as_mut_ptr().cast(),
657                    &raw mut size,
658                )
659            };
660            match result {
661                0 => break,
662                BUFFER_OVERFLOW => buffer.clear(),
663                _ => return Vec::new(),
664            }
665        }
666        if buffer.is_empty() {
667            return Vec::new();
668        }
669        let mut found = Vec::new();
670        let mut entry = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();
671        while !entry.is_null() {
672            // SAFETY: each entry of the list lies within the buffer.
673            let adapter = unsafe { &*entry };
674            entry = adapter.Next;
675            if let Some(read) = read(adapter) {
676                found.push(read);
677            }
678        }
679        found
680    }
681
682    fn read(adapter: &IP_ADAPTER_ADDRESSES_LH) -> Option<(Interface, String)> {
683        let wireless = match adapter.IfType {
684            IF_TYPE_ETHERNET_CSMACD => false,
685            IF_TYPE_IEEE80211 => true,
686            _ => return None,
687        };
688        if adapter.PhysicalAddressLength != 6 || adapter.FriendlyName.is_null() {
689            return None;
690        }
691        let mut mac = [0; 6];
692        mac.copy_from_slice(&adapter.PhysicalAddress[..6]);
693        // SAFETY: the friendly name is a NUL-terminated wide string and the
694        // adapter name a NUL-terminated string, both within the list.
695        let (name, guid) = unsafe {
696            (
697                String::from_utf16_lossy(wide(adapter.FriendlyName)),
698                std::ffi::CStr::from_ptr(adapter.AdapterName.cast())
699                    .to_string_lossy()
700                    .into_owned(),
701            )
702        };
703        let up = adapter.OperStatus == IfOperStatusUp;
704        // SAFETY: MIB_IF_ROW2 is plain data, valid when zeroed; the call
705        // reads the LUID set in it and fills in the rest.
706        let physical = unsafe {
707            let mut row: MIB_IF_ROW2 = std::mem::zeroed();
708            row.InterfaceLuid = adapter.Luid;
709            GetIfEntry2(&raw mut row) == 0
710                && row.InterfaceAndOperStatusFlags._bitfield & CONNECTOR_PRESENT != 0
711        };
712        // Unknown speeds read as all ones.
713        let speed = (up && adapter.TransmitLinkSpeed != u64::MAX)
714            .then(|| u32::try_from(adapter.TransmitLinkSpeed / 1_000_000).ok())
715            .flatten()
716            .filter(|&speed| speed > 0);
717        Some((
718            Interface {
719                name,
720                mac: MacAddress(mac),
721                up,
722                speed,
723                physical,
724                wireless,
725                hardware_clock: None,
726            },
727            guid,
728        ))
729    }
730
731    /// The characters of a NUL-terminated wide string.
732    ///
733    /// # Safety
734    ///
735    /// `string` points at a NUL-terminated wide string that outlives the
736    /// slice.
737    unsafe fn wide<'a>(string: *const u16) -> &'a [u16] {
738        let mut length = 0;
739        // SAFETY: the string ends at a NUL, as the caller promises.
740        unsafe {
741            while *string.add(length) != 0 {
742                length += 1;
743            }
744            std::slice::from_raw_parts(string, length)
745        }
746    }
747}
748
749#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
750mod platform {
751    use super::Interface;
752
753    /// Not listed on this system yet.
754    pub fn interfaces() -> Vec<Interface> {
755        Vec::new()
756    }
757}
758
759#[cfg(all(test, target_os = "linux"))]
760mod tests {
761    use super::*;
762
763    #[test]
764    fn link_changes_need_no_privileges_and_never_block() {
765        let links = LinkChanges::open().expect("netlink");
766        links.take().expect("nothing waiting is no error");
767    }
768
769    #[test]
770    fn lists_without_loopback() {
771        assert!(interfaces().iter().all(|found| found.name != "lo"));
772    }
773
774    #[test]
775    fn finds_clocks_under_the_device_or_the_interface() {
776        let root = std::env::temp_dir().join(format!("raw-ether-clocks-{}", std::process::id()));
777        let device = root.join("igc0");
778        let own = root.join("atlantic0");
779        let none = root.join("r8169");
780        for folder in [
781            device.join("device/ptp/ptp2"),
782            own.join("ptp0"),
783            none.join("device"),
784        ] {
785            std::fs::create_dir_all(folder).unwrap();
786        }
787        // An entry that only starts like a clock is not one.
788        std::fs::create_dir_all(own.join("ptpx")).unwrap();
789        assert_eq!(platform::hardware_clock(&device), Some(2));
790        assert_eq!(platform::hardware_clock(&own), Some(0));
791        assert_eq!(platform::hardware_clock(&none), None);
792        std::fs::remove_dir_all(root).unwrap();
793    }
794}