-fn start_watcher_thread<F: FnMut(Update) + 'static>(callback: F) -> Result<OwnedFd, Error> {
- let sockfd = socket(AddressFamily::Netlink, SockType::Raw, SockFlag::empty(), Some(SockProtocol::NetlinkRoute))
- .map_err(|_| Error::Internal)?; // TODO: proper errors
- 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 fd = sockfd.as_raw_fd();
- println!("netlink socket on fd {}", fd);
+fn start_watcher_thread<F: FnMut(Update) + Send + 'static>(
+ mut callback: F,
+) -> Result<(OwnedFd, mpsc::Receiver<()>), Error> {
+ let sockfd = socket(
+ AddressFamily::Netlink,
+ SockType::Raw,
+ SockFlag::SOCK_NONBLOCK,
+ Some(SockProtocol::NetlinkRoute),
+ )
+ .map_err(|e| Error::CreateSocket(e.to_string()))?;
+ 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(|e| Error::Bind(e.to_string()))?;
+ let (pipe_rd, pipe_wr) = pipe().map_err(|e| Error::CreatePipe(e.to_string()))?;
+
+ 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;
+ };
+
+ // 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()?);
+
+ let (complete_tx, complete_rx) = mpsc::channel();