]> code.octet-stream.net Git - netwatcher/blob - src/watch_linux.rs
e8e1ffc6350236c4a5a3d96ea8378ea4d280f1de
[netwatcher] / src / watch_linux.rs
1 use std::os::fd::AsRawFd;
2 use std::os::fd::OwnedFd;
3
4 use nix::libc::poll;
5 use nix::libc::pollfd;
6 use nix::libc::POLLIN;
7 use nix::sys::socket::bind;
8 use nix::sys::socket::recv;
9 use nix::sys::socket::socket;
10 use nix::sys::socket::AddressFamily;
11 use nix::sys::socket::MsgFlags;
12 use nix::sys::socket::NetlinkAddr;
13 use nix::sys::socket::SockFlag;
14 use nix::sys::socket::SockProtocol;
15 use nix::sys::socket::SockType;
16 use nix::unistd::pipe;
17
18 use crate::Error;
19 use crate::List;
20 use crate::Update;
21
22 const RTMGRP_IPV4_IFADDR: u32 = 0x10;
23 const RTMGRP_IPV6_IFADDR: u32 = 0x20;
24 const RTMGRP_LINK: u32 = 0x01;
25
26 pub(crate) struct WatchHandle {
27 // Dropping will close the fd which will be detected by poll
28 _pipefd: OwnedFd,
29 }
30
31 pub(crate) fn watch_interfaces<F: FnMut(Update) + Send + 'static>(
32 callback: F,
33 ) -> Result<WatchHandle, Error> {
34 let pipefd = start_watcher_thread(callback)?;
35 Ok(WatchHandle { _pipefd: pipefd })
36 }
37
38 fn start_watcher_thread<F: FnMut(Update) + Send + 'static>(
39 mut callback: F,
40 ) -> Result<OwnedFd, Error> {
41 let sockfd = socket(
42 AddressFamily::Netlink,
43 SockType::Raw,
44 SockFlag::empty(),
45 Some(SockProtocol::NetlinkRoute),
46 )
47 .map_err(|e| Error::CreateSocket(e))?;
48 // TODO: set nonblocking
49 let sa_nl = NetlinkAddr::new(
50 0,
51 (RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR) as u32,
52 );
53 bind(sockfd.as_raw_fd(), &sa_nl).map_err(|e| Error::Bind(e))?;
54 let (pipe_rd, pipe_wr) = pipe().map_err(|e| Error::CreatePipe(e))?;
55
56 let mut prev_list = List::default();
57 let mut handle_update = move |new_list: List| {
58 if new_list == prev_list {
59 return;
60 }
61 let update = Update {
62 interfaces: new_list.0.clone(),
63 diff: new_list.diff_from(&prev_list),
64 };
65 (callback)(update);
66 prev_list = new_list;
67 };
68
69 // Now that netlink socket is open, provide an initial update.
70 // By having this outside the thread we can return an error synchronously if it
71 // looks like we're going to have trouble listing interfaces.
72 handle_update(crate::list::list_interfaces()?);
73
74 std::thread::spawn(move || {
75 let mut buf = [0u8; 4096];
76
77 loop {
78 let mut fds = [
79 pollfd {
80 fd: sockfd.as_raw_fd(),
81 events: POLLIN,
82 revents: 0,
83 },
84 pollfd {
85 fd: pipe_rd.as_raw_fd(),
86 events: POLLIN,
87 revents: 0,
88 },
89 ];
90 unsafe {
91 poll(&mut fds as *mut _, 2, -1);
92 }
93 if fds[0].revents != 0 {
94 // netlink socket had something happen
95 if recv(sockfd.as_raw_fd(), &mut buf, MsgFlags::empty()).is_ok() {
96 let Ok(new_list) = crate::list::list_interfaces() else {
97 continue;
98 };
99 handle_update(new_list);
100 }
101 }
102 if fds[1].revents != 0 {
103 // pipe had something happen
104 break;
105 }
106 }
107 });
108
109 Ok(pipe_wr)
110 }