]>
code.octet-stream.net Git - netwatcher/blob - src/watch_linux.rs
1 use std
::os
::fd
::AsRawFd
;
2 use std
::os
::fd
::OwnedFd
;
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
;
22 const RTMGRP_IPV4_IFADDR
: u32 = 0x10;
23 const RTMGRP_IPV6_IFADDR
: u32 = 0x20;
24 const RTMGRP_LINK
: u32 = 0x01;
26 pub(crate) struct WatchHandle
{
27 // Dropping will close the fd which will be detected by poll
31 pub(crate) fn watch_interfaces
<F
: FnMut(Update
) + Send
+ '
static>(
33 ) -> Result
<WatchHandle
, Error
> {
34 let pipefd
= start_watcher_thread(callback
)?
;
35 Ok(WatchHandle
{ _pipefd
: pipefd
})
38 fn start_watcher_thread
<F
: FnMut(Update
) + Send
+ '
static>(
40 ) -> Result
<OwnedFd
, Error
> {
42 AddressFamily
::Netlink
,
45 Some(SockProtocol
::NetlinkRoute
),
47 .map_err(|_
| Error
::Internal
)?
; // TODO: proper errors
48 let sa_nl
= NetlinkAddr
::new(
50 (RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
| RTMGRP_IPV6_IFADDR
) as u32,
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
)?
;
55 let mut prev_list
= List
::default();
56 let mut handle_update
= move |new_list
: List
| {
57 if new_list
== prev_list
{
61 interfaces
: new_list
.0.clone(),
62 diff
: new_list
.diff_from(&prev_list
),
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()?
);
73 std
::thread
::spawn(move || {
74 let mut buf
= [0u8; 4096];
79 fd
: sockfd
.as_raw_fd(),
84 fd
: pipe_rd
.as_raw_fd(),
90 poll(&mut fds
as *mut _
, 2, -1);
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 {
98 handle_update(new_list
);
101 if fds
[1].revents
!= 0 {
102 // pipe had something happen