Skip to main content

veilid_tools/network_interfaces/
mod.rs

1mod tools;
2
3use crate::*;
4use serde::*;
5
6cfg_if::cfg_if! {
7    if #[cfg(any(target_os = "linux", target_os = "android"))] {
8        mod netlink;
9        use self::netlink::PlatformSupportNetlink as PlatformSupport;
10    } else if #[cfg(target_os = "windows")] {
11        mod windows;
12        mod sockaddr_tools;
13        use self::windows::PlatformSupportWindows as PlatformSupport;
14    } else if #[cfg(any(target_os = "macos", target_os = "ios"))] {
15        mod apple;
16        mod sockaddr_tools;
17        use self::apple::PlatformSupportApple as PlatformSupport;
18    } else if #[cfg(target_os = "openbsd")] {
19        mod openbsd;
20        mod sockaddr_tools;
21        use self::openbsd::PlatformSupportOpenBSD as PlatformSupport;
22    } else if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] {
23        mod wasm;
24        use self::wasm::PlatformSupportWasm as PlatformSupport;
25    } else {
26        compile_error!("No network interfaces support for this platform!");
27    }
28}
29
30/// An interface address that is either IPv4 or IPv6, with its netmask and broadcast address.
31#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
32pub enum IfAddr {
33    /// An IPv4 interface address.
34    V4(Ifv4Addr),
35    /// An IPv6 interface address.
36    V6(Ifv6Addr),
37}
38
39impl IfAddr {
40    /// The IP address.
41    #[must_use]
42    pub fn ip(&self) -> IpAddr {
43        match *self {
44            IfAddr::V4(ref ifv4_addr) => IpAddr::V4(ifv4_addr.ip),
45            IfAddr::V6(ref ifv6_addr) => IpAddr::V6(ifv6_addr.ip),
46        }
47    }
48    /// The netmask.
49    #[must_use]
50    pub fn netmask(&self) -> IpAddr {
51        match *self {
52            IfAddr::V4(ref ifv4_addr) => IpAddr::V4(ifv4_addr.netmask),
53            IfAddr::V6(ref ifv6_addr) => IpAddr::V6(ifv6_addr.netmask),
54        }
55    }
56    /// The broadcast address, if one is set.
57    pub fn broadcast(&self) -> Option<IpAddr> {
58        match *self {
59            IfAddr::V4(ref ifv4_addr) => ifv4_addr.broadcast.map(IpAddr::V4),
60            IfAddr::V6(ref ifv6_addr) => ifv6_addr.broadcast.map(IpAddr::V6),
61        }
62    }
63
64    /// The network address, with the host bits masked off by the netmask.
65    #[must_use]
66    pub fn network(&self) -> IfAddr {
67        match *self {
68            IfAddr::V4(ref ifv4_addr) => IfAddr::V4(ifv4_addr.network()),
69            IfAddr::V6(ref ifv6_addr) => IfAddr::V6(ifv6_addr.network()),
70        }
71    }
72
73    /// Whether `addr` is in the same subnet as this address. False across address families.
74    #[must_use]
75    pub fn contains_address(&self, addr: IpAddr) -> bool {
76        match *self {
77            IfAddr::V4(ref ifv4_addr) => match addr {
78                IpAddr::V4(ipv4_addr) => ifv4_addr.contains_address(ipv4_addr),
79                IpAddr::V6(_consensus_count) => false,
80            },
81            IfAddr::V6(ref ifv6_addr) => match addr {
82                IpAddr::V4(_) => false,
83                IpAddr::V6(ipv6_addr) => ifv6_addr.contains_address(ipv6_addr),
84            },
85        }
86    }
87}
88
89impl fmt::Display for IfAddr {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        match *self {
92            IfAddr::V4(ref ifv4_addr) => write!(f, "{}", f.to_string(ifv4_addr)),
93            IfAddr::V6(ref ifv6_addr) => write!(f, "{}", f.to_string(ifv6_addr)),
94        }
95    }
96}
97
98/// Details about the ipv4 address of an interface on this host.
99#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
100pub struct Ifv4Addr {
101    /// The IP address of the interface.
102    pub ip: Ipv4Addr,
103    /// The netmask of the interface.
104    pub netmask: Ipv4Addr,
105    /// The broadcast address of the interface.
106    pub broadcast: Option<Ipv4Addr>,
107}
108
109impl fmt::Display for Ifv4Addr {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        write!(
112            f,
113            "{}/{}",
114            self.ip,
115            if let Some(prefix_len) = self.prefix_len() {
116                format!("{}", prefix_len)
117            } else {
118                format!("(invalid netmask={})", self.netmask)
119            },
120        )
121    }
122}
123
124fn ipv4_netmask_to_prefix_len(netmask: Ipv4Addr) -> Option<u8> {
125    let netmask_u32 = netmask.to_bits();
126    let prefix_len = netmask_u32.leading_ones() as u8;
127    let suffix_len = netmask_u32.trailing_zeros() as u8;
128
129    if suffix_len != 32 - prefix_len {
130        None
131    } else {
132        Some(prefix_len)
133    }
134}
135
136impl Ifv4Addr {
137    /// Convert ip address to the address of the network itself by applying the netmask
138    #[must_use]
139    pub fn network(&self) -> Ifv4Addr {
140        let v4 = self.ip.octets();
141        let v4mask = self.netmask.octets();
142        let ip = Ipv4Addr::new(
143            v4[0] & v4mask[0],
144            v4[1] & v4mask[1],
145            v4[2] & v4mask[2],
146            v4[3] & v4mask[3],
147        );
148        Ifv4Addr {
149            ip,
150            netmask: self.netmask,
151            broadcast: self.broadcast,
152        }
153    }
154
155    /// Whether `addr` is in this address's subnet.
156    #[must_use]
157    pub fn contains_address(&self, addr: Ipv4Addr) -> bool {
158        let v4mask = self.netmask.octets();
159
160        let self_v4 = self.ip.octets();
161        let self_ip = Ipv4Addr::new(
162            self_v4[0] & v4mask[0],
163            self_v4[1] & v4mask[1],
164            self_v4[2] & v4mask[2],
165            self_v4[3] & v4mask[3],
166        );
167
168        let addr_v4 = addr.octets();
169        let addr_ip = Ipv4Addr::new(
170            addr_v4[0] & v4mask[0],
171            addr_v4[1] & v4mask[1],
172            addr_v4[2] & v4mask[2],
173            addr_v4[3] & v4mask[3],
174        );
175
176        self_ip == addr_ip
177    }
178
179    /// CIDR prefix length of the netmask, or `None` if the netmask is not contiguous.
180    #[must_use]
181    pub fn prefix_len(&self) -> Option<u8> {
182        ipv4_netmask_to_prefix_len(self.netmask)
183    }
184}
185
186/// Details about the ipv6 address of an interface on this host.
187#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
188pub struct Ifv6Addr {
189    /// The IP address of the interface.
190    pub ip: Ipv6Addr,
191    /// The netmask of the interface.
192    pub netmask: Ipv6Addr,
193    /// The broadcast address of the interface.
194    pub broadcast: Option<Ipv6Addr>,
195}
196
197impl fmt::Display for Ifv6Addr {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        write!(
200            f,
201            "{}/{}",
202            self.ip,
203            if let Some(prefix_len) = self.prefix_len() {
204                format!("{}", prefix_len)
205            } else {
206                format!("(invalid netmask={})", self.netmask)
207            },
208        )
209    }
210}
211
212impl Ifv6Addr {
213    /// Convert ip address to the address of the network itself by applying the netmask
214    #[must_use]
215    pub fn network(&self) -> Ifv6Addr {
216        let v6 = self.ip.segments();
217        let v6mask = self.netmask.segments();
218        let ip = Ipv6Addr::new(
219            v6[0] & v6mask[0],
220            v6[1] & v6mask[1],
221            v6[2] & v6mask[2],
222            v6[3] & v6mask[3],
223            v6[4] & v6mask[4],
224            v6[5] & v6mask[5],
225            v6[6] & v6mask[6],
226            v6[7] & v6mask[7],
227        );
228        Ifv6Addr {
229            ip,
230            netmask: self.netmask,
231            broadcast: self.broadcast,
232        }
233    }
234
235    /// Whether `addr` is in this address's subnet.
236    #[must_use]
237    pub fn contains_address(&self, addr: Ipv6Addr) -> bool {
238        let v6mask = self.netmask.segments();
239
240        let self_v6 = self.ip.segments();
241        let self_ip = Ipv6Addr::new(
242            self_v6[0] & v6mask[0],
243            self_v6[1] & v6mask[1],
244            self_v6[2] & v6mask[2],
245            self_v6[3] & v6mask[3],
246            self_v6[4] & v6mask[4],
247            self_v6[5] & v6mask[5],
248            self_v6[6] & v6mask[6],
249            self_v6[7] & v6mask[7],
250        );
251
252        let addr_v6 = addr.segments();
253        let addr_ip = Ipv6Addr::new(
254            addr_v6[0] & v6mask[0],
255            addr_v6[1] & v6mask[1],
256            addr_v6[2] & v6mask[2],
257            addr_v6[3] & v6mask[3],
258            addr_v6[4] & v6mask[4],
259            addr_v6[5] & v6mask[5],
260            addr_v6[6] & v6mask[6],
261            addr_v6[7] & v6mask[7],
262        );
263
264        self_ip == addr_ip
265    }
266
267    /// CIDR prefix length of the netmask, or `None` if the netmask is not contiguous.
268    #[must_use]
269    pub fn prefix_len(&self) -> Option<u8> {
270        ipv6_netmask_to_prefix_len(self.netmask)
271    }
272}
273
274fn ipv6_netmask_to_prefix_len(netmask: Ipv6Addr) -> Option<u8> {
275    let netmask_u128 = netmask.to_bits();
276    let prefix_len = netmask_u128.leading_ones() as u8;
277    let suffix_len = netmask_u128.trailing_zeros() as u8;
278
279    if suffix_len != 128 - prefix_len {
280        None
281    } else {
282        Some(prefix_len)
283    }
284}
285
286/// Some of the flags associated with an interface
287#[derive(
288    Debug, Default, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Copy, Serialize, Deserialize,
289)]
290pub struct InterfaceFlags {
291    /// Loopback interface (lo/lo0)
292    pub is_loopback: bool,
293    /// Interface is up and operational
294    pub is_running: bool,
295    /// Point-to-point link (PPP, tun, etc.)
296    pub is_point_to_point: bool,
297    /// CLAT (RFC 6877) virtual interface (e.g. Android `clat4*` / `v4-*`); local-only
298    pub is_clat: bool,
299}
300
301/// Some of the flags associated with an address
302#[derive(
303    Debug, Default, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Copy, Serialize, Deserialize,
304)]
305pub struct AddressFlags {
306    /// Auto-configured (DHCP/SLAAC) rather than statically configured
307    pub is_dynamic: bool,
308    /// RFC 4941 privacy/temporary IPv6 address (rotates periodically)
309    pub is_temporary: bool,
310    /// Address has finished DAD and is not deprecated/tentative/duplicated
311    pub is_preferred: bool,
312    /// CLAT46 synthesized IPv6 (RFC 6877); local-only on macOS/iOS
313    pub is_clat: bool,
314    /// Absolute expiration in seconds since UNIX epoch; `None` if non-expiring (static)
315    pub expiration_secs: Option<u64>,
316}
317
318/// An address bound to an interface, with its flags. Ordered by reachability preference.
319#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
320pub struct InterfaceAddress {
321    /// The IPv4 or IPv6 address with its netmask and broadcast.
322    pub if_addr: IfAddr,
323    /// Scope and lifetime flags for the address.
324    pub flags: AddressFlags,
325}
326
327use core::cmp::Ordering;
328
329// less is less preferable, greater is more preferable
330impl Ord for InterfaceAddress {
331    fn cmp(&self, other: &Self) -> Ordering {
332        match (&self.if_addr, &other.if_addr) {
333            (IfAddr::V4(a), IfAddr::V4(b)) => {
334                // global scope addresses are better
335                let ret = ipv4addr_is_global(&a.ip).cmp(&ipv4addr_is_global(&b.ip));
336                if ret != Ordering::Equal {
337                    return ret;
338                }
339                // local scope addresses are better
340                let ret = ipv4addr_is_private(&a.ip).cmp(&ipv4addr_is_private(&b.ip));
341                if ret != Ordering::Equal {
342                    return ret;
343                }
344                // non-dynamic addresses are better
345                let ret = (!self.flags.is_dynamic).cmp(&!other.flags.is_dynamic);
346                if ret != Ordering::Equal {
347                    return ret;
348                }
349            }
350            (IfAddr::V6(a), IfAddr::V6(b)) => {
351                // preferred addresses are better
352                let ret = self.flags.is_preferred.cmp(&other.flags.is_preferred);
353                if ret != Ordering::Equal {
354                    return ret;
355                }
356                // non-temporary address are better
357                let ret = (!self.flags.is_temporary).cmp(&!other.flags.is_temporary);
358                if ret != Ordering::Equal {
359                    return ret;
360                }
361                // global scope addresses are better
362                let ret = ipv6addr_is_global(&a.ip).cmp(&ipv6addr_is_global(&b.ip));
363                if ret != Ordering::Equal {
364                    return ret;
365                }
366                // unique local unicast addresses are better
367                let ret = ipv6addr_is_unique_local(&a.ip).cmp(&ipv6addr_is_unique_local(&b.ip));
368                if ret != Ordering::Equal {
369                    return ret;
370                }
371                // unicast site local addresses are better
372                let ret = ipv6addr_is_unicast_site_local(&a.ip)
373                    .cmp(&ipv6addr_is_unicast_site_local(&b.ip));
374                if ret != Ordering::Equal {
375                    return ret;
376                }
377                // unicast link local addresses are better
378                let ret = ipv6addr_is_unicast_link_local(&a.ip)
379                    .cmp(&ipv6addr_is_unicast_link_local(&b.ip));
380                if ret != Ordering::Equal {
381                    return ret;
382                }
383                // non-dynamic addresses are better
384                let ret = (!self.flags.is_dynamic).cmp(&!other.flags.is_dynamic);
385                if ret != Ordering::Equal {
386                    return ret;
387                }
388            }
389            (IfAddr::V4(a), IfAddr::V6(b)) => {
390                // If the IPv6 address is preferred and not temporary, compare if it is global scope
391                if other.flags.is_preferred && !other.flags.is_temporary {
392                    let ret = ipv4addr_is_global(&a.ip).cmp(&ipv6addr_is_global(&b.ip));
393                    if ret != Ordering::Equal {
394                        return ret;
395                    }
396                }
397
398                // Default, prefer IPv4 because many IPv6 addresses are not actually routed
399                return Ordering::Greater;
400            }
401            (IfAddr::V6(a), IfAddr::V4(b)) => {
402                // If the IPv6 address is preferred and not temporary, compare if it is global scope
403                if self.flags.is_preferred && !self.flags.is_temporary {
404                    let ret = ipv6addr_is_global(&a.ip).cmp(&ipv4addr_is_global(&b.ip));
405                    if ret != Ordering::Equal {
406                        return ret;
407                    }
408                }
409
410                // Default, prefer IPv4 because many IPv6 addresses are not actually routed
411                return Ordering::Less;
412            }
413        }
414        // stable sort
415        let ret = self.if_addr.cmp(&other.if_addr);
416        if ret != Ordering::Equal {
417            return ret;
418        }
419        self.flags.cmp(&other.flags)
420    }
421}
422impl PartialOrd for InterfaceAddress {
423    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
424        Some(self.cmp(other))
425    }
426}
427
428impl InterfaceAddress {
429    /// Make an `InterfaceAddress` from an address and its flags.
430    #[must_use]
431    pub fn new(if_addr: IfAddr, flags: AddressFlags) -> Self {
432        Self { if_addr, flags }
433    }
434
435    /// Underlying IPv4 or IPv6 address with netmask/broadcast.
436    #[must_use]
437    pub fn if_addr(&self) -> &IfAddr {
438        &self.if_addr
439    }
440
441    /// RFC 4941 privacy/temporary IPv6 (rotates)
442    #[must_use]
443    pub fn is_temporary(&self) -> bool {
444        self.flags.is_temporary
445    }
446
447    /// Auto-configured (DHCP/SLAAC) rather than statically configured
448    #[must_use]
449    pub fn is_dynamic(&self) -> bool {
450        self.flags.is_dynamic
451    }
452
453    /// Address has finished DAD and is not deprecated/tentative/duplicated
454    #[must_use]
455    pub fn is_preferred(&self) -> bool {
456        self.flags.is_preferred
457    }
458
459    /// CLAT46 synthesized IPv6 (RFC 6877), local-only on macOS/iOS
460    #[must_use]
461    pub fn is_clat(&self) -> bool {
462        self.flags.is_clat
463    }
464
465    /// IPv4 address in CGNAT (RFC 6598 100.64.0.0/10) or DS-Lite (RFC 6333 192.0.0.0/24);
466    /// always false for IPv6
467    #[must_use]
468    pub fn is_cgnat_or_ds_lite(&self) -> bool {
469        match &self.if_addr {
470            IfAddr::V4(v4) => {
471                ipv4addr_is_shared(&v4.ip) || ipv4addr_is_ietf_protocol_assignment(&v4.ip)
472            }
473            IfAddr::V6(_) => false,
474        }
475    }
476
477    /// IPv4 link-local / APIPA (169.254.0.0/16), DHCP-failed fallback, transient
478    /// and not reachable by peers; always false for IPv6 (link-local IPv6 is
479    /// handled by `ipv6addr_is_global`)
480    #[must_use]
481    pub fn is_ipv4_link_local(&self) -> bool {
482        match &self.if_addr {
483            IfAddr::V4(v4) => ipv4addr_is_link_local(&v4.ip),
484            IfAddr::V6(_) => false,
485        }
486    }
487
488    /// IPv6 link-local (RFC 4291 fe80::/10)
489    #[must_use]
490    pub fn is_ipv6_link_local(&self) -> bool {
491        match &self.if_addr {
492            IfAddr::V4(_) => false,
493            IfAddr::V6(v6) => ipv6addr_is_unicast_link_local(&v6.ip),
494        }
495    }
496}
497
498// #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
499// enum NetworkInterfaceType {
500//     Mobile,     // Least preferable, usually metered and slow
501//     Unknown,    // Everything else if we can't detect the type
502//     Wireless,   // Wifi is usually free or cheap and medium speed
503//     Wired,      // Wired is usually free or cheap and high speed
504// }
505
506/// A single network interface on this host, with its flags, gateways, and addresses.
507#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
508pub struct NetworkInterface {
509    /// OS interface name (e.g. `en0`, `eth0`).
510    pub name: String,
511    /// Interface-level flags.
512    pub flags: InterfaceFlags,
513    /// Default-route gateways reachable through this interface, sorted and deduplicated.
514    pub gateways: Vec<IpAddr>,
515    /// Addresses bound to this interface, sorted by preference and deduplicated.
516    pub addrs: Vec<InterfaceAddress>,
517    /// Largest IP packet the interface carries, when the OS reports it.
518    #[serde(default)]
519    pub mtu: Option<u32>,
520}
521
522impl fmt::Debug for NetworkInterface {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        let alt = f.alternate();
525        let mut ds = f.debug_struct("NetworkInterface");
526        ds.field("name", &self.name)
527            .field("flags", &self.flags)
528            .field("gateways", &self.gateways)
529            .field("addrs", &self.addrs)
530            .field("mtu", &self.mtu);
531        if alt {
532            ds.field("// primary_ipv4", &self.primary_ipv4());
533            ds.field("// primary_ipv6", &self.primary_ipv6());
534        }
535        ds.finish()
536    }
537}
538impl NetworkInterface {
539    /// Make an empty `NetworkInterface` with the given name and flags.
540    #[must_use]
541    pub fn new(name: String, flags: InterfaceFlags) -> Self {
542        Self {
543            name,
544            flags,
545            gateways: Vec::new(),
546            addrs: Vec::new(),
547            mtu: None,
548        }
549    }
550
551    /// OS interface name (e.g. `en0`, `eth0`, `clat4-rmnet_data0`)
552    #[must_use]
553    pub fn name(&self) -> String {
554        self.name.clone()
555    }
556
557    /// Loopback interface (lo/lo0)
558    #[must_use]
559    pub fn is_loopback(&self) -> bool {
560        self.flags.is_loopback
561    }
562
563    /// Point-to-point link (PPP, tun, etc.)
564    #[must_use]
565    pub fn is_point_to_point(&self) -> bool {
566        self.flags.is_point_to_point
567    }
568
569    /// Interface is up and operational
570    #[must_use]
571    pub fn is_running(&self) -> bool {
572        self.flags.is_running
573    }
574
575    /// CLAT (RFC 6877) virtual interface (e.g. Android `clat4*` / `v4-*`); local-only
576    #[must_use]
577    pub fn is_clat(&self) -> bool {
578        self.flags.is_clat
579    }
580
581    /// Append an address to this interface; addresses are kept sorted and deduplicated
582    pub fn add_address(&mut self, addr: InterfaceAddress) {
583        self.addrs.push(addr);
584        self.addrs.sort();
585        self.addrs.dedup();
586    }
587
588    /// All addresses bound to this interface.
589    #[must_use]
590    pub fn addresses(&self) -> &[InterfaceAddress] {
591        &self.addrs
592    }
593
594    /// Append a gateway to this interface; gateways are kept sorted and deduplicated.
595    pub fn add_gateway(&mut self, gateway: IpAddr) {
596        self.gateways.push(gateway);
597        self.gateways.sort();
598        self.gateways.dedup();
599    }
600
601    /// Default-route gateways reachable through this interface.
602    #[must_use]
603    pub fn gateways(&self) -> &[IpAddr] {
604        &self.gateways
605    }
606
607    /// Largest IP packet the interface carries, when the OS reports it.
608    #[must_use]
609    pub fn mtu(&self) -> Option<u32> {
610        self.mtu
611    }
612
613    /// Most-preferred IPv4 address on this interface (per `InterfaceAddress::cmp`).
614    #[must_use]
615    pub fn primary_ipv4(&self) -> Option<InterfaceAddress> {
616        let mut ipv4addrs: Vec<&InterfaceAddress> = self
617            .addrs
618            .iter()
619            .filter(|a| matches!(a.if_addr(), IfAddr::V4(_)))
620            .collect();
621        ipv4addrs.sort();
622        ipv4addrs.last().cloned().cloned()
623    }
624
625    /// Most-preferred IPv6 address on this interface (per `InterfaceAddress::cmp`).
626    #[must_use]
627    pub fn primary_ipv6(&self) -> Option<InterfaceAddress> {
628        let mut ipv6addrs: Vec<&InterfaceAddress> = self
629            .addrs
630            .iter()
631            .filter(|a| matches!(a.if_addr(), IfAddr::V6(_)))
632            .collect();
633        ipv6addrs.sort();
634        ipv6addrs.last().cloned().cloned()
635    }
636}
637
638/// The interface a family's outbound traffic leaves from, the address it leaves from and the
639/// gateways it leaves through. A privacy address rotating or an alias coming or going changes
640/// nothing here; the source, a gateway or the interface changing does.
641#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
642pub struct EgressIdentity {
643    /// OS interface name.
644    pub interface: String,
645    /// The address veilid sends from: the kernel's source, or the best published address of
646    /// the family when the kernel sends from a privacy address; `None` with nothing published.
647    pub source: Option<IpAddr>,
648    /// Default-route gateways of the family on this interface, sorted.
649    pub gateways: Vec<IpAddr>,
650}
651
652impl fmt::Display for EgressIdentity {
653    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
654        match self.source {
655            Some(source) => write!(f, "{} {} via {:?}", self.interface, source, self.gateways),
656            None => write!(f, "{} (no source) via {:?}", self.interface, self.gateways),
657        }
658    }
659}
660
661/// The gateway, publication, identity and egress addresses distilled from all interfaces.
662#[derive(Clone, Default, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
663pub struct NetworkInterfaceAddressState {
664    /// Gateway addresses across all interfaces, sorted and deduplicated.
665    pub gateway_addresses: Vec<IpAddr>,
666    /// PUBLICATION set: best routable interface addresses, sorted by preference and
667    /// deduplicated. Privacy, CLAT and CGNAT addresses are excluded from peer info.
668    pub interface_addresses: Vec<IfAddr>,
669    /// IDENTITY set: every address on a running non-loopback interface, sorted and
670    /// deduplicated. Includes privacy addresses, which a peer may report back as our
671    /// external address. Not part of change detection.
672    pub own_addresses: Vec<IpAddr>,
673    /// The interface the kernel sends IPv4 from, the address veilid sends from there and its
674    /// gateways; `None` without an IPv4 default route.
675    pub egress_v4: Option<EgressIdentity>,
676    /// The IPv6 egress, as `egress_v4`.
677    pub egress_v6: Option<EgressIdentity>,
678}
679
680impl NetworkInterfaceAddressState {
681    /// True when the address belongs to one of our interfaces. Identity, not
682    /// publishability: matches privacy (RFC 4941) and CLAT addresses that publication excludes.
683    #[must_use]
684    pub fn is_own_address(&self, addr: IpAddr) -> bool {
685        self.own_addresses.binary_search(&addr).is_ok()
686    }
687}
688
689/// Which address families are present across the running non-loopback interfaces.
690#[derive(Clone, Copy, Default, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
691pub struct RawAddressSummary {
692    /// At least one non-loopback IPv4 address is present.
693    pub has_non_loopback_ipv4: bool,
694    /// At least one non-loopback IPv6 address is present.
695    pub has_non_loopback_ipv6: bool,
696    /// At least one globally-routable unicast IPv6 address is present.
697    pub has_unicast_global_ipv6: bool,
698}
699
700/// Mutex-guarded interior state of `NetworkInterfaces`.
701pub struct NetworkInterfacesInner {
702    /// A successful `refresh` has populated the interface set.
703    valid: bool,
704    /// Interfaces from the last `refresh`, globals kept only on the primary interfaces.
705    interfaces: BTreeMap<String, NetworkInterface>,
706    /// Address state distilled from `interfaces` and the primaries.
707    interface_address_state_cache: Arc<NetworkInterfaceAddressState>,
708    /// The kernel's IPv4 outbound source at the last `refresh`.
709    primary_v4: Option<Ipv4Addr>,
710    /// The kernel's IPv6 outbound source at the last `refresh`.
711    primary_v6: Option<Ipv6Addr>,
712}
713
714/// Cross-platform enumeration of this host's network interfaces and their addresses.
715#[derive(Clone)]
716pub struct NetworkInterfaces {
717    inner: Arc<Mutex<NetworkInterfacesInner>>,
718}
719
720impl fmt::Debug for NetworkInterfaces {
721    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
722        let inner = self.inner.lock();
723        f.debug_struct("NetworkInterfaces")
724            .field("valid", &inner.valid)
725            .field("interfaces", &inner.interfaces)
726            .finish()?;
727        if f.alternate() {
728            writeln!(f)?;
729            writeln!(
730                f,
731                "// interface_address_state_cache: {:?}",
732                inner.interface_address_state_cache
733            )?;
734        }
735        Ok(())
736    }
737}
738
739impl Default for NetworkInterfaces {
740    fn default() -> Self {
741        Self::new()
742    }
743}
744
745impl NetworkInterfaces {
746    /// Make an empty `NetworkInterfaces`; call `refresh` to populate it.
747    #[must_use]
748    pub fn new() -> Self {
749        Self {
750            inner: Arc::new(Mutex::new(NetworkInterfacesInner {
751                valid: false,
752                interfaces: BTreeMap::new(),
753                interface_address_state_cache: Arc::new(NetworkInterfaceAddressState::default()),
754                primary_v4: None,
755                primary_v6: None,
756            })),
757        }
758    }
759
760    /// Whether a successful `refresh` has populated the interface set.
761    #[must_use]
762    pub fn is_valid(&self) -> bool {
763        let inner = self.inner.lock();
764        inner.valid
765    }
766    /// Drop all interfaces and the cached address state, marking the set invalid.
767    pub fn clear(&self) {
768        let mut inner = self.inner.lock();
769
770        inner.interfaces.clear();
771        inner.interface_address_state_cache = Arc::new(NetworkInterfaceAddressState::default());
772        inner.primary_v4 = None;
773        inner.primary_v6 = None;
774        inner.valid = false;
775    }
776    /// Re-enumerate the platform's interfaces. Returns `true` when the publication set, the
777    /// gateways or a family's egress changed; identity-only churn, a privacy address rotating,
778    /// refreshes the cache without reporting a change.
779    ///
780    /// Errors with an `io::Error` if the platform's interface enumeration fails; the interface set is
781    /// left unchanged in that case.
782    pub async fn refresh(&self) -> std::io::Result<bool> {
783        let mut last_interfaces = {
784            let mut last_interfaces = BTreeMap::<String, NetworkInterface>::new();
785            let mut platform_support = PlatformSupport::new();
786            platform_support
787                .get_interfaces(&mut last_interfaces)
788                .await?;
789            last_interfaces
790        };
791
792        // The kernel's outbound source per family names the egress interface; one UDP connect
793        // per family, nothing is sent
794        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
795        let (primary_v4, primary_v6) = (primary_source_ipv4(), primary_source_ipv6());
796        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
797        let (primary_v4, primary_v6): (Option<Ipv4Addr>, Option<Ipv6Addr>) = (None, None);
798
799        // wasm has no network stack to filter
800        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
801        Self::filter_non_primary_global_addresses(&mut last_interfaces, primary_v4, primary_v6);
802
803        let mut inner = self.inner.lock();
804        core::mem::swap(&mut inner.interfaces, &mut last_interfaces);
805        inner.valid = true;
806        // A default route moving between interfaces changes the egress with every address in place
807        let primaries_changed = (inner.primary_v4, inner.primary_v6) != (primary_v4, primary_v6);
808        inner.primary_v4 = primary_v4;
809        inner.primary_v6 = primary_v6;
810
811        if last_interfaces != inner.interfaces || primaries_changed {
812            let old = inner.interface_address_state_cache.clone();
813            Self::cache_interface_address_state(&mut inner);
814            let new = &inner.interface_address_state_cache;
815            if old.gateway_addresses != new.gateway_addresses
816                || old.interface_addresses != new.interface_addresses
817                || old.egress_v4 != new.egress_v4
818                || old.egress_v6 != new.egress_v6
819            {
820                return Ok(true);
821            }
822        }
823        Ok(false)
824    }
825    /// Call `f` with the interface map held under the lock, returning its result.
826    pub fn with_interfaces<F, R>(&self, f: F) -> R
827    where
828        F: FnOnce(&BTreeMap<String, NetworkInterface>) -> R,
829    {
830        let inner = self.inner.lock();
831        f(&inner.interfaces)
832    }
833
834    /// The cached best-address state from the last `refresh`.
835    #[must_use]
836    pub fn interface_address_state(&self) -> Arc<NetworkInterfaceAddressState> {
837        let inner = self.inner.lock();
838        inner.interface_address_state_cache.clone()
839    }
840
841    /// Address presence across running, non-loopback interfaces, NOT filtered by
842    /// `is_temporary()`, since RFC 7217 secured SLAAC globals get marked temporary on macOS.
843    #[must_use]
844    pub fn raw_address_summary(&self) -> RawAddressSummary {
845        let inner = self.inner.lock();
846        let mut summary = RawAddressSummary::default();
847        for intf in inner.interfaces.values() {
848            if !intf.is_running() || intf.is_loopback() {
849                continue;
850            }
851            for addr in intf.addresses() {
852                match addr.if_addr() {
853                    IfAddr::V4(v4) => {
854                        if !v4.ip.is_loopback() && !v4.ip.is_unspecified() {
855                            summary.has_non_loopback_ipv4 = true;
856                        }
857                    }
858                    IfAddr::V6(v6) => {
859                        if !v6.ip.is_loopback() && !v6.ip.is_unspecified() {
860                            summary.has_non_loopback_ipv6 = true;
861                            if ipv6addr_is_unicast_global(&v6.ip) {
862                                summary.has_unicast_global_ipv6 = true;
863                            }
864                        }
865                    }
866                }
867            }
868        }
869        summary
870    }
871
872    /////////////////////////////////////////////
873
874    /// Keep global addresses only on the interface carrying the kernel's primary outbound
875    /// source for that family; a global on any other interface (iOS cellular beside wifi) is
876    /// unreachable from peers, and publishing it causes timeouts. The interface decides, not
877    /// the exact address: the kernel sends from a privacy address, which must not choose the
878    /// stable global that gets published. Private, link-local and ULA addresses stay for
879    /// LocalNetwork. Interfaces left with no addresses are dropped.
880    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
881    pub(crate) fn filter_non_primary_global_addresses(
882        interfaces: &mut BTreeMap<String, NetworkInterface>,
883        primary_v4: Option<Ipv4Addr>,
884        primary_v6: Option<Ipv6Addr>,
885    ) {
886        let primary_v4_intf =
887            primary_v4.and_then(|p| owner_of(interfaces, IpAddr::V4(p)).map(str::to_owned));
888        let primary_v6_intf =
889            primary_v6.and_then(|p| owner_of(interfaces, IpAddr::V6(p)).map(str::to_owned));
890
891        interfaces.retain(|name, intf| {
892            intf.addrs.retain(|addr| match addr.if_addr() {
893                IfAddr::V4(v4) => {
894                    !ipv4addr_is_global(&v4.ip) || primary_v4_intf.as_deref() == Some(name.as_str())
895                }
896                IfAddr::V6(v6) => {
897                    !ipv6addr_is_unicast_global(&v6.ip)
898                        || primary_v6_intf.as_deref() == Some(name.as_str())
899                }
900            });
901            !intf.addrs.is_empty()
902        });
903    }
904
905    fn cache_interface_address_state(inner: &mut NetworkInterfacesInner) {
906        inner.interface_address_state_cache = Arc::new(Self::interface_address_state_for(
907            &inner.interfaces,
908            inner.primary_v4,
909            inner.primary_v6,
910        ));
911    }
912
913    /// The gateway, publication, identity and egress sets distilled from `interfaces`; the
914    /// primaries are the kernel's outbound sources, whose owning interfaces are the egress
915    pub(crate) fn interface_address_state_for(
916        interfaces: &BTreeMap<String, NetworkInterface>,
917        primary_v4: Option<Ipv4Addr>,
918        primary_v6: Option<Ipv6Addr>,
919    ) -> NetworkInterfaceAddressState {
920        // Reduce interfaces to their best routable ip addresses
921        let mut intf_addrs = Vec::new();
922        let mut gateway_addresses = Vec::new();
923        let mut own_addresses = Vec::new();
924        for intf in interfaces.values() {
925            // Skip down, loopback, and CLAT virtual interfaces (Android: clat4*/v4-*)
926            if !intf.is_running() || intf.is_loopback() || intf.is_clat() {
927                continue;
928            }
929
930            for addr in intf.addresses() {
931                // Identity set keeps what publication filters out; peers report those back
932                // to us as our external address
933                own_addresses.push(addr.if_addr().ip());
934                if is_published(addr) {
935                    intf_addrs.push(addr.clone());
936                }
937            }
938
939            for gateway in intf.gateways() {
940                gateway_addresses.push(*gateway);
941            }
942        }
943
944        // Sort one more time to get the best interface addresses overall
945        let mut interface_addresses = intf_addrs
946            .iter()
947            .map(|x| x.if_addr().clone())
948            .collect::<Vec<_>>();
949
950        interface_addresses.sort();
951        interface_addresses.dedup();
952
953        gateway_addresses.sort();
954        gateway_addresses.dedup();
955
956        own_addresses.sort();
957        own_addresses.dedup();
958
959        let egress_v4 = primary_v4.and_then(|p| egress_identity(interfaces, IpAddr::V4(p)));
960        let egress_v6 = primary_v6.and_then(|p| egress_identity(interfaces, IpAddr::V6(p)));
961
962        NetworkInterfaceAddressState {
963            gateway_addresses,
964            interface_addresses,
965            own_addresses,
966            egress_v4,
967            egress_v6,
968        }
969    }
970}
971
972/// The interface holding `ip`, if any
973fn owner_of(interfaces: &BTreeMap<String, NetworkInterface>, ip: IpAddr) -> Option<&str> {
974    interfaces
975        .iter()
976        .find(|(_, intf)| intf.addrs.iter().any(|a| a.if_addr().ip() == ip))
977        .map(|(name, _)| name.as_str())
978}
979
980/// Publication keeps what peers can reach: RFC 4941 privacy addresses rotate and churn peer
981/// info, CLAT46 and CGNAT/DS-Lite addresses are not reachable, IPv4 link-local is a transient
982/// DHCP fallback, and IPv6 link-local needs a scope id no dial info carries, so no peer can
983/// dial it and every tunnel and AirDrop interface would churn peer info as its address rotates
984fn is_published(addr: &InterfaceAddress) -> bool {
985    !addr.is_temporary()
986        && !addr.is_clat()
987        && !addr.is_cgnat_or_ds_lite()
988        && !addr.is_ipv4_link_local()
989        && !addr.is_ipv6_link_local()
990}
991
992/// The interface the kernel sends `primary` from, the address veilid sends from there and the
993/// family's gateways. veilid never binds a privacy address, so when the kernel picked one the
994/// source is the best published address of the family instead, stable across rotations
995fn egress_identity(
996    interfaces: &BTreeMap<String, NetworkInterface>,
997    primary: IpAddr,
998) -> Option<EgressIdentity> {
999    let name = owner_of(interfaces, primary)?;
1000    let intf = &interfaces[name];
1001    let same_family = |ip: IpAddr| ip.is_ipv4() == primary.is_ipv4();
1002    let primary_is_temporary = intf
1003        .addrs
1004        .iter()
1005        .any(|a| a.if_addr().ip() == primary && a.is_temporary());
1006    let source = if primary_is_temporary {
1007        intf.addrs
1008            .iter()
1009            .filter(|a| {
1010                let ip = a.if_addr().ip();
1011                is_published(a)
1012                    && same_family(ip)
1013                    && !matches!(a.if_addr(), IfAddr::V6(v6) if ipv6addr_is_unicast_link_local(&v6.ip))
1014            })
1015            .max()
1016            .map(|a| a.if_addr().ip())
1017    } else {
1018        Some(primary)
1019    };
1020    let gateways = intf
1021        .gateways()
1022        .iter()
1023        .copied()
1024        .filter(|g| same_family(*g))
1025        .collect();
1026    Some(EgressIdentity {
1027        interface: name.to_owned(),
1028        source,
1029        gateways,
1030    })
1031}