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