use nix::libc::poll;
use nix::libc::pollfd;
use nix::libc::POLLIN;
-use nix::libc::RTMGRP_IPV4_IFADDR;
-use nix::libc::RTMGRP_IPV6_IFADDR;
-use nix::libc::RTMGRP_LINK;
use nix::sys::socket::bind;
use nix::sys::socket::recv;
use nix::sys::socket::socket;
use crate::List;
use crate::Update;
+const RTMGRP_IPV4_IFADDR: u32 = 0x10;
+const RTMGRP_IPV6_IFADDR: u32 = 0x20;
+const RTMGRP_LINK: u32 = 0x01;
+
pub(crate) struct WatchHandle {
// Dropping will close the fd which will be detected by poll
_pipefd: OwnedFd,
SockFlag::empty(),
Some(SockProtocol::NetlinkRoute),
)
- .map_err(|_| Error::Internal)?; // TODO: proper errors
+ .map_err(|e| Error::CreateSocket(e))?;
+ // TODO: set nonblocking
let sa_nl = NetlinkAddr::new(
0,
(RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR) as u32,
);
- bind(sockfd.as_raw_fd(), &sa_nl).map_err(|_| Error::Internal)?; // TODO: proper errors
- let (pipe_rd, pipe_wr) = pipe().map_err(|_| Error::Internal)?;
+ bind(sockfd.as_raw_fd(), &sa_nl).map_err(|e| Error::Bind(e))?;
+ let (pipe_rd, pipe_wr) = pipe().map_err(|e| Error::CreatePipe(e))?;
- std::thread::spawn(move || {
- let mut prev_list = List::default();
- let mut buf = [0u8; 4096];
- let mut handle_update = move |new_list: List| {
- if new_list == prev_list {
- return;
- }
- let update = Update {
- interfaces: new_list.0.clone(),
- diff: new_list.diff_from(&prev_list),
- };
- (callback)(update);
- prev_list = new_list;
+ let mut prev_list = List::default();
+ let mut handle_update = move |new_list: List| {
+ if new_list == prev_list {
+ return;
+ }
+ let update = Update {
+ interfaces: new_list.0.clone(),
+ diff: new_list.diff_from(&prev_list),
};
+ (callback)(update);
+ prev_list = new_list;
+ };
- if let Ok(initial) = crate::list::list_interfaces() {
- handle_update(initial);
- };
+ // Now that netlink socket is open, provide an initial update.
+ // By having this outside the thread we can return an error synchronously if it
+ // looks like we're going to have trouble listing interfaces.
+ handle_update(crate::list::list_interfaces()?);
+
+ std::thread::spawn(move || {
+ let mut buf = [0u8; 4096];
loop {
let mut fds = [