sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::collections::HashMap;
use std::collections::HashSet;
use std::ffi::{CStr, OsString};
use std::marker::PhantomData;
use std::net::IpAddr;
use std::os::raw::c_char;
use std::os::unix::ffi::OsStringExt;
use std::ptr::null_mut;

use crate::{IpNetwork, MacAddr};

/// Yields an interface name and address.
pub(crate) struct InterfaceAddress {
    /// Pointer to the first element of the linked list.
    buf: *mut libc::ifaddrs,
}

impl Drop for InterfaceAddress {
    fn drop(&mut self) {
        // Safety: `buf` is never NULL when this struct is constructed.
        unsafe {
            libc::freeifaddrs(self.buf);
        }
    }
}

impl InterfaceAddress {
    pub(crate) fn new() -> Option<Self> {
        let mut ifap = null_mut();
        if unsafe { retry_eintr!(libc::getifaddrs(&mut ifap)) } == 0 && !ifap.is_null() {
            Some(Self { buf: ifap })
        } else {
            sinf_debug!("`getifaddrs` failed");
            None
        }
    }

    pub(crate) fn iter(&self) -> InterfaceAddressIterator<'_> {
        InterfaceAddressIterator {
            ifap: self.buf,
            _phantom: PhantomData,
        }
    }
}

pub(crate) struct InterfaceAddressIterator<'a> {
    ifap: *mut libc::ifaddrs,
    _phantom: PhantomData<&'a ()>,
}

pub(crate) struct InterfaceAddressHelper {
    ifap: *mut libc::ifaddrs,
}

impl InterfaceAddressHelper {
    pub(crate) fn name(&self) -> Option<OsString> {
        // Safety: `addr` is valid for the lifetime of this body and is not mutated.
        let addr_ref: &libc::ifaddrs = unsafe { &*self.ifap };

        let c_str = addr_ref.ifa_name as *const c_char;

        // Safety: `ifa_name` is a NUL-terminated interface name.
        let bytes = unsafe { CStr::from_ptr(c_str).to_bytes() };
        // Interface names may carry the form `<interface name>:<sub-interface index>`.
        let bytes = if let Some(pos) = bytes.iter().rposition(|b| *b == b':') {
            bytes[..pos].to_owned()
        } else {
            bytes.to_owned()
        };
        if bytes.is_empty() {
            None
        } else {
            Some(OsString::from_vec(bytes))
        }
    }

    pub(crate) fn ip(&self) -> Option<IpAddr> {
        // Safety: `addr` is valid for the lifetime of this body and is not mutated.
        let addr_ref: &libc::ifaddrs = unsafe { &*self.ifap };

        sockaddr_to_network_addr(addr_ref.ifa_addr as *const libc::sockaddr)
    }

    pub(crate) fn prefix(&self) -> u8 {
        // Safety: `addr` is valid for the lifetime of this body and is not mutated.
        let addr_ref: &libc::ifaddrs = unsafe { &*self.ifap };
        let netmask = sockaddr_to_network_addr(addr_ref.ifa_netmask as *const libc::sockaddr);
        netmask
            .and_then(|netmask| ip_mask_to_prefix(netmask).ok())
            .unwrap_or(0)
    }

    pub(crate) fn mac_addr(&self) -> Option<MacAddr> {
        // Safety: `addr` is valid for the lifetime of this body and is not mutated.
        let addr_ref: &libc::ifaddrs = unsafe { &*self.ifap };
        unsafe { parse_interface_address(addr_ref) }
    }
}

impl<'a> Iterator for InterfaceAddressIterator<'a> {
    type Item = InterfaceAddressHelper;

    fn next(&mut self) -> Option<Self::Item> {
        if self.ifap.is_null() {
            return None;
        }
        let ifap = self.ifap;
        // Safety: `ifap` is non-null and points into the active `ifaddrs` list.
        self.ifap = unsafe { (*ifap).ifa_next };
        Some(InterfaceAddressHelper { ifap })
    }
}

#[cfg(any(
    target_os = "macos",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "ios"
))]
impl From<&libc::sockaddr_dl> for MacAddr {
    fn from(value: &libc::sockaddr_dl) -> Self {
        let sdl_data = value.sdl_data;
        // Interface name length, without a trailing NUL.
        let sdl_nlen = value.sdl_nlen as usize;
        // Guard against reading out of bounds.
        if sdl_nlen + 5 < 12 {
            MacAddr([
                sdl_data[sdl_nlen] as u8,
                sdl_data[sdl_nlen + 1] as u8,
                sdl_data[sdl_nlen + 2] as u8,
                sdl_data[sdl_nlen + 3] as u8,
                sdl_data[sdl_nlen + 4] as u8,
                sdl_data[sdl_nlen + 5] as u8,
            ])
        } else {
            MacAddr::UNSPECIFIED
        }
    }
}

#[cfg(any(
    target_os = "macos",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "ios"
))]
unsafe fn parse_interface_address(ifap: &libc::ifaddrs) -> Option<MacAddr> {
    let sock_addr = ifap.ifa_addr;
    if sock_addr.is_null() {
        return None;
    }
    unsafe {
        match (*sock_addr).sa_family as libc::c_int {
            libc::AF_LINK => {
                let addr = sock_addr as *const libc::sockaddr_dl;
                Some(MacAddr::from(&*addr))
            }
            _ => None,
        }
    }
}

#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn parse_interface_address(ifap: &libc::ifaddrs) -> Option<MacAddr> {
    use libc::sockaddr_ll;

    let sock_addr = ifap.ifa_addr;
    if sock_addr.is_null() {
        return None;
    }
    unsafe {
        match (*sock_addr).sa_family as libc::c_int {
            libc::AF_PACKET => {
                let addr = sock_addr as *const sockaddr_ll;
                // Take the first six bytes.
                let [addr @ .., _, _] = (*addr).sll_addr;
                Some(MacAddr(addr))
            }
            _ => None,
        }
    }
}

pub(crate) fn refresh_network_interfaces(interfaces: &mut HashMap<OsString, crate::NetworkData>) {
    let Some(interface_iter) = InterfaceAddress::new() else {
        return;
    };
    let mut ifaces: HashMap<OsString, HashSet<IpNetwork>> = HashMap::new();

    for entry in interface_iter.iter() {
        if let Some(interface_name) = entry.name()
            // Do work only when the existing interfaces contain this one.
            && let Some(interface) = interfaces.get_mut(&interface_name)
        {
            if let Some(mac_addr) = entry.mac_addr() {
                interface.inner.mac_addr = mac_addr;
            }
            if let Some(ip) = entry.ip() {
                let prefix = entry.prefix();
                ifaces
                    .entry(interface_name)
                    .and_modify(|values| {
                        values.insert(IpNetwork { addr: ip, prefix });
                    })
                    .or_insert(HashSet::from([IpNetwork { addr: ip, prefix }]));
            }
        }
    }

    for (interface_name, ip_networks) in ifaces {
        if let Some(interface) = interfaces.get_mut(&interface_name) {
            interface.inner.ip_networks = ip_networks.into_iter().collect::<Vec<_>>();
        }
    }
}

pub(crate) mod address;

use self::address::{ip_mask_to_prefix, sockaddr_to_network_addr};