use std::{
collections::{HashMap, HashSet},
net::{IpAddr, Ipv4Addr, Ipv6Addr},
ops::Sub,
};
mod error;
#[cfg(any(windows, target_os = "android"))]
mod async_callback;
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
mod watch_fd;
#[cfg_attr(windows, path = "list_win.rs")]
#[cfg_attr(unix, path = "list_unix.rs")]
mod list;
#[cfg(target_os = "android")]
mod android;
#[cfg_attr(windows, path = "watch_win.rs")]
#[cfg_attr(target_vendor = "apple", path = "watch_mac.rs")]
#[cfg_attr(target_os = "linux", path = "watch_linux.rs")]
#[cfg_attr(target_os = "android", path = "watch_android.rs")]
mod watch;
pub mod async_adapter;
type IfIndex = u32;
pub use error::Error;
#[cfg(target_os = "android")]
pub use android::set_android_context;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IpRecord {
pub ip: IpAddr,
pub prefix_len: u8,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Interface {
pub index: u32,
pub name: String,
pub hw_addr: String,
pub ips: Vec<IpRecord>,
}
impl Interface {
pub fn ipv4_ips(&self) -> impl Iterator<Item = &Ipv4Addr> {
self.ips.iter().filter_map(|ip_record| match ip_record.ip {
IpAddr::V4(ref v4) => Some(v4),
IpAddr::V6(_) => None,
})
}
pub fn ipv6_ips(&self) -> impl Iterator<Item = &Ipv6Addr> {
self.ips.iter().filter_map(|ip_record| match ip_record.ip {
IpAddr::V4(_) => None,
IpAddr::V6(ref v6) => Some(v6),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Update {
pub is_initial: bool,
pub interfaces: HashMap<IfIndex, Interface>,
pub diff: UpdateDiff,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct UpdateDiff {
pub added: Vec<IfIndex>,
pub removed: Vec<IfIndex>,
pub modified: HashMap<IfIndex, InterfaceDiff>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct InterfaceDiff {
pub hw_addr_changed: bool,
pub addrs_added: Vec<IpRecord>,
pub addrs_removed: Vec<IpRecord>,
}
#[derive(Default, PartialEq, Eq, Clone)]
struct List(HashMap<IfIndex, Interface>);
impl List {
fn initial_update(&self) -> Update {
self.update_from_with_flag(&List::default(), true)
}
fn update_from(&self, prev: &List) -> Update {
self.update_from_with_flag(prev, false)
}
fn update_from_with_flag(&self, prev: &List, is_initial: bool) -> Update {
let prev_index_set: HashSet<IfIndex> = prev.0.keys().cloned().collect();
let curr_index_set: HashSet<IfIndex> = self.0.keys().cloned().collect();
let added = curr_index_set.sub(&prev_index_set).into_iter().collect();
let removed = prev_index_set.sub(&curr_index_set).into_iter().collect();
let mut modified = HashMap::new();
for index in curr_index_set.intersection(&prev_index_set) {
if prev.0[index] == self.0[index] {
continue;
}
let prev_addr_set: HashSet<&IpRecord> = prev.0[index].ips.iter().collect();
let curr_addr_set: HashSet<&IpRecord> = self.0[index].ips.iter().collect();
let addrs_added: Vec<IpRecord> = curr_addr_set
.sub(&prev_addr_set)
.iter()
.cloned()
.cloned()
.collect();
let addrs_removed: Vec<IpRecord> = prev_addr_set
.sub(&curr_addr_set)
.iter()
.cloned()
.cloned()
.collect();
let hw_addr_changed = prev.0[index].hw_addr != self.0[index].hw_addr;
modified.insert(
*index,
InterfaceDiff {
hw_addr_changed,
addrs_added,
addrs_removed,
},
);
}
Update {
is_initial,
interfaces: self.0.clone(),
diff: UpdateDiff {
added,
removed,
modified,
},
}
}
}
struct UpdateCursor {
prev_list: List,
initial_pending: bool,
}
impl Default for UpdateCursor {
fn default() -> Self {
Self {
prev_list: List::default(),
initial_pending: true,
}
}
}
impl UpdateCursor {
fn advance(&mut self, new_list: List) -> Option<Update> {
if self.initial_pending {
self.initial_pending = false;
self.prev_list = new_list.clone();
return Some(new_list.initial_update());
}
if new_list == self.prev_list {
return None;
}
let update = new_list.update_from(&self.prev_list);
self.prev_list = new_list;
Some(update)
}
}
pub struct WatchHandle {
_inner: watch::WatchHandle,
}
pub struct AsyncWatch {
_inner: watch::AsyncWatch,
}
pub struct BlockingWatch {
_inner: watch::BlockingWatch,
}
impl AsyncWatch {
pub async fn changed(&mut self) -> Update {
self._inner.changed().await
}
}
impl BlockingWatch {
pub fn updated(&mut self) -> Update {
self._inner.updated()
}
}
pub fn list_interfaces() -> Result<HashMap<IfIndex, Interface>, Error> {
list::list_interfaces().map(|list| list.0)
}
pub fn watch_interfaces_with_callback<F: FnMut(Update) + Send + 'static>(
callback: F,
) -> Result<WatchHandle, Error> {
watch::watch_interfaces_with_callback(callback).map(|handle| WatchHandle { _inner: handle })
}
pub fn watch_interfaces_blocking() -> Result<BlockingWatch, Error> {
watch::watch_interfaces_blocking().map(|handle| BlockingWatch { _inner: handle })
}
pub fn watch_interfaces_async<A: async_adapter::AsyncFdAdapter>() -> Result<AsyncWatch, Error> {
watch::watch_interfaces_async::<A>().map(|handle| AsyncWatch { _inner: handle })
}