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
macro_rules! size_of {
($t:ty) => {
::core::mem::size_of::<$t>()
};
}
macro_rules! align_of {
($t:ty) => {
::core::mem::align_of::<$t>()
};
}
macro_rules! errno {
($t:expr) => {{
let res = $t;
if res < 0 {
Err(Error::last_os_error())
} else {
Ok(res)
}
}};
}
use crate::IfEvent;
use async_io::Async;
use ipnet::IpNet;
use std::collections::{HashSet, VecDeque};
use std::io::Result;
use std::os::unix::prelude::*;
mod aligned_buffer;
#[cfg(target_os = "linux")]
mod linux;
type Watcher = linux::NetlinkSocket;
#[derive(Debug)]
struct Fd(RawFd);
impl Fd {
pub fn new(fd: RawFd) -> Result<Async<Self>> {
Async::new(Self(fd))
}
}
impl AsRawFd for Fd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Drop for Fd {
fn drop(&mut self) {
unsafe {
libc::close(self.0);
}
}
}
#[derive(Debug)]
pub struct IfWatcher {
addrs: HashSet<IpNet>,
watcher: Watcher,
queue: VecDeque<IfEvent>,
}
impl IfWatcher {
pub async fn new() -> Result<Self> {
let addrs = HashSet::new();
let queue = VecDeque::new();
let mut watcher = Watcher::new()?;
watcher.send_getaddr().await?;
Ok(Self {
addrs,
watcher,
queue,
})
}
pub fn iter(&self) -> impl Iterator<Item = &IpNet> {
self.addrs.iter()
}
pub async fn next(&mut self) -> Result<IfEvent> {
loop {
while let Some(event) = self.queue.pop_front() {
match event {
IfEvent::Up(inet) => {
if self.addrs.insert(inet) {
return Ok(event);
}
}
IfEvent::Down(inet) => {
if self.addrs.remove(&inet) {
return Ok(event);
}
}
}
}
self.watcher.recv_event(&mut self.queue).await?;
}
}
}