]>
code.octet-stream.net Git - netwatcher/blob - src/watch_linux.rs
e5842117994da2f0951bb66a5b1cc31e43ab86e2
1 use std
::os
::fd
::AsRawFd
;
2 use std
::os
::fd
::OwnedFd
;
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
;
25 pub(crate) struct WatchHandle
{
26 // Dropping will close the fd which will be detected by poll
30 pub(crate) fn watch_interfaces
<F
: FnMut(Update
) + Send
+ '
static>(
32 ) -> Result
<WatchHandle
, Error
> {
33 let pipefd
= start_watcher_thread(callback
)?
;
34 Ok(WatchHandle
{ _pipefd
: pipefd
})
37 fn start_watcher_thread
<F
: FnMut(Update
) + Send
+ '
static>(
39 ) -> Result
<OwnedFd
, Error
> {
41 AddressFamily
::Netlink
,
44 Some(SockProtocol
::NetlinkRoute
),
46 .map_err(|_
| Error
::Internal
)?
; // TODO: proper errors
47 let sa_nl
= NetlinkAddr
::new(
49 (RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
| RTMGRP_IPV6_IFADDR
) as u32,
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
)?
;
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
{
62 interfaces
: new_list
.0.clone(),
63 diff
: new_list
.diff_from(&prev_list
),
69 if let Ok(initial
) = crate::list
::list_interfaces() {
70 handle_update(initial
);
76 fd
: sockfd
.as_raw_fd(),
81 fd
: pipe_rd
.as_raw_fd(),
87 poll(&mut fds
as *mut _
, 2, -1);
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 {
95 handle_update(new_list
);
98 if fds
[1].revents
!= 0 {
99 // pipe had something happen