]> code.octet-stream.net Git - netwatcher/blob - src/watch_linux.rs
Support for cancelling linux watch
[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::libc::RTMGRP_IPV4_IFADDR;
8 use nix::libc::RTMGRP_IPV6_IFADDR;
9 use nix::libc::RTMGRP_LINK;
10 use nix::sys::socket::bind;
11 use nix::sys::socket::recv;
12 use nix::sys::socket::socket;
13 use nix::sys::socket::AddressFamily;
14 use nix::sys::socket::MsgFlags;
15 use nix::sys::socket::NetlinkAddr;
16 use nix::sys::socket::SockFlag;
17 use nix::sys::socket::SockProtocol;
18 use nix::sys::socket::SockType;
19 use nix::unistd::pipe;
20
21 use crate::Error;
22 use crate::List;
23 use crate::Update;
24
25 pub(crate) struct WatchHandle {
26 // Dropping will close the fd which will be detected by poll
27 _pipefd: OwnedFd,
28 }
29
30 pub(crate) fn watch_interfaces<F: FnMut(Update) + Send + 'static>(
31 callback: F,
32 ) -> Result<WatchHandle, Error> {
33 let pipefd = start_watcher_thread(callback)?;
34 Ok(WatchHandle { _pipefd: pipefd })
35 }
36
37 fn start_watcher_thread<F: FnMut(Update) + Send + 'static>(
38 mut callback: F,
39 ) -> Result<OwnedFd, Error> {
40 let sockfd = socket(
41 AddressFamily::Netlink,
42 SockType::Raw,
43 SockFlag::empty(),
44 Some(SockProtocol::NetlinkRoute),
45 )
46 .map_err(|_| Error::Internal)?; // TODO: proper errors
47 let sa_nl = NetlinkAddr::new(
48 0,
49 (RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR) as u32,
50 );
51 bind(sockfd.as_raw_fd(), &sa_nl).map_err(|_| Error::Internal)?; // TODO: proper errors
52 let (pipe_rd, pipe_wr) = pipe().map_err(|_| Error::Internal)?;
53
54 std::thread::spawn(move || {
55 let mut prev_list = List::default();
56 let mut buf = [0u8; 4096];
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 if let Ok(initial) = crate::list::list_interfaces() {
70 handle_update(initial);
71 };
72
73 loop {
74 let mut fds = [
75 pollfd {
76 fd: sockfd.as_raw_fd(),
77 events: POLLIN,
78 revents: 0,
79 },
80 pollfd {
81 fd: pipe_rd.as_raw_fd(),
82 events: POLLIN,
83 revents: 0,
84 },
85 ];
86 unsafe {
87 poll(&mut fds as *mut _, 2, -1);
88 }
89 if fds[0].revents != 0 {
90 // netlink socket had something happen
91 if recv(sockfd.as_raw_fd(), &mut buf, MsgFlags::empty()).is_ok() {
92 let Ok(new_list) = crate::list::list_interfaces() else {
93 continue;
94 };
95 handle_update(new_list);
96 }
97 }
98 if fds[1].revents != 0 {
99 // pipe had something happen
100 break;
101 }
102 }
103 });
104
105 Ok(pipe_wr)
106 }