netwatch 0.19.0

Cross-platform monitoring for network interface changes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Contains helpers for looking up system network interfaces.

use std::{collections::HashMap, fmt, net::IpAddr};

use n0_future::time::Instant;

#[cfg(any(
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "macos",
    target_os = "ios"
))]
pub(super) mod bsd;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux;
#[cfg(target_os = "windows")]
mod windows;

pub(crate) use ipnet::{Ipv4Net, Ipv6Net};
pub use netdev::interface::ipv6_addr_flags::Ipv6AddrFlags;

#[cfg(any(
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "macos",
    target_os = "ios"
))]
use self::bsd::default_route;
#[cfg(any(target_os = "linux", target_os = "android"))]
use self::linux::default_route;
#[cfg(target_os = "windows")]
use self::windows::default_route;
#[cfg(not(wasm_browser))]
use crate::ip::is_link_local;
use crate::ip::{LocalAddresses, is_private_v6, is_up};
#[cfg(not(wasm_browser))]
use crate::netmon::is_interesting_interface;

/// Represents a network interface.
#[derive(Debug, Clone)]
pub struct Interface {
    iface: netdev::Interface,
}

impl fmt::Display for Interface {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}. {} {:?} ipv4={:?} ipv6={:?}",
            self.iface.index, self.iface.name, self.iface.if_type, self.iface.ipv4, self.iface.ipv6
        )
    }
}

impl PartialEq for Interface {
    fn eq(&self, other: &Self) -> bool {
        self.iface.index == other.iface.index
            && self.iface.name == other.iface.name
            && self.iface.flags == other.iface.flags
            && self.iface.mac_addr.as_ref().map(|a| a.octets())
                == other.iface.mac_addr.as_ref().map(|a| a.octets())
    }
}

impl Eq for Interface {}

impl Interface {
    /// Is this interface up?
    pub fn is_up(&self) -> bool {
        is_up(&self.iface)
    }

    /// The name of the interface.
    pub fn name(&self) -> &str {
        &self.iface.name
    }

    /// A list of all ip addresses of this interface.
    pub fn addrs(&self) -> impl Iterator<Item = IpNet> + '_ {
        self.iface.ipv4.iter().cloned().map(IpNet::V4).chain(
            self.iface
                .ipv6
                .iter()
                .zip(self.iface.ipv6_scope_ids.iter())
                .zip(self.iface.ipv6_addr_flags.iter())
                .map(|((net, scope_id), flags)| IpNet::V6 {
                    net: *net,
                    scope_id: *scope_id,
                    flags: *flags,
                }),
        )
    }

    /// Creates a fake interface for usage in tests.
    ///
    /// This allows tests to be independent of the host interfaces.
    pub(crate) fn fake() -> Self {
        use std::net::Ipv4Addr;

        use netdev::{
            NetworkDevice,
            prelude::{InterfaceType, MacAddr, OperState},
        };

        Self {
            iface: netdev::Interface {
                index: 2,
                name: String::from("wifi0"),
                friendly_name: None,
                description: None,
                if_type: InterfaceType::Ethernet,
                mac_addr: Some(MacAddr::new(2, 3, 4, 5, 6, 7)),
                ipv4: vec![Ipv4Net::new(Ipv4Addr::new(192, 168, 0, 189), 24).unwrap()],
                ipv6: vec![],
                flags: 69699,
                transmit_speed: None,
                receive_speed: None,
                gateway: Some(NetworkDevice {
                    mac_addr: MacAddr::new(2, 3, 4, 5, 6, 8),
                    ipv4: vec![Ipv4Addr::from([192, 168, 0, 1])],
                    ipv6: vec![],
                }),
                dns_servers: vec![],
                default: false,
                ipv6_scope_ids: vec![],
                ipv6_addr_flags: vec![],
                stats: None,
                mtu: None,
                oper_state: OperState::Up,
                auto_negotiate: None,
                dhcp_v4_enabled: None,
                dhcp_v6_enabled: None,
            },
        }
    }
}

/// Structure of an IP network, either IPv4 or IPv6.
#[derive(Clone, Debug)]
pub enum IpNet {
    /// Structure of IPv4 Network.
    V4(Ipv4Net),
    /// Structure of IPv6 Network.
    V6 {
        /// The actual network address.
        net: Ipv6Net,
        /// IPv6 scope ID
        scope_id: u32,
        /// IPv6 address flags.
        flags: Ipv6AddrFlags,
    },
}

impl PartialEq for IpNet {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (IpNet::V4(a), IpNet::V4(b)) => {
                a.addr() == b.addr()
                    && a.prefix_len() == b.prefix_len()
                    && a.netmask() == b.netmask()
            }
            (
                IpNet::V6 {
                    net: net_a,
                    scope_id: scope_id_a,
                    flags: flags_a,
                },
                IpNet::V6 {
                    net: net_b,
                    scope_id: scope_id_b,
                    flags: flags_b,
                },
            ) => {
                net_a.addr() == net_b.addr()
                    && net_a.prefix_len() == net_b.prefix_len()
                    && net_a.netmask() == net_b.netmask()
                    && scope_id_a == scope_id_b
                    && flags_a == flags_b
            }
            _ => false,
        }
    }
}
impl Eq for IpNet {}

impl IpNet {
    /// The IP address of this structure.
    pub fn addr(&self) -> IpAddr {
        match self {
            IpNet::V4(a) => IpAddr::V4(a.addr()),
            IpNet::V6 { net, .. } => IpAddr::V6(net.addr()),
        }
    }
}

/// Intended to store the state of the machine's network interfaces, routing table, and
/// other network configuration. For now it's pretty basic.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct State {
    /// Maps from an interface name interface.
    pub interfaces: HashMap<String, Interface>,
    /// List of machine's local IP addresses.
    pub local_addresses: LocalAddresses,

    /// Whether this machine has an IPv6 Global or Unique Local Address
    /// which might provide connectivity.
    pub have_v6: bool,

    /// Whether the machine has some non-localhost, non-link-local IPv4 address.
    pub have_v4: bool,

    /// Whether the current network interface is considered "expensive", which currently means LTE/etc
    /// instead of Wifi. This field is not populated by `get_state`.
    pub is_expensive: bool,

    /// The interface name for the machine's default route.
    ///
    /// It is not yet populated on all OSes.
    ///
    /// When set, its value is the map key into `interface` and `interface_ips`.
    pub default_route_interface: Option<String>,

    /// Monotonic timestamp, when an unsuspend was detected.
    pub last_unsuspend: Option<Instant>,
}

impl fmt::Display for State {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut ifaces: Vec<_> = self.interfaces.values().collect();
        ifaces.sort_by_key(|iface| iface.iface.index);
        for iface in ifaces {
            write!(f, "{iface}")?;
            if let Some(ref default_if) = self.default_route_interface
                && iface.name() == default_if
            {
                write!(f, " (default)")?;
            }
            if f.alternate() {
                writeln!(f)?;
            } else {
                write!(f, "; ")?;
            }
        }
        Ok(())
    }
}

impl State {
    /// Returns the state of all the current machine's network interfaces.
    ///
    /// It does not set the returned `State.is_expensive`. The caller can populate that.
    pub async fn new() -> Self {
        let mut interfaces = HashMap::new();
        let mut have_v6 = false;
        let mut have_v4 = false;

        let ifaces = netdev::interface::get_interfaces();
        let local_addresses = LocalAddresses::from_raw_interfaces(&ifaces);

        for mut iface in ifaces {
            // ensure these are all sorted, so any comparisons made are stable
            iface.ipv4.sort();
            iface.dns_servers.sort();

            // ipv6_scope_ids and ipv6_addr_flags need to match ipv6 order
            sort_ipv6(&mut iface);

            let ni = Interface { iface };
            let if_up = ni.is_up();
            let name = ni.iface.name.clone();
            let pfxs: Vec<_> = ni.addrs().collect();

            if if_up {
                for pfx in &pfxs {
                    if pfx.addr().is_loopback() {
                        continue;
                    }
                    have_v6 |= is_usable_v6(&pfx.addr());
                    have_v4 |= is_usable_v4(&pfx.addr());
                }
            }

            interfaces.insert(name, ni);
        }

        let default_route_interface = default_route_interface().await;

        State {
            interfaces,
            local_addresses,
            have_v4,
            have_v6,
            is_expensive: false,
            default_route_interface,
            last_unsuspend: None,
        }
    }

    /// Creates a fake interface state for usage in tests.
    ///
    /// This allows tests to be independent of the host interfaces.
    pub fn fake() -> Self {
        let fake = Interface::fake();
        let ifname = fake.iface.name.clone();
        Self {
            interfaces: [(ifname.clone(), fake)].into_iter().collect(),
            local_addresses: LocalAddresses::from_raw_interfaces(&[]),
            have_v6: true,
            have_v4: true,
            is_expensive: false,
            default_route_interface: Some(ifname),
            last_unsuspend: None,
        }
    }

    /// Is this a major change compared to the `old` one?.
    pub fn is_major_change(&self, old: &State) -> bool {
        if self.have_v6 != old.have_v6
            || self.have_v4 != old.have_v4
            || self.is_expensive != old.is_expensive
            || self.default_route_interface != old.default_route_interface
        {
            return true;
        }

        for (iname, i) in &old.interfaces {
            if !is_interesting_interface(i.name()) {
                continue;
            }
            let Some(i2) = self.interfaces.get(iname) else {
                return true;
            };
            if i != i2 || !prefixes_major_equal(i.addrs(), i2.addrs()) {
                return true;
            }
        }

        // Check for new interesting interfaces not present in old state
        for (iname, i) in &self.interfaces {
            if !is_interesting_interface(i.name()) {
                continue;
            }
            if !old.interfaces.contains_key(iname) {
                return true;
            }
        }

        false
    }
}

/// Sorts all ipv6 related fields in one go.
fn sort_ipv6(iface: &mut netdev::Interface) {
    let n = iface.ipv6.len();
    debug_assert_eq!(n, iface.ipv6_scope_ids.len());
    debug_assert_eq!(n, iface.ipv6_addr_flags.len());

    let mut keys: Vec<_> = (0..n).collect();

    // calculate ordering
    keys.sort_by_key(|x| &iface.ipv6[*x]);

    // apply ordering to all three
    iface.ipv6 = keys.iter().map(|&i| iface.ipv6[i]).collect();
    iface.ipv6_scope_ids = keys.iter().map(|&i| iface.ipv6_scope_ids[i]).collect();
    iface.ipv6_addr_flags = keys.iter().map(|&i| iface.ipv6_addr_flags[i]).collect();
}

/// Reports whether ip is a usable IPv4 address which should have Internet connectivity.
///
/// Globally routable and private IPv4 addresses are always Usable, and link local
/// 169.254.x.x addresses are in some environments.
fn is_usable_v4(ip: &IpAddr) -> bool {
    if !ip.is_ipv4() || ip.is_loopback() {
        return false;
    }

    true
}

/// Reports whether ip is a usable IPv6 address which should have Internet connectivity.
///
/// Globally routable IPv6 addresses are always Usable, and Unique Local Addresses
/// (fc00::/7) are in some environments used with address translation.
///
/// We consider all 2000::/3 addresses to be routable, which is the interpretation of
/// <https://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml>
/// as well.  However this probably includes some addresses which should not be routed,
/// e.g. documentation addresses.  See also
/// <https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html#method.is_global> for an
/// alternative implementation which is both stricter and laxer in some regards.
fn is_usable_v6(ip: &IpAddr) -> bool {
    match ip {
        IpAddr::V6(ip) => {
            // V6 Global1 2000::/3
            let mask: u16 = 0b1110_0000_0000_0000;
            let base: u16 = 0x2000;
            let segment1 = ip.segments()[0];
            if (base & mask) == (segment1 & mask) {
                return true;
            }

            is_private_v6(ip)
        }
        IpAddr::V4(_) => false,
    }
}

/// The details about a default route.
#[derive(Debug, Clone)]
pub struct DefaultRouteDetails {
    /// The interface name.
    /// It's like "eth0" (Linux), "Ethernet 2" (Windows), "en0" (macOS).
    pub interface_name: String,
}

impl DefaultRouteDetails {
    /// Reads the default route from the current system and returns the details.
    pub async fn new() -> Option<Self> {
        default_route().await
    }
}

/// Like `DefaultRoutDetails::new` but only returns the interface name.
pub async fn default_route_interface() -> Option<String> {
    DefaultRouteDetails::new().await.map(|v| v.interface_name)
}

/// Likely IPs of the residentla router, and the ip address of the current
/// machine using it.
#[derive(Debug, Clone)]
pub struct HomeRouter {
    /// Ip of the router.
    pub gateway: IpAddr,
    /// Our local Ip if known.
    pub my_ip: Option<IpAddr>,
}

impl HomeRouter {
    /// Returns the likely IP of the residential router, which will always
    /// be a private address, if found.
    /// In addition, it returns the IP address of the current machine on
    /// the LAN using that gateway.
    /// This is used as the destination for UPnP, NAT-PMP, PCP, etc queries.
    pub fn new() -> Option<Self> {
        let gateway = Self::get_default_gateway()?;
        let my_ip = netdev::net::ip::get_local_ipaddr();

        Some(HomeRouter { gateway, my_ip })
    }

    #[cfg(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "macos",
        target_os = "ios"
    ))]
    fn get_default_gateway() -> Option<IpAddr> {
        // netdev doesn't work yet
        // See: https://github.com/shellrow/default-net/issues/34
        bsd::likely_home_router()
    }

    #[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
    fn get_default_gateway() -> Option<IpAddr> {
        let gateway = netdev::get_default_gateway().ok()?;
        gateway
            .ipv4
            .iter()
            .cloned()
            .map(IpAddr::V4)
            .chain(gateway.ipv6.iter().cloned().map(IpAddr::V6))
            .next()
    }
}

/// Checks whether `a` and `b` are equal after ignoring uninteresting
/// things, like link-local, loopback and multicast addresses.
#[cfg(not(wasm_browser))]
fn prefixes_major_equal(a: impl Iterator<Item = IpNet>, b: impl Iterator<Item = IpNet>) -> bool {
    fn is_interesting(p: &IpNet) -> bool {
        let a = p.addr();
        if is_link_local(a) || a.is_loopback() || a.is_multicast() {
            return false;
        }
        true
    }

    let mut a = a.filter(is_interesting);
    let mut b = b.filter(is_interesting);

    loop {
        match (a.next(), b.next()) {
            (None, None) => return true,
            (Some(a), Some(b)) if a == b => continue,
            _ => return false,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::net::Ipv6Addr;

    use super::*;

    #[test]
    fn test_is_major_change_identical() {
        let a = State::fake();
        let b = State::fake();
        assert!(!a.is_major_change(&b));
    }

    #[test]
    fn test_is_major_change_new_interface_added() {
        let old = State::fake();
        let mut new = State::fake();
        // Add a new interesting interface to new state
        let mut iface = Interface::fake();
        iface.iface.index = 10;
        iface.iface.name = "eth1".to_string();
        new.interfaces.insert("eth1".to_string(), iface);
        assert!(new.is_major_change(&old));
    }

    #[test]
    fn test_is_major_change_interface_removed() {
        let old = State::fake();
        let mut new = State::fake();
        new.interfaces.clear();
        assert!(new.is_major_change(&old));
    }

    #[tokio::test]
    async fn test_default_route() {
        let default_route = DefaultRouteDetails::new()
            .await
            .expect("missing default route");
        println!("default_route: {default_route:#?}");
    }

    #[tokio::test]
    async fn test_likely_home_router() {
        let home_router = HomeRouter::new().expect("missing home router");
        println!("home router: {home_router:#?}");
    }

    #[test]
    fn test_prefixes_major_equal() {
        use std::net::Ipv4Addr;

        let a1 = IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 0, 1), 24).unwrap());
        let a2 = IpNet::V4(Ipv4Net::new(Ipv4Addr::new(10, 0, 0, 1), 8).unwrap());
        let a3 = IpNet::V4(Ipv4Net::new(Ipv4Addr::new(172, 16, 0, 1), 16).unwrap());

        // equal lists
        assert!(prefixes_major_equal(
            vec![a1.clone(), a2.clone()].into_iter(),
            vec![a1.clone(), a2.clone()].into_iter(),
        ));

        // both empty
        assert!(prefixes_major_equal(std::iter::empty(), std::iter::empty(),));

        // different prefixes
        assert!(!prefixes_major_equal(
            vec![a1.clone()].into_iter(),
            vec![a2.clone()].into_iter(),
        ));

        // a has extra prefix
        assert!(!prefixes_major_equal(
            vec![a1.clone(), a2.clone(), a3.clone()].into_iter(),
            vec![a1.clone(), a2.clone()].into_iter(),
        ));

        // b has extra prefix
        assert!(!prefixes_major_equal(
            vec![a1.clone(), a2.clone()].into_iter(),
            vec![a1.clone(), a2.clone(), a3.clone()].into_iter(),
        ));
    }

    #[test]
    fn test_sort_ipv6() {
        let addr_a = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
        let addr_b = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2);
        let addr_c = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);

        let net_a = Ipv6Net::new(addr_a, 64).unwrap();
        let net_b = Ipv6Net::new(addr_b, 64).unwrap();
        let net_c = Ipv6Net::new(addr_c, 64).unwrap();

        let flags_a = Ipv6AddrFlags {
            permanent: true,
            ..Default::default()
        };
        let flags_b = Ipv6AddrFlags {
            temporary: true,
            ..Default::default()
        };
        let flags_c = Ipv6AddrFlags {
            deprecated: true,
            ..Default::default()
        };

        let mut iface = Interface::fake().iface;

        // Deliberately out of sorted order: c, b, a
        iface.ipv6 = vec![net_c, net_b, net_a];
        iface.ipv6_scope_ids = vec![30, 20, 10];
        iface.ipv6_addr_flags = vec![flags_c, flags_b, flags_a];

        sort_ipv6(&mut iface);

        assert_eq!(iface.ipv6, vec![net_a, net_b, net_c]);
        assert_eq!(iface.ipv6_scope_ids, vec![10, 20, 30]);
        assert!(iface.ipv6_addr_flags[0].permanent);
        assert!(iface.ipv6_addr_flags[1].temporary);
        assert!(iface.ipv6_addr_flags[2].deprecated);
    }

    #[test]
    fn test_is_usable_v6() {
        let loopback = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1);
        assert!(!is_usable_v6(&loopback.into()));

        let link_local = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xcbc9, 0x6aff, 0x5b07, 0x4a9e);
        assert!(!is_usable_v6(&link_local.into()));

        let relay_use1 = Ipv6Addr::new(0x2a01, 0x4ff, 0xf0, 0xc4a1, 0, 0, 0, 0x1);
        assert!(is_usable_v6(&relay_use1.into()));

        let random_2603 = Ipv6Addr::new(0x2603, 0x3ff, 0xf1, 0xc3aa, 0x1, 0x2, 0x3, 0x1);
        assert!(is_usable_v6(&random_2603.into()));
    }
}