]> code.octet-stream.net Git - netwatcher/blob - src/lib.rs
Commit to reporting error if original interface listing fails
[netwatcher] / src / lib.rs
1 use std::{
2 collections::{HashMap, HashSet},
3 net::{IpAddr, Ipv4Addr, Ipv6Addr},
4 ops::Sub,
5 };
6
7 #[cfg_attr(windows, path = "list_win.rs")]
8 #[cfg_attr(unix, path = "list_unix.rs")]
9 mod list;
10
11 #[cfg_attr(windows, path = "watch_win.rs")]
12 #[cfg_attr(target_vendor = "apple", path = "watch_mac.rs")]
13 #[cfg_attr(target_os = "linux", path = "watch_linux.rs")]
14 mod watch;
15
16 type IfIndex = u32;
17
18 /// Information about one network interface at a point in time.
19 #[derive(Debug, Clone, PartialEq, Eq)]
20 pub struct Interface {
21 pub index: u32,
22 pub name: String,
23 pub hw_addr: String,
24 pub ips: Vec<IpAddr>,
25 }
26
27 impl Interface {
28 /// Helper to iterate over only the IPv4 addresses on this interface.
29 pub fn ipv4_ips(&self) -> impl Iterator<Item = &Ipv4Addr> {
30 self.ips.iter().filter_map(|ip| match ip {
31 IpAddr::V4(v4) => Some(v4),
32 IpAddr::V6(_) => None,
33 })
34 }
35
36 /// Helper to iterate over only the IPv6 addresses on this interface.
37 pub fn ipv6_ips(&self) -> impl Iterator<Item = &Ipv6Addr> {
38 self.ips.iter().filter_map(|ip| match ip {
39 IpAddr::V4(_) => None,
40 IpAddr::V6(v6) => Some(v6),
41 })
42 }
43 }
44
45 /// Information delivered via callback when a network interface change is detected.
46 ///
47 /// This contains up-to-date information about all interfaces, plus a diff which
48 /// details which interfaces and IP addresses have changed since the last callback.
49 #[derive(Debug, Clone, PartialEq, Eq)]
50 pub struct Update {
51 pub interfaces: HashMap<IfIndex, Interface>,
52 pub diff: UpdateDiff,
53 }
54
55 /// What changed between one `Update` and the next.
56 #[derive(Debug, Clone, PartialEq, Eq, Default)]
57 pub struct UpdateDiff {
58 pub added: Vec<IfIndex>,
59 pub removed: Vec<IfIndex>,
60 pub modified: HashMap<IfIndex, InterfaceDiff>,
61 }
62
63 /// What changed within a single interface between updates, if it was present in both.
64 #[derive(Debug, Clone, PartialEq, Eq, Default)]
65 pub struct InterfaceDiff {
66 pub hw_addr_changed: bool,
67 pub addrs_added: Vec<IpAddr>,
68 pub addrs_removed: Vec<IpAddr>,
69 }
70
71 /// Errors in netwatcher or in one of the underlying platform integratinos.
72 #[derive(Debug, Clone, PartialEq, Eq)]
73 pub enum Error {
74 // TODO: handle all cases with proper sources
75 Internal,
76 }
77
78 #[derive(Default, PartialEq, Eq)]
79 struct List(HashMap<IfIndex, Interface>);
80
81 impl List {
82 fn diff_from(&self, prev: &List) -> UpdateDiff {
83 let prev_index_set: HashSet<IfIndex> = prev.0.keys().cloned().collect();
84 let curr_index_set: HashSet<IfIndex> = self.0.keys().cloned().collect();
85 let added = curr_index_set.sub(&prev_index_set).into_iter().collect();
86 let removed = prev_index_set.sub(&curr_index_set).into_iter().collect();
87 let mut modified = HashMap::new();
88 for index in curr_index_set.intersection(&prev_index_set) {
89 if prev.0[index] == self.0[index] {
90 continue;
91 }
92 let prev_addr_set: HashSet<&IpAddr> = prev.0[index].ips.iter().collect();
93 let curr_addr_set: HashSet<&IpAddr> = self.0[index].ips.iter().collect();
94 let addrs_added: Vec<IpAddr> = curr_addr_set
95 .sub(&prev_addr_set)
96 .iter()
97 .cloned()
98 .cloned()
99 .collect();
100 let addrs_removed: Vec<IpAddr> = prev_addr_set
101 .sub(&curr_addr_set)
102 .iter()
103 .cloned()
104 .cloned()
105 .collect();
106 let hw_addr_changed = prev.0[index].hw_addr != self.0[index].hw_addr;
107 modified.insert(
108 *index,
109 InterfaceDiff {
110 hw_addr_changed,
111 addrs_added,
112 addrs_removed,
113 },
114 );
115 }
116 UpdateDiff {
117 added,
118 removed,
119 modified,
120 }
121 }
122 }
123
124 /// A handle to keep alive as long as you wish to receive callbacks.
125 ///
126 /// If the callback is executing at the time the handle is dropped, drop will block until
127 /// the callback is finished and it's guaranteed that it will not be called again.
128 ///
129 /// Do not drop the handle from within the callback itself. It will probably deadlock.
130 pub struct WatchHandle {
131 _inner: watch::WatchHandle,
132 }
133
134 /// Retrieve information about all enabled network interfaces and their IP addresses.
135 ///
136 /// This is a once-off operation. If you want to detect changes over time, see `watch_interfaces`.
137 pub fn list_interfaces() -> Result<HashMap<IfIndex, Interface>, Error> {
138 list::list_interfaces().map(|list| list.0)
139 }
140
141 /// Retrieve interface information and watch for changes, which will be delivered via callback.
142 ///
143 /// If setting up the watch is successful, this returns a `WatchHandle` which must be kept for
144 /// as long as the provided callback should operate.
145 ///
146 /// The callback will fire once immediately with an initial interface list, and a diff as if
147 /// there were originally no interfaces present.
148 ///
149 /// This function will return an error if there is a problem configuring the watcher, or if there
150 /// is an error retrieving the initial interface list.
151 ///
152 /// We assume that if listing the interfaces worked the first time, then it will continue to work
153 /// for as long as the watcher is running. If listing interfaces begins to fail later, those
154 /// failures will be swallowed and the callback will not be called for that change event.
155 pub fn watch_interfaces<F: FnMut(Update) + Send + 'static>(
156 callback: F,
157 ) -> Result<WatchHandle, Error> {
158 watch::watch_interfaces(callback).map(|handle| WatchHandle { _inner: handle })
159 }