]>
code.octet-stream.net Git - netwatcher/blob - src/watch_linux.rs
dc9957211a698fc4269911e4adf674bfd4f8cfc4
1 use std
::os
::fd
::AsRawFd
;
2 use std
::os
::fd
::OwnedFd
;
8 use nix
::sys
::socket
::bind
;
9 use nix
::sys
::socket
::recv
;
10 use nix
::sys
::socket
::socket
;
11 use nix
::sys
::socket
::AddressFamily
;
12 use nix
::sys
::socket
::MsgFlags
;
13 use nix
::sys
::socket
::NetlinkAddr
;
14 use nix
::sys
::socket
::SockProtocol
;
15 use nix
::sys
::socket
::SockType
;
16 use nix
::sys
::socket
::SOCK_NONBLOCK
;
17 use nix
::unistd
::pipe
;
23 const RTMGRP_IPV4_IFADDR
: u32 = 0x10;
24 const RTMGRP_IPV6_IFADDR
: u32 = 0x20;
25 const RTMGRP_LINK
: u32 = 0x01;
27 pub(crate) struct WatchHandle
{
28 // Close on drop, which will be detected by poll in background thread
29 pipefd
: Option
<OwnedFd
>,
31 // Detect when thread has completed
32 complete
: Option
<mpsc
::Receiver
<()>>,
35 impl Drop
for WatchHandle
{
37 drop(self.pipefd
.take());
38 let _
= self.complete
.take().recv();
42 pub(crate) fn watch_interfaces
<F
: FnMut(Update
) + Send
+ '
static>(
44 ) -> Result
<WatchHandle
, Error
> {
45 let (pipefd
, complete
) = start_watcher_thread(callback
)?
;
48 complete
: Some(complete
),
52 fn start_watcher_thread
<F
: FnMut(Update
) + Send
+ '
static>(
54 ) -> Result
<(OwnedFd
, mpsc
::Receiver
<()>), Error
> {
56 AddressFamily
::Netlink
,
59 Some(SockProtocol
::NetlinkRoute
),
61 .map_err(|e
| Error
::CreateSocket(e
.to_string()))?
;
62 sockfd
.set_nonblocking(true);
63 let sa_nl
= NetlinkAddr
::new(
65 (RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
| RTMGRP_IPV6_IFADDR
) as u32,
67 bind(sockfd
.as_raw_fd(), &sa_nl
).map_err(|e
| Error
::Bind(e
.to_string()))?
;
68 let (pipe_rd
, pipe_wr
) = pipe().map_err(|e
| Error
::CreatePipe(e
.to_string()))?
;
70 let mut prev_list
= List
::default();
71 let mut handle_update
= move |new_list
: List
| {
72 if new_list
== prev_list
{
76 interfaces
: new_list
.0.clone(),
77 diff
: new_list
.diff_from(&prev_list
),
83 // Now that netlink socket is open, provide an initial update.
84 // By having this outside the thread we can return an error synchronously if it
85 // looks like we're going to have trouble listing interfaces.
86 handle_update(crate::list
::list_interfaces()?
);
88 let (complete_tx
, complete_rx
) = mpsc
::channel();
90 std
::thread
::spawn(move || {
91 let mut buf
= [0u8; 4096];
96 fd
: sockfd
.as_raw_fd(),
101 fd
: pipe_rd
.as_raw_fd(),
107 poll(&mut fds
as *mut _
, 2, -1);
109 if fds
[0].revents
!= 0 {
110 // netlink socket had something happen
111 if recv(sockfd
.as_raw_fd(), &mut buf
, MsgFlags
::empty()).is
_ok
() {
112 let Ok(new_list
) = crate::list
::list_interfaces() else {
115 handle_update(new_list
);
118 if fds
[1].revents
!= 0 {
119 // pipe had something happen