]>
code.octet-stream.net Git - netwatcher/blob - src/watch_linux.rs
95ef10638e5c5551ee9743106508031ca0462c6f
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 let mut prev_list
= List
::default();
55 let mut handle_update
= move |new_list
: List
| {
56 if new_list
== prev_list
{
60 interfaces
: new_list
.0.clone(),
61 diff
: new_list
.diff_from(&prev_list
),
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()?
);
72 std
::thread
::spawn(move || {
73 let mut buf
= [0u8; 4096];
78 fd
: sockfd
.as_raw_fd(),
83 fd
: pipe_rd
.as_raw_fd(),
89 poll(&mut fds
as *mut _
, 2, -1);
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 {
97 handle_update(new_list
);
100 if fds
[1].revents
!= 0 {
101 // pipe had something happen