]>
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(|e
| Error
::CreateSocket(e
.to_string()))?
; 
  48     sockfd
.set_nonblocking(true); 
  49     let sa_nl 
= NetlinkAddr
::new( 
  51         (RTMGRP_LINK 
| RTMGRP_IPV4_IFADDR 
| RTMGRP_IPV6_IFADDR
) as u32, 
  53     bind(sockfd
.as_raw_fd(), &sa_nl
).map_err(|e
| Error
::Bind(e
.to_string()))?
; 
  54     let (pipe_rd
, pipe_wr
) = pipe().map_err(|e
| Error
::CreatePipe(e
.to_string()))?
; 
  56     let mut prev_list 
= List
::default(); 
  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     // Now that netlink socket is open, provide an initial update. 
  70     // By having this outside the thread we can return an error synchronously if it 
  71     // looks like we're going to have trouble listing interfaces. 
  72     handle_update(crate::list
::list_interfaces()?
); 
  74     std
::thread
::spawn(move || { 
  75         let mut buf 
= [0u8; 4096]; 
  80                     fd
: sockfd
.as_raw_fd(), 
  85                     fd
: pipe_rd
.as_raw_fd(), 
  91                 poll(&mut fds 
as *mut _
, 2, -1); 
  93             if fds
[0].revents 
!= 0 { 
  94                 // netlink socket had something happen 
  95                 if recv(sockfd
.as_raw_fd(), &mut buf
, MsgFlags
::empty()).is
_ok
() { 
  96                     let Ok(new_list
) = crate::list
::list_interfaces() else { 
  99                     handle_update(new_list
); 
 102             if fds
[1].revents 
!= 0 { 
 103                 // pipe had something happen