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::ffi::{CStr, OsString};
use std::os::unix::ffi::OsStringExt;

use crate::network::refresh_networks_addresses;
use crate::platform::bsd::network::remove_stale;
use crate::platform::network_data::{NetworkDataInner, NetworkSnapshot};
use crate::{Error, InterfaceOperationalState, NetworkData};

pub(crate) struct NetworksInner {
    pub(crate) interfaces: HashMap<OsString, NetworkData>,
}

impl NetworksInner {
    pub(crate) fn new() -> Result<Self, Error> {
        Ok(Self {
            interfaces: HashMap::new(),
        })
    }

    pub(crate) fn list(&self) -> &HashMap<OsString, NetworkData> {
        &self.interfaces
    }

    pub(crate) fn refresh(&mut self, remove_not_listed_interfaces: bool) {
        unsafe {
            refresh_interfaces(&mut self.interfaces);
        }
        remove_stale(&mut self.interfaces, remove_not_listed_interfaces);
        refresh_networks_addresses(&mut self.interfaces);
    }
}

unsafe fn refresh_interfaces(interfaces: &mut HashMap<OsString, NetworkData>) {
    unsafe {
        let Some(ifaddrs) = InterfaceAddressIterator::new() else {
            sinf_debug!("getifaddrs failed");
            return;
        };

        for ifa in ifaddrs {
            let ifa = &*ifa;
            if ifa.ifa_name.is_null() {
                continue;
            }
            // SAFETY: `ifa_name` is null-terminated.
            let bytes = CStr::from_ptr(ifa.ifa_name).to_bytes();
            let name = OsString::from_vec(bytes.to_owned());
            let flags = ifa.ifa_flags;
            let data: &libc::if_data = &*(ifa.ifa_data as *mut libc::if_data);
            let mtu = data.ifi_mtu;
            let baudrate = data.ifi_baudrate;
            let link_speed = (baudrate != 0).then_some(baudrate);
            let operational_state = InterfaceOperationalState::from_flag(
                flags as core::ffi::c_int,
                data.ifi_link_state,
            );
            let snapshot = NetworkSnapshot::new(
                data.ifi_ibytes,
                data.ifi_obytes,
                data.ifi_ipackets,
                data.ifi_opackets,
                data.ifi_ierrors,
                data.ifi_oerrors,
            );

            match interfaces.entry(name) {
                std::collections::hash_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().inner.update(
                        snapshot,
                        mtu,
                        link_speed,
                        link_speed,
                        operational_state,
                    );
                }
                std::collections::hash_map::Entry::Vacant(entry) => {
                    entry.insert(NetworkData {
                        inner: NetworkDataInner::new_with_zero_history(
                            snapshot,
                            mtu,
                            link_speed,
                            link_speed,
                            operational_state,
                        ),
                    });
                }
            }
        }
    }
}

struct InterfaceAddressIterator {
    /// Pointer to the current `ifaddrs` struct.
    ifap: *mut libc::ifaddrs,
    /// Pointer to the first element in the linked list.
    buf: *mut libc::ifaddrs,
}

impl InterfaceAddressIterator {
    fn new() -> Option<Self> {
        let mut ifap = std::ptr::null_mut();
        if unsafe { retry_eintr!(libc::getifaddrs(&mut ifap)) } == 0 && !ifap.is_null() {
            Some(Self { ifap, buf: ifap })
        } else {
            None
        }
    }
}

impl Iterator for InterfaceAddressIterator {
    type Item = *mut libc::ifaddrs;

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            while !self.ifap.is_null() {
                let ifap = self.ifap;
                let ifa = &*ifap;
                self.ifap = ifa.ifa_next;

                if ifa.ifa_addr.is_null()
                    || (*ifa.ifa_addr).sa_family as libc::c_int != libc::AF_LINK
                    || ifa.ifa_flags & libc::IFF_LOOPBACK as libc::c_uint != 0
                {
                    continue;
                }
                return Some(ifap);
            }
            None
        }
    }
}

impl Drop for InterfaceAddressIterator {
    fn drop(&mut self) {
        unsafe {
            libc::freeifaddrs(self.buf);
        }
    }
}