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#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
32pub enum IfAddr {
33 V4(Ifv4Addr),
35 V6(Ifv6Addr),
37}
38
39impl IfAddr {
40 #[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 #[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 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 #[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 #[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#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
100pub struct Ifv4Addr {
101 pub ip: Ipv4Addr,
103 pub netmask: Ipv4Addr,
105 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 #[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 #[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 #[must_use]
181 pub fn prefix_len(&self) -> Option<u8> {
182 ipv4_netmask_to_prefix_len(self.netmask)
183 }
184}
185
186#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
188pub struct Ifv6Addr {
189 pub ip: Ipv6Addr,
191 pub netmask: Ipv6Addr,
193 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 #[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 #[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 #[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#[derive(
288 Debug, Default, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Copy, Serialize, Deserialize,
289)]
290pub struct InterfaceFlags {
291 pub is_loopback: bool,
293 pub is_running: bool,
295 pub is_point_to_point: bool,
297 pub is_clat: bool,
299}
300
301#[derive(
303 Debug, Default, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Copy, Serialize, Deserialize,
304)]
305pub struct AddressFlags {
306 pub is_dynamic: bool,
308 pub is_temporary: bool,
310 pub is_preferred: bool,
312 pub is_clat: bool,
314 pub expiration_secs: Option<u64>,
316}
317
318#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
320pub struct InterfaceAddress {
321 pub if_addr: IfAddr,
323 pub flags: AddressFlags,
325}
326
327use core::cmp::Ordering;
328
329impl 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 let ret = ipv4addr_is_global(&a.ip).cmp(&ipv4addr_is_global(&b.ip));
336 if ret != Ordering::Equal {
337 return ret;
338 }
339 let ret = ipv4addr_is_private(&a.ip).cmp(&ipv4addr_is_private(&b.ip));
341 if ret != Ordering::Equal {
342 return ret;
343 }
344 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 let ret = self.flags.is_preferred.cmp(&other.flags.is_preferred);
353 if ret != Ordering::Equal {
354 return ret;
355 }
356 let ret = (!self.flags.is_temporary).cmp(&!other.flags.is_temporary);
358 if ret != Ordering::Equal {
359 return ret;
360 }
361 let ret = ipv6addr_is_global(&a.ip).cmp(&ipv6addr_is_global(&b.ip));
363 if ret != Ordering::Equal {
364 return ret;
365 }
366 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 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 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 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 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 return Ordering::Greater;
400 }
401 (IfAddr::V6(a), IfAddr::V4(b)) => {
402 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 return Ordering::Less;
412 }
413 }
414 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 #[must_use]
431 pub fn new(if_addr: IfAddr, flags: AddressFlags) -> Self {
432 Self { if_addr, flags }
433 }
434
435 #[must_use]
437 pub fn if_addr(&self) -> &IfAddr {
438 &self.if_addr
439 }
440
441 #[must_use]
443 pub fn is_temporary(&self) -> bool {
444 self.flags.is_temporary
445 }
446
447 #[must_use]
449 pub fn is_dynamic(&self) -> bool {
450 self.flags.is_dynamic
451 }
452
453 #[must_use]
455 pub fn is_preferred(&self) -> bool {
456 self.flags.is_preferred
457 }
458
459 #[must_use]
461 pub fn is_clat(&self) -> bool {
462 self.flags.is_clat
463 }
464
465 #[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 #[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 #[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(PartialEq, Eq, Clone, Serialize, Deserialize)]
508pub struct NetworkInterface {
509 pub name: String,
511 pub flags: InterfaceFlags,
513 pub gateways: Vec<IpAddr>,
515 pub addrs: Vec<InterfaceAddress>,
517 #[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 #[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 #[must_use]
553 pub fn name(&self) -> String {
554 self.name.clone()
555 }
556
557 #[must_use]
559 pub fn is_loopback(&self) -> bool {
560 self.flags.is_loopback
561 }
562
563 #[must_use]
565 pub fn is_point_to_point(&self) -> bool {
566 self.flags.is_point_to_point
567 }
568
569 #[must_use]
571 pub fn is_running(&self) -> bool {
572 self.flags.is_running
573 }
574
575 #[must_use]
577 pub fn is_clat(&self) -> bool {
578 self.flags.is_clat
579 }
580
581 pub fn add_address(&mut self, addr: InterfaceAddress) {
583 self.addrs.push(addr);
584 self.addrs.sort();
585 self.addrs.dedup();
586 }
587
588 #[must_use]
590 pub fn addresses(&self) -> &[InterfaceAddress] {
591 &self.addrs
592 }
593
594 pub fn add_gateway(&mut self, gateway: IpAddr) {
596 self.gateways.push(gateway);
597 self.gateways.sort();
598 self.gateways.dedup();
599 }
600
601 #[must_use]
603 pub fn gateways(&self) -> &[IpAddr] {
604 &self.gateways
605 }
606
607 #[must_use]
609 pub fn mtu(&self) -> Option<u32> {
610 self.mtu
611 }
612
613 #[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 #[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#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
642pub struct EgressIdentity {
643 pub interface: String,
645 pub source: Option<IpAddr>,
648 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#[derive(Clone, Default, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
663pub struct NetworkInterfaceAddressState {
664 pub gateway_addresses: Vec<IpAddr>,
666 pub interface_addresses: Vec<IfAddr>,
669 pub own_addresses: Vec<IpAddr>,
673 pub egress_v4: Option<EgressIdentity>,
676 pub egress_v6: Option<EgressIdentity>,
678}
679
680impl NetworkInterfaceAddressState {
681 #[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#[derive(Clone, Copy, Default, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
691pub struct RawAddressSummary {
692 pub has_non_loopback_ipv4: bool,
694 pub has_non_loopback_ipv6: bool,
696 pub has_unicast_global_ipv6: bool,
698}
699
700pub struct NetworkInterfacesInner {
702 valid: bool,
704 interfaces: BTreeMap<String, NetworkInterface>,
706 interface_address_state_cache: Arc<NetworkInterfaceAddressState>,
708 primary_v4: Option<Ipv4Addr>,
710 primary_v6: Option<Ipv6Addr>,
712}
713
714#[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 #[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 #[must_use]
762 pub fn is_valid(&self) -> bool {
763 let inner = self.inner.lock();
764 inner.valid
765 }
766 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 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 #[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 #[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 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 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 #[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 #[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 #[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 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 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 if !intf.is_running() || intf.is_loopback() || intf.is_clat() {
927 continue;
928 }
929
930 for addr in intf.addresses() {
931 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 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
972fn 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
980fn 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
992fn 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}