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