Skip to main content

zond_engine/system/interface/
link.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # What this machine is plugged into, as this engine needs it
10//!
11//! One type, [`Link`], owned by this crate so the public API does not carry the
12//! enumerating library's type or its platform defects. Where the facts come from
13//! is [`from_netdev`](Link::from_netdev)'s business alone.
14//!
15//! It carries only what the engine reads: speed, MTU, DNS servers and statistics
16//! are left out.
17
18use std::io;
19use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
20
21use crate::model::ip::range::{IpRange, cidr_range};
22use crate::model::ip::scoped::Zone;
23use crate::model::ip::set::IpSet;
24use crate::model::mac::MacAddr;
25
26/// One address an interface holds, and how much of it names the network.
27///
28/// The address is what a probe goes out *from*, and the network decides whether
29/// a target is on this link or beyond it.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub struct LinkAddress {
32    address: IpAddr,
33    prefix: u8,
34}
35
36impl LinkAddress {
37    /// An address and the length of its prefix.
38    ///
39    /// The prefix is clamped to what the family allows. A value past the end is
40    /// the platform reporting something impossible, and the address is still
41    /// worth having.
42    pub fn new(address: IpAddr, prefix: u8) -> Self {
43        let ceiling = if address.is_ipv4() { 32 } else { 128 };
44        Self {
45            address,
46            prefix: prefix.min(ceiling),
47        }
48    }
49
50    /// The address itself.
51    pub fn address(&self) -> IpAddr {
52        self.address
53    }
54
55    /// How many leading bits name the network.
56    pub fn prefix(&self) -> u8 {
57        self.prefix
58    }
59
60    /// Every address this prefix covers, network and broadcast included.
61    ///
62    /// This is what the link carries, as an on-link test needs; whether either
63    /// end is worth probing is the sweeper's decision.
64    pub fn network(&self) -> IpRange {
65        // `new` clamped the prefix to its family, the only way this could fail.
66        cidr_range(self.address, self.prefix).expect("a prefix clamped to its family")
67    }
68
69    /// Whether `ip` is on the same network as this address.
70    pub fn contains(&self, ip: &IpAddr) -> bool {
71        self.network().contains(ip)
72    }
73}
74
75/// What kind of thing a link is.
76///
77/// The engine asks only three questions of it: can it carry a link-layer probe,
78/// is it wireless (a pacing question), and is it the machine talking to itself.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80#[non_exhaustive]
81pub enum LinkKind {
82    /// Something a frame can be put on the wire of: Ethernet at any speed, and
83    /// the wired families that look like it from here.
84    Wired,
85    /// 802.11. Told apart from [`Wired`](Self::Wired) because a wireless link
86    /// answers slower and less predictably.
87    Wireless,
88    /// The machine talking to itself.
89    Loopback,
90    /// A tunnel, a virtual adapter, or anything else with no physical port
91    /// behind it. Capable of carrying IP and not of carrying a neighbour.
92    Virtual,
93}
94
95/// A network interface on this machine.
96///
97/// Built from the host's interface table by `from_netdev`, or by hand in a test.
98#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub struct Link {
100    name: String,
101    friendly_name: Option<String>,
102    index: u32,
103    mac: Option<MacAddr>,
104    addresses: Vec<LinkAddress>,
105    kind: LinkKind,
106    up: bool,
107    addressing: Addressing,
108    physical: bool,
109    default_route: bool,
110    gateway: bool,
111}
112
113impl Link {
114    /// A link with nothing on it but a name and a number.
115    ///
116    /// The starting point for a test, or for a caller describing a link this
117    /// machine cannot be asked about. Everything else is added through the
118    /// builders below.
119    pub fn new(name: impl Into<String>, index: u32) -> Self {
120        Self {
121            name: name.into(),
122            friendly_name: None,
123            index,
124            mac: None,
125            addresses: Vec::new(),
126            kind: LinkKind::Virtual,
127            up: false,
128            addressing: Addressing::Neither,
129            physical: false,
130            default_route: false,
131            gateway: false,
132        }
133    }
134
135    /// The hardware address this link answers at.
136    #[must_use]
137    pub fn with_mac(mut self, mac: MacAddr) -> Self {
138        self.mac = Some(mac);
139        self
140    }
141
142    /// The addresses it holds.
143    #[must_use]
144    pub fn with_addresses(mut self, addresses: Vec<LinkAddress>) -> Self {
145        self.addresses = addresses;
146        self
147    }
148
149    /// What kind of link it is.
150    #[must_use]
151    pub fn with_kind(mut self, kind: LinkKind) -> Self {
152        self.kind = kind;
153        self
154    }
155
156    /// Whether the operating system reports it as up.
157    #[must_use]
158    pub fn with_link_up(mut self, up: bool) -> Self {
159        self.up = up;
160        self
161    }
162
163    /// How addresses on this link reach anything.
164    #[must_use]
165    pub fn with_addressing(mut self, addressing: Addressing) -> Self {
166        self.addressing = addressing;
167        self
168    }
169
170    /// Whether there is real hardware behind it.
171    #[must_use]
172    pub fn with_physical(mut self, physical: bool) -> Self {
173        self.physical = physical;
174        self
175    }
176
177    /// Whether this machine's default route leaves by it.
178    #[must_use]
179    pub fn with_default_route(mut self, carries: bool) -> Self {
180        self.default_route = carries;
181        self
182    }
183
184    /// Whether a router is configured on the link.
185    #[must_use]
186    pub fn with_gateway(mut self, has: bool) -> Self {
187        self.gateway = has;
188        self
189    }
190
191    /// What the interface is called here.
192    ///
193    /// The platform's name, which every other call in this crate is keyed by.
194    /// On Windows it is the adapter's GUID.
195    pub fn name(&self) -> &str {
196        &self.name
197    }
198
199    /// What a person calls the interface, for a message addressed to one.
200    ///
201    /// The name the system settings show where the platform keeps one apart
202    /// from [`name`](Self::name): `Wi-Fi` or `vEthernet (WSL)` on Windows, where
203    /// the name is a GUID nobody recognises, and the display name on macOS.
204    /// Otherwise the name itself, which on Linux is what a person writes.
205    pub(crate) fn display_name(&self) -> &str {
206        self.friendly_name.as_deref().unwrap_or(&self.name)
207    }
208
209    /// Its number in this kernel's interface table.
210    ///
211    /// Valid for this boot only, so nothing durable is keyed by it. See [`Zone`].
212    pub fn index(&self) -> u32 {
213        self.index
214    }
215
216    /// The hardware address, where it has one.
217    ///
218    /// `None` for a link with no link layer to have one on: a tunnel, and
219    /// loopback on most platforms.
220    pub fn mac(&self) -> Option<MacAddr> {
221        self.mac
222    }
223
224    /// Every address this link holds.
225    pub fn addresses(&self) -> &[LinkAddress] {
226        &self.addresses
227    }
228
229    /// The IPv4 addresses among them.
230    pub fn ipv4(&self) -> impl Iterator<Item = (Ipv4Addr, u8)> + '_ {
231        self.addresses.iter().filter_map(|held| match held.address {
232            IpAddr::V4(v4) => Some((v4, held.prefix)),
233            IpAddr::V6(_) => None,
234        })
235    }
236
237    /// The IPv6 addresses among them.
238    pub fn ipv6(&self) -> impl Iterator<Item = (Ipv6Addr, u8)> + '_ {
239        self.addresses.iter().filter_map(|held| match held.address {
240            IpAddr::V6(v6) => Some((v6, held.prefix)),
241            IpAddr::V4(_) => None,
242        })
243    }
244
245    /// This link as a zone, for scoping a link-local address to it.
246    pub fn zone(&self) -> Zone {
247        Zone::new(self.index, self.name.clone())
248    }
249
250    /// What kind of link it is.
251    pub fn kind(&self) -> LinkKind {
252        self.kind
253    }
254
255    /// Whether the operating system reports it as up.
256    pub fn is_up(&self) -> bool {
257        self.up
258    }
259
260    /// Whether this is the machine talking to itself.
261    pub fn is_loopback(&self) -> bool {
262        self.kind == LinkKind::Loopback
263    }
264
265    /// Whether it is 802.11.
266    pub fn is_wireless(&self) -> bool {
267        self.kind == LinkKind::Wireless
268    }
269
270    /// Whether there is a physical port behind it.
271    ///
272    /// False for a tunnel, a hypervisor's virtual switch, and a VPN, none of
273    /// which has a neighbour to ARP for.
274    pub fn is_physical(&self) -> bool {
275        self.physical
276    }
277
278    /// Whether it can carry a broadcast.
279    pub fn is_broadcast(&self) -> bool {
280        self.addressing == Addressing::Broadcast
281    }
282
283    /// Whether it is a point-to-point link, which has one peer and no segment.
284    pub fn is_point_to_point(&self) -> bool {
285        self.addressing == Addressing::PointToPoint
286    }
287
288    /// Whether this machine's default route leaves by this link.
289    ///
290    /// The closest thing there is to "which network am I on", answerable the
291    /// same way on every platform. Hardware fields cannot tell: macOS presents
292    /// `awdl0` (AirDrop) and `llw0` as ordinary wired Ethernet.
293    pub fn carries_default_route(&self) -> bool {
294        self.default_route
295    }
296
297    /// Whether a router is configured on this link. True of a real LAN, false of
298    /// a host-only virtualisation bridge, which is what tells them apart when a
299    /// VPN owns the global default route.
300    pub fn has_gateway(&self) -> bool {
301        self.gateway
302    }
303
304    /// Whether it is a physical link that is not wireless.
305    ///
306    /// The one to prefer when there is a choice: a wired segment answers faster
307    /// and more consistently than 802.11.
308    pub fn is_wired(&self) -> bool {
309        self.kind == LinkKind::Wired
310    }
311
312    /// Whether a link-layer probe can be put on it.
313    ///
314    /// ARP and neighbour discovery need a segment with somebody else on it and
315    /// a hardware address to send from. A point-to-point link has a peer and no
316    /// segment, loopback has neither, and a link with no hardware address has
317    /// nothing to put in the frame.
318    pub fn carries_frames(&self) -> bool {
319        !self.is_point_to_point() && !self.is_loopback() && self.mac.is_some()
320    }
321}
322
323/// How addresses on a link reach anything, which decides what a scan may send
324/// out of it.
325///
326/// One value, since the platform's two flags are not independent.
327#[non_exhaustive]
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
329pub enum Addressing {
330    /// A shared segment: one frame sent to the broadcast address reaches every
331    /// host on the link, which is what a sweep of a local network needs.
332    Broadcast,
333
334    /// Exactly one peer at the far end, and no broadcast address to reach it
335    /// by. A tunnel or a dial-up link. Sweeping it means probing one host.
336    PointToPoint,
337
338    /// Neither. Loopback carries nothing to another machine at all, and some
339    /// virtual interfaces present the same way.
340    Neither,
341}
342
343impl Addressing {
344    /// What a platform's two flags amount to.
345    ///
346    /// A link reporting both `IFF_BROADCAST` and `IFF_POINTOPOINT` (which no
347    /// operating system does) is read as point-to-point, since broadcasting onto
348    /// something that is not a broadcast domain is the more expensive mistake.
349    pub(crate) fn of(broadcast: bool, point_to_point: bool) -> Self {
350        match (broadcast, point_to_point) {
351            (_, true) => Self::PointToPoint,
352            (true, false) => Self::Broadcast,
353            (false, false) => Self::Neither,
354        }
355    }
356}
357
358/// Every interface this machine has.
359///
360/// The one place the host is asked. Everything else in this crate takes
361/// [`Link`]s from a caller or from here, so a scan against a stated set of links
362/// and a scan against the real machine share a code path.
363///
364/// # Errors
365///
366/// When the host cannot be asked because the process has no descriptor free:
367/// `EMFILE`, or, where no shortage can be found, an error saying the table came
368/// back empty. Every host has a loopback interface, so an empty table means a
369/// read failed silently.
370///
371/// On macOS the first read in a process with no descriptor free is refused,
372/// because the system framework it goes through would segfault. Once one read
373/// has succeeded, later ones need no descriptor.
374pub fn interfaces() -> io::Result<Vec<Link>> {
375    Ok(host_table()?.into_iter().map(Link::from_netdev).collect())
376}
377
378/// [`interfaces`], or none where the host cannot be asked, for a reader with no
379/// error of its own to give.
380///
381/// The table is unreadable only in a process with no descriptor free, where
382/// nothing a reader would do with a link could open a socket either. A scan is
383/// refused before it starts in such a table; see
384/// [`too_few`](crate::system::descriptors::too_few).
385pub(crate) fn interfaces_or_none() -> Vec<Link> {
386    interfaces().unwrap_or_default()
387}
388
389/// The host's interface table as `netdev` reads it, with the one fact it reads
390/// wrong put right.
391///
392/// Every part of the crate that needs something [`Link`] does not carry, such as
393/// a gateway's hardware address, reads the table through here, so the correction
394/// and the refusal below hold everywhere. A census in
395/// `tests/hygiene/architecture.rs` enforces this.
396///
397/// The correction is to a point-to-point link's own address on Linux. `netdev`
398/// keeps the first of a netlink message's `IFA_ADDRESS` and `IFA_LOCAL`, which
399/// are one address on most links. On a point-to-point link configured with a
400/// peer (every pppd link, OpenVPN's p2p and net30 topologies) the kernel sends
401/// `IFA_ADDRESS` first and it names the far end. Uncorrected, the VPN's gateway
402/// would be reported as this machine, and the tunnel's real address would be
403/// missing as a source.
404///
405/// The refusal is of a read that would end the process; see [`asked_safely`].
406/// `netdev` returns an empty table on failure, with no usable error number. The
407/// one known cause is a process with no descriptor free, so a descriptor is
408/// opened and closed and its `EMFILE` is the error given. Only a table empty with
409/// a descriptor to spare is reported as merely empty.
410pub(crate) fn host_table() -> io::Result<Vec<netdev::Interface>> {
411    let mut table = asked_safely(netdev::get_interfaces)?;
412    if table.is_empty() {
413        descriptor_free()?;
414        return Err(io::Error::other(
415            "the interface table came back empty, which no host's is",
416        ));
417    }
418    let peers = point_to_point_peers();
419    if !peers.is_empty() {
420        for interface in &mut table {
421            own_addresses_for_peers(interface, &peers);
422        }
423    }
424    Ok(table)
425}
426
427/// Runs `read` where it cannot end the process, or refuses it.
428///
429/// On macOS `netdev` reads each interface's kind and display name from
430/// SystemConfiguration, which opens a descriptor the first time a process asks.
431/// With none free, the framework dereferences what it failed to open and the
432/// process segfaults. Once loaded, it needs no descriptor again.
433///
434/// So until one read has succeeded, a read is let through only after a
435/// descriptor has been opened and closed, and is refused with the system's error
436/// otherwise. Reads are serialised while this holds, so two cannot count on the
437/// same free descriptor. Another thread can still take it between the check and
438/// the read; the engine's own connections never take a table's last few (see
439/// [`OPENED_WHILE_RUNNING`](crate::system::descriptors::OPENED_WHILE_RUNNING)).
440#[cfg(target_os = "macos")]
441fn asked_safely<T>(read: impl FnOnce() -> T) -> io::Result<T> {
442    use std::sync::Mutex;
443    use std::sync::atomic::{AtomicBool, Ordering};
444
445    static LOADED: AtomicBool = AtomicBool::new(false);
446    static FIRST: Mutex<()> = Mutex::new(());
447
448    if LOADED.load(Ordering::Acquire) {
449        return Ok(read());
450    }
451    let _first = FIRST
452        .lock()
453        .unwrap_or_else(std::sync::PoisonError::into_inner);
454    if !LOADED.load(Ordering::Acquire) {
455        descriptor_free()?;
456    }
457    let answer = read();
458    LOADED.store(true, Ordering::Release);
459    Ok(answer)
460}
461
462/// Opens a descriptor and closes it again, or gives the system's reason it
463/// could not: `EMFILE` in a process with none free.
464fn descriptor_free() -> io::Result<()> {
465    #[cfg(unix)]
466    drop(std::fs::File::open("/dev/null")?);
467    #[cfg(windows)]
468    drop(std::fs::File::open("NUL")?);
469    Ok(())
470}
471
472/// Elsewhere the read fails without harm where it has no descriptor, and the
473/// empty table it returns is refused by [`host_table`].
474#[cfg(not(target_os = "macos"))]
475fn asked_safely<T>(read: impl FnOnce() -> T) -> io::Result<T> {
476    Ok(read())
477}
478
479/// A point-to-point link's peer, paired with the address this host holds on
480/// that link.
481#[derive(Debug, Clone, PartialEq, Eq)]
482struct PeerAddress {
483    /// The link's name, which is what `netdev` and the C library both key it by.
484    link: String,
485    /// The far end, as `IFA_ADDRESS` names it.
486    peer: IpAddr,
487    /// This host's own address on the link, `IFA_LOCAL`.
488    local: IpAddr,
489}
490
491/// Puts this host's own address wherever `interface` lists a peer in its place.
492///
493/// Each prefix is kept: the kernel reports one prefix for the pair.
494fn own_addresses_for_peers(interface: &mut netdev::Interface, peers: &[PeerAddress]) {
495    let local_for = |peer: IpAddr| {
496        peers
497            .iter()
498            .find(|pair| pair.link == interface.name && pair.peer == peer)
499            .map(|pair| pair.local)
500    };
501
502    let replaced_v4: Vec<_> = interface
503        .ipv4
504        .iter()
505        .map(|net| match local_for(IpAddr::V4(net.addr())) {
506            Some(IpAddr::V4(local)) => {
507                netdev::ipnet::Ipv4Net::new(local, net.prefix_len()).unwrap_or(*net)
508            }
509            _ => *net,
510        })
511        .collect();
512    let replaced_v6: Vec<_> = interface
513        .ipv6
514        .iter()
515        .map(|net| match local_for(IpAddr::V6(net.addr())) {
516            Some(IpAddr::V6(local)) => {
517                netdev::ipnet::Ipv6Net::new(local, net.prefix_len()).unwrap_or(*net)
518            }
519            _ => *net,
520        })
521        .collect();
522    interface.ipv4 = replaced_v4;
523    interface.ipv6 = replaced_v6;
524}
525
526/// Every point-to-point link's peer and the address this host holds opposite
527/// it, from the C library's `getifaddrs`.
528///
529/// On Linux glibc and musl both fill `getifaddrs` the right way round:
530/// `IFA_LOCAL` as the interface's address and `IFA_ADDRESS` as its destination.
531/// Only pairs where the two differ are returned, which is the set `netdev` reads
532/// wrong.
533#[cfg(target_os = "linux")]
534fn point_to_point_peers() -> Vec<PeerAddress> {
535    let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
536    // SAFETY: `getifaddrs` writes a list head into the pointer it is handed
537    // and returns non-zero without touching it on failure.
538    if unsafe { libc::getifaddrs(&mut head) } != 0 {
539        return Vec::new();
540    }
541
542    let mut pairs = Vec::new();
543    let mut entry = head;
544    while !entry.is_null() {
545        // SAFETY: `entry` is a node of the list `getifaddrs` returned, which
546        // stays valid until `freeifaddrs` below.
547        let node = unsafe { &*entry };
548        entry = node.ifa_next;
549
550        if node.ifa_flags & libc::IFF_POINTOPOINT as u32 == 0 {
551            continue;
552        }
553        // SAFETY: both are null or point at a socket address whose family says
554        // how much of it may be read; `ip_of` reads no further than that.
555        let (Some(local), Some(peer)) = (unsafe { ip_of(node.ifa_addr) }, unsafe {
556            ip_of(node.ifa_ifu)
557        }) else {
558            continue;
559        };
560        if local == peer {
561            continue;
562        }
563        // SAFETY: `ifa_name` is a NUL-terminated string owned by the list.
564        let link = unsafe { std::ffi::CStr::from_ptr(node.ifa_name) }
565            .to_string_lossy()
566            .into_owned();
567        pairs.push(PeerAddress { link, peer, local });
568    }
569
570    // SAFETY: `head` came from `getifaddrs` and is freed exactly once, after
571    // the last read of any node.
572    unsafe { libc::freeifaddrs(head) };
573    pairs
574}
575
576/// Elsewhere `netdev` reads `getifaddrs` itself, and there is nothing to put
577/// right.
578#[cfg(not(target_os = "linux"))]
579fn point_to_point_peers() -> Vec<PeerAddress> {
580    Vec::new()
581}
582
583/// The address in a socket address of either IP family.
584///
585/// # Safety
586///
587/// `address` must be null or point at a socket address at least as large as
588/// its family's structure.
589#[cfg(target_os = "linux")]
590unsafe fn ip_of(address: *const libc::sockaddr) -> Option<IpAddr> {
591    if address.is_null() {
592        return None;
593    }
594    // SAFETY: non-null, and every socket address starts with its family.
595    match i32::from(unsafe { (*address).sa_family }) {
596        libc::AF_INET => {
597            // SAFETY: the family says this is a `sockaddr_in`.
598            let v4 = unsafe { &*address.cast::<libc::sockaddr_in>() };
599            Some(IpAddr::V4(Ipv4Addr::from(u32::from_be(v4.sin_addr.s_addr))))
600        }
601        libc::AF_INET6 => {
602            // SAFETY: the family says this is a `sockaddr_in6`.
603            let v6 = unsafe { &*address.cast::<libc::sockaddr_in6>() };
604            Some(IpAddr::V6(Ipv6Addr::from(v6.sin6_addr.s6_addr)))
605        }
606        _ => None,
607    }
608}
609
610impl Link {
611    /// Reads one interface out of the host's table.
612    ///
613    /// The crate's whole dependency on how that table is read; every fact is
614    /// copied out.
615    ///
616    /// Reads `oper_state` because Windows publishes an operational state
617    /// (through `GetAdaptersAddresses`) and no flags word.
618    pub(crate) fn from_netdev(interface: netdev::Interface) -> Self {
619        use netdev::interface::types::InterfaceType;
620
621        let kind = if interface.is_loopback() {
622            LinkKind::Loopback
623        } else if interface.if_type == InterfaceType::Wireless80211 {
624            LinkKind::Wireless
625        } else if interface.is_physical() {
626            LinkKind::Wired
627        } else {
628            LinkKind::Virtual
629        };
630
631        let addresses = interface
632            .ipv4
633            .iter()
634            .map(|net| LinkAddress::new(IpAddr::V4(net.addr()), net.prefix_len()))
635            .chain(
636                interface
637                    .ipv6
638                    .iter()
639                    .map(|net| LinkAddress::new(IpAddr::V6(net.addr()), net.prefix_len())),
640            )
641            .collect();
642
643        Self {
644            mac: interface.mac_addr.map(|mac| MacAddr::from(mac.octets())),
645            addresses,
646            kind,
647            up: carries_traffic(
648                interface.is_up(),
649                interface.oper_state(),
650                interface.is_running(),
651            ),
652            addressing: Addressing::of(interface.is_broadcast(), interface.is_point_to_point()),
653            physical: interface.is_physical(),
654            default_route: interface.default,
655            gateway: interface
656                .gateway
657                .as_ref()
658                .is_some_and(|g| !g.ipv4.is_empty() || !g.ipv6.is_empty()),
659            // Kept only where it says something the name does not.
660            friendly_name: interface
661                .friendly_name
662                .filter(|friendly| !friendly.is_empty() && *friendly != interface.name),
663            name: interface.name,
664            index: interface.index,
665        }
666    }
667}
668
669/// Whether a link-layer probe can be put on this link.
670///
671/// The free-function form of [`Link::carries_frames`].
672pub fn is_layer_2_capable(link: &Link) -> bool {
673    link.carries_frames()
674}
675
676/// Whether every target in `ips` is on the same segment as `link`.
677///
678/// Every range, wholly, in both families. A range straddling the edge of the
679/// link's network is not on-link, since a sweep would wait out a timeout for
680/// every address past the boundary.
681///
682/// An empty set is on-link.
683pub fn is_on_link(link: &Link, ips: &IpSet) -> bool {
684    let within = |start: IpAddr, end: IpAddr| {
685        link.addresses()
686            .iter()
687            .any(|held| held.contains(&start) && held.contains(&end))
688    };
689
690    ips.v4()
691        .iter()
692        .all(|range| within(range.start_addr().into(), range.end_addr().into()))
693        && ips
694            .v6()
695            .iter()
696            .all(|range| within(range.start_addr().into(), range.end_addr().into()))
697}
698
699/// Whether an interface with this administrative state, operational state and
700/// running flag can carry a probe or a reply.
701///
702/// Both states must be up: a cable can be plugged into an interface nobody has
703/// brought up, and an interface can be administratively up with nothing on the
704/// other end.
705///
706/// **An operational state of `unknown` is read from the running flag.** Drivers
707/// that keep no operational state report `unknown`, and the kernel documentation
708/// says to treat such an interface as usable. Linux reports it for every tun,
709/// WireGuard and ppp device, so read as down, a VPN tunnel would be left out of
710/// source selection and capture. Such a driver sets the running flag once
711/// something is attached, so a tunnel nobody has opened stays out.
712fn carries_traffic(
713    admin_up: bool,
714    oper: netdev::interface::state::OperState,
715    running: bool,
716) -> bool {
717    use netdev::interface::state::OperState;
718
719    admin_up
720        && match oper {
721            OperState::Up => true,
722            OperState::Unknown => running,
723            OperState::NotPresent
724            | OperState::Down
725            | OperState::LowerLayerDown
726            | OperState::Testing
727            | OperState::Dormant => false,
728        }
729}
730
731// ╔════════════════════════════════════════════╗
732// ║ ████████╗███████╗███████╗████████╗███████╗ ║
733// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
734// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
735// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
736// ║    ██║   ███████╗███████║   ██║   ███████║ ║
737// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
738// ╚════════════════════════════════════════════╝
739
740#[cfg(test)]
741mod tests {
742    use crate::model::ip::range::IpRange;
743
744    /// A point-to-point link as Linux reports it through `netdev`: the peer
745    /// where this host's own address belongs, in both families, beside an
746    /// address that is this host's own and must be left alone.
747    fn misread_ppp() -> netdev::Interface {
748        let mut interface = netdev::Interface::dummy();
749        interface.name = "ppp0".to_string();
750        interface.ipv4 = vec![
751            "203.0.113.2/32".parse().expect("a network"),
752            "198.51.100.9/24".parse().expect("a network"),
753        ];
754        interface.ipv6 = vec!["2001:db8::2/128".parse().expect("a network")];
755        interface
756    }
757
758    fn peer(link: &str, peer: &str, local: &str) -> PeerAddress {
759        PeerAddress {
760            link: link.to_string(),
761            peer: peer.parse().expect("an address"),
762            local: local.parse().expect("an address"),
763        }
764    }
765
766    /// The link holds this host's address, at the prefix the pair was given,
767    /// and the peer is no longer claimed as this host's own.
768    #[test]
769    fn a_point_to_point_link_holds_its_own_address_and_not_its_peers() {
770        let mut interface = misread_ppp();
771        own_addresses_for_peers(
772            &mut interface,
773            &[
774                peer("ppp0", "203.0.113.2", "203.0.113.1"),
775                peer("ppp0", "2001:db8::2", "2001:db8::1"),
776            ],
777        );
778
779        let held: Vec<String> = Link::from_netdev(interface)
780            .addresses()
781            .iter()
782            .map(|held| format!("{}/{}", held.address(), held.prefix()))
783            .collect();
784        assert_eq!(
785            held,
786            ["203.0.113.1/32", "198.51.100.9/24", "2001:db8::1/128"]
787        );
788    }
789
790    /// A pair belongs to its own link. Another link that happens to list the
791    /// same address is not rewritten by it.
792    #[test]
793    fn a_peer_is_corrected_on_its_own_link_only() {
794        let mut interface = misread_ppp();
795        interface.name = "eth0".to_string();
796        own_addresses_for_peers(
797            &mut interface,
798            &[peer("ppp0", "203.0.113.2", "203.0.113.1")],
799        );
800
801        assert_eq!(
802            interface.ipv4[0],
803            "203.0.113.2/32".parse::<netdev::ipnet::Ipv4Net>().unwrap()
804        );
805    }
806
807    fn link(name: &str, kind: LinkKind) -> Link {
808        Link::new(name, 1)
809            .with_kind(kind)
810            .with_mac(MacAddr::new(1, 2, 3, 4, 5, 6))
811    }
812    fn holding(name: &str, address: &str, prefix: u8) -> Link {
813        link(name, LinkKind::Wired).with_addresses(vec![LinkAddress::new(
814            address.parse::<IpAddr>().expect("an address"),
815            prefix,
816        )])
817    }
818    fn targets(written: &str) -> IpSet {
819        let mut set = IpSet::new();
820        set.insert_range(written.parse::<IpRange>().expect("a range"));
821        set
822    }
823    /// A range wholly inside the link's network is on it; one that leaves it,
824    /// even halfway, is not.
825    #[test]
826    fn a_range_is_on_link_only_if_all_of_it_is() {
827        let link = holding("en0", "198.51.100.7", 25);
828
829        assert!(is_on_link(&link, &targets("198.51.100.1-198.51.100.50")));
830        assert!(is_on_link(&link, &targets("198.51.100.0/25")), "the whole");
831        assert!(
832            !is_on_link(&link, &targets("198.51.100.130-198.51.100.135")),
833            "past"
834        );
835        assert!(
836            !is_on_link(&link, &targets("198.51.100.100-198.51.100.140")),
837            "a range that starts on the link and leaves it is not on the link"
838        );
839    }
840    /// A link with no address of its own puts nothing on it.
841    #[test]
842    fn a_link_with_no_addressing_has_nothing_on_it() {
843        let bare = link("en0", LinkKind::Wired);
844
845        assert!(!is_on_link(&bare, &targets("198.51.100.1-198.51.100.50")));
846    }
847    /// An IPv6 address on the link does not make an IPv4 range local.
848    ///
849    /// A v6 prefix that happens to contain the same bits must not be read as
850    /// covering a v4 range.
851    #[test]
852    fn an_ipv6_prefix_does_not_answer_for_an_ipv4_range() {
853        let v6_only = link("en0", LinkKind::Wired).with_addresses(vec![LinkAddress::new(
854            "fe80::1".parse::<IpAddr>().expect("an address"),
855            64,
856        )]);
857
858        assert!(!is_on_link(
859            &v6_only,
860            &targets("198.51.100.1-198.51.100.50")
861        ));
862    }
863    use super::*;
864
865    /// A tunnel is a link: Linux reports `unknown` for tun and WireGuard
866    /// devices, and one with something attached to it carries traffic.
867    #[test]
868    fn an_interface_of_unknown_state_carries_traffic_while_it_runs() {
869        use netdev::interface::state::OperState;
870
871        assert!(carries_traffic(true, OperState::Up, true));
872        assert!(
873            carries_traffic(true, OperState::Unknown, true),
874            "a tunnel in use"
875        );
876        assert!(
877            !carries_traffic(true, OperState::Unknown, false),
878            "a tunnel nothing is attached to"
879        );
880        assert!(
881            !carries_traffic(false, OperState::Unknown, true),
882            "brought down"
883        );
884        for down in [
885            OperState::Down,
886            OperState::LowerLayerDown,
887            OperState::Dormant,
888            OperState::Testing,
889            OperState::NotPresent,
890        ] {
891            assert!(!carries_traffic(true, down, true), "{down:?}");
892        }
893    }
894
895    fn v4(address: &str, prefix: u8) -> LinkAddress {
896        LinkAddress::new(IpAddr::V4(address.parse().expect("an address")), prefix)
897    }
898
899    /// The network is derived from the prefix, and covers both ends.
900    ///
901    /// Both ends, because this is what the *link* carries; an on-link test
902    /// that excluded them would place a host at `198.51.100.127` elsewhere.
903    #[test]
904    fn a_network_covers_every_address_its_prefix_names() {
905        let held = v4("198.51.100.7", 25);
906        let network = held.network();
907
908        assert_eq!(
909            network.start_addr(),
910            "198.51.100.0".parse::<IpAddr>().unwrap()
911        );
912        assert_eq!(
913            network.end_addr(),
914            "198.51.100.127".parse::<IpAddr>().unwrap()
915        );
916        assert!(
917            held.contains(&"198.51.100.0".parse().unwrap()),
918            "the network"
919        );
920        assert!(
921            held.contains(&"198.51.100.127".parse().unwrap()),
922            "the broadcast"
923        );
924        assert!(
925            !held.contains(&"198.51.100.128".parse().unwrap()),
926            "the next one"
927        );
928    }
929
930    /// A `/32` is one address, and a `/0` is all of them. Both are real: a
931    /// point-to-point link routinely holds the first.
932    #[test]
933    fn the_ends_of_the_prefix_range_are_both_networks() {
934        let single = v4("192.0.2.1", 32);
935        assert_eq!(single.network().len(), 1);
936        assert!(single.contains(&"192.0.2.1".parse().unwrap()));
937
938        let everything = v4("192.0.2.1", 0);
939        assert!(everything.contains(&"8.8.8.8".parse().unwrap()));
940    }
941
942    /// A prefix past the end of its family is clamped, which keeps the address
943    /// and makes `network` total.
944    #[test]
945    fn a_prefix_past_its_family_is_clamped_and_the_address_survives() {
946        let absurd = v4("198.51.100.7", 200);
947
948        assert_eq!(absurd.prefix(), 32, "clamped to what IPv4 has");
949        assert_eq!(absurd.address(), "198.51.100.7".parse::<IpAddr>().unwrap());
950        assert_eq!(absurd.network().len(), 1);
951
952        let v6 = LinkAddress::new(IpAddr::V6("fe80::1".parse().unwrap()), 255);
953        assert_eq!(v6.prefix(), 128, "and to what IPv6 has");
954    }
955
956    /// The three things a link-layer probe needs, and each one's absence.
957    #[test]
958    fn a_link_carries_frames_only_with_a_segment_and_an_address_to_send_from() {
959        let mac = MacAddr::new(2, 0, 0, 0, 0, 1);
960        let wired = Link::new("en0", 1).with_kind(LinkKind::Wired).with_mac(mac);
961        assert!(wired.carries_frames());
962
963        assert!(
964            !Link::new("en0", 1)
965                .with_kind(LinkKind::Wired)
966                .carries_frames(),
967            "no hardware address to send from"
968        );
969        assert!(
970            !Link::new("lo0", 1)
971                .with_kind(LinkKind::Loopback)
972                .with_mac(mac)
973                .carries_frames(),
974            "nobody else on it"
975        );
976        assert!(
977            !Link::new("utun0", 1)
978                .with_kind(LinkKind::Wired)
979                .with_mac(mac)
980                .with_addressing(Addressing::PointToPoint)
981                .carries_frames(),
982            "a peer rather than a segment"
983        );
984    }
985
986    /// The families are kept apart.
987    #[test]
988    fn a_links_addresses_are_readable_by_family() {
989        let link = Link::new("en0", 1).with_addresses(vec![
990            v4("198.51.100.7", 24),
991            LinkAddress::new(IpAddr::V6("fe80::1".parse().unwrap()), 64),
992            v4("192.0.2.5", 25),
993        ]);
994
995        let v4s: Vec<_> = link.ipv4().collect();
996        assert_eq!(v4s.len(), 2);
997        assert_eq!(v4s[0], ("198.51.100.7".parse().unwrap(), 24));
998        assert_eq!(v4s[1], ("192.0.2.5".parse().unwrap(), 25));
999
1000        let v6s: Vec<_> = link.ipv6().collect();
1001        assert_eq!(v6s.len(), 1);
1002        assert_eq!(v6s[0], ("fe80::1".parse().unwrap(), 64));
1003    }
1004
1005    /// A link names its own zone.
1006    #[test]
1007    fn a_link_is_its_own_zone() {
1008        let zone = Link::new("en0", 7).zone();
1009
1010        assert_eq!(zone.name(), "en0");
1011        assert_eq!(zone.index(), Some(7));
1012    }
1013
1014    /// A message about an interface names it the way the system settings do,
1015    /// falling back to the system name when the friendly name is empty or
1016    /// repeated.
1017    #[test]
1018    fn an_interface_is_called_what_a_person_calls_it() {
1019        let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
1020        let read = |friendly: Option<&str>| {
1021            let mut interface = netdev::Interface::dummy();
1022            interface.name = guid.to_owned();
1023            interface.friendly_name = friendly.map(str::to_owned);
1024            Link::from_netdev(interface)
1025        };
1026
1027        assert_eq!(
1028            read(Some("vEthernet (WSL)")).display_name(),
1029            "vEthernet (WSL)"
1030        );
1031        assert_eq!(read(None).display_name(), guid);
1032        assert_eq!(read(Some("")).display_name(), guid);
1033    }
1034
1035    /// A process with no descriptor free is told the interface table cannot
1036    /// be read, with the system's `EMFILE`: no segfault on macOS, no empty
1037    /// table elsewhere.
1038    #[cfg(unix)]
1039    #[test]
1040    fn a_first_read_in_a_full_table_is_refused_rather_than_ending_the_process() {
1041        use crate::system::descriptors::testing::{exhaust, in_a_process_of_its_own};
1042
1043        if !in_a_process_of_its_own(
1044            module_path!(),
1045            "a_first_read_in_a_full_table_is_refused_rather_than_ending_the_process",
1046        ) {
1047            return;
1048        }
1049        let held = exhaust(64);
1050        let read = interfaces();
1051        drop(held);
1052
1053        let refused = read.expect_err("a table read with no descriptor free");
1054        assert_eq!(refused.raw_os_error(), Some(libc::EMFILE), "{refused}");
1055        assert!(
1056            !interfaces()
1057                .expect("the table, once there is room")
1058                .is_empty(),
1059            "every host has a loopback interface"
1060        );
1061    }
1062
1063    /// Once a process has read its interface table, it reads it whole again
1064    /// with no descriptor free, so a scan whose connections fill the table
1065    /// still knows which addresses are on its own segments.
1066    #[cfg(target_os = "macos")]
1067    #[test]
1068    fn a_table_read_once_is_read_again_with_no_descriptor_free() {
1069        use crate::system::descriptors::testing::{exhaust, in_a_process_of_its_own};
1070
1071        if !in_a_process_of_its_own(
1072            module_path!(),
1073            "a_table_read_once_is_read_again_with_no_descriptor_free",
1074        ) {
1075            return;
1076        }
1077        let names = |links: Vec<Link>| {
1078            let mut names: Vec<String> = links.iter().map(|l| l.name().to_owned()).collect();
1079            names.sort();
1080            names
1081        };
1082        let before = names(interfaces().expect("the table, with room to read it"));
1083        let held = exhaust(64);
1084        let again = interfaces();
1085        drop(held);
1086
1087        assert_eq!(names(again.expect("a second read in a full table")), before);
1088    }
1089
1090    /// Whatever the host says, read through the one function that reads it.
1091    ///
1092    /// Asserts properties of `from_netdev` for every interface present: a
1093    /// `Loopback` link does not claim to carry frames, and no address keeps a
1094    /// prefix its family cannot hold.
1095    #[test]
1096    fn every_interface_this_machine_has_reads_back_consistently() {
1097        for link in interfaces().expect("this machine's interfaces") {
1098            assert!(!link.name().is_empty(), "an interface with no name");
1099
1100            if link.is_loopback() {
1101                assert!(
1102                    !link.carries_frames(),
1103                    "{} is loopback and claims a segment",
1104                    link.name()
1105                );
1106            }
1107
1108            for held in link.addresses() {
1109                let ceiling = if held.address().is_ipv4() { 32 } else { 128 };
1110                assert!(
1111                    held.prefix() <= ceiling,
1112                    "{} holds {} with a /{} its family cannot express",
1113                    link.name(),
1114                    held.address(),
1115                    held.prefix()
1116                );
1117                assert!(
1118                    held.contains(&held.address()),
1119                    "{} holds {} on a network that excludes it",
1120                    link.name(),
1121                    held.address()
1122                );
1123            }
1124        }
1125    }
1126}