]> code.octet-stream.net Git - netwatcher/blob - src/watch_linux.rs
Commit to reporting error if original interface listing fails
[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 let mut prev_list = List::default();
55 let mut handle_update = move |new_list: List| {
56 if new_list == prev_list {
57 return;
58 }
59 let update = Update {
60 interfaces: new_list.0.clone(),
61 diff: new_list.diff_from(&prev_list),
62 };
63 (callback)(update);
64 prev_list = new_list;
65 };
66
67 // Now that netlink socket is open, provide an initial update.
68 // By having this outside the thread we can return an error synchronously if it
69 // looks like we're going to have trouble listing interfaces.
70 handle_update(crate::list::list_interfaces()?);
71
72 std::thread::spawn(move || {
73 let mut buf = [0u8; 4096];
74
75 loop {
76 let mut fds = [
77 pollfd {
78 fd: sockfd.as_raw_fd(),
79 events: POLLIN,
80 revents: 0,
81 },
82 pollfd {
83 fd: pipe_rd.as_raw_fd(),
84 events: POLLIN,
85 revents: 0,
86 },
87 ];
88 unsafe {
89 poll(&mut fds as *mut _, 2, -1);
90 }
91 if fds[0].revents != 0 {
92 // netlink socket had something happen
93 if recv(sockfd.as_raw_fd(), &mut buf, MsgFlags::empty()).is_ok() {
94 let Ok(new_list) = crate::list::list_interfaces() else {
95 continue;
96 };
97 handle_update(new_list);
98 }
99 }
100 if fds[1].revents != 0 {
101 // pipe had something happen
102 break;
103 }
104 }
105 });
106
107 Ok(pipe_wr)
108 }