sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use super::*;

impl SystemInner {
    pub(crate) fn uptime() -> Result<u64, Error> {
        unsafe {
            let csec = libc::time(::std::ptr::null_mut());

            Ok(libc::difftime(csec, Self::boot_time()? as _) as _)
        }
    }

    pub(crate) fn load_average() -> Result<LoadAvg, Error> {
        let mut loads = vec![0f64; 3];

        unsafe {
            if libc::getloadavg(loads.as_mut_ptr(), 3) == -1 {
                Err(Error::from("getloadavg failed"))
            } else {
                Ok(LoadAvg {
                    one: loads[0],
                    five: loads[1],
                    fifteen: loads[2],
                })
            }
        }
    }

    pub(crate) fn boot_time() -> Result<u64, Error> {
        boot_time()
    }

    pub(crate) fn name() -> Result<String, Error> {
        match get_system_info(libc::KERN_OSTYPE) {
            Some(v) => Ok(v),
            None => Ok("Darwin".to_owned()),
        }
    }

    pub(crate) fn long_os_version() -> Result<String, Error> {
        #[cfg(target_os = "macos")]
        {
            let Ok(os_version) = Self::os_version() else {
                return Ok("macOS".to_owned());
            };
            // https://en.wikipedia.org/wiki/MacOS_version_history
            for (version_prefix, macos_spelling, friendly_name) in [
                ("26", "macOS", "Tahoe"),
                ("15", "macOS", "Sequoia"),
                ("14", "macOS", "Sonoma"),
                ("13", "macOS", "Ventura"),
                ("12", "macOS", "Monterey"),
                ("11", "macOS", "Big Sur"),
                // Big Sur identifies itself as 10.16 in some situations.
                ("10.16", "macOS", "Big Sur"),
                ("10.15", "macOS", "Catalina"),
                ("10.14", "macOS", "Mojave"),
                ("10.13", "macOS", "High Sierra"),
                ("10.12", "macOS", "Sierra"),
                ("10.11", "OS X", "El Capitan"),
                ("10.10", "OS X", "Yosemite"),
                ("10.9", "OS X", "Mavericks"),
                ("10.8", "OS X", "Mountain Lion"),
                ("10.7", "Mac OS X", "Lion"),
                ("10.6", "Mac OS X", "Snow Leopard"),
                ("10.5", "Mac OS X", "Leopard"),
                ("10.4", "Mac OS X", "Tiger"),
                ("10.3", "Mac OS X", "Panther"),
                ("10.2", "Mac OS X", "Jaguar"),
                ("10.1", "Mac OS X", "Puma"),
                ("10.0", "Mac OS X", "Cheetah"),
            ] {
                if os_version.starts_with(version_prefix) {
                    return Ok(format!("{macos_spelling} {os_version} {friendly_name}"));
                }
            }
            Ok(format!("macOS {os_version}"))
        }

        #[cfg(target_os = "ios")]
        {
            let mut long_name = "iOS".to_owned();
            if let Ok(os_version) = Self::os_version() {
                long_name.push(' ');
                long_name.push_str(&os_version);
            }
            Ok(long_name)
        }
    }

    pub(crate) fn host_name() -> Result<String, Error> {
        get_system_info(libc::KERN_HOSTNAME)
            .ok_or_else(|| Error::Other("failed to retrieve host name".into()))
    }

    pub(crate) fn kernel_version() -> Result<String, Error> {
        get_system_info(libc::KERN_OSRELEASE)
            .ok_or_else(|| Error::Other("failed to retrieve kernel version".into()))
    }

    pub(crate) fn os_version() -> Result<String, Error> {
        unsafe {
            // First retrieve the buffer size.
            let mut size = 0;
            if get_sys_value_by_name(b"kern.osproductversion\0", &mut size, std::ptr::null_mut())
                && size > 0
            {
                // Create a buffer with the size obtained above and read the real value.
                let mut buf = vec![0_u8; size as _];

                if get_sys_value_by_name(
                    b"kern.osproductversion\0",
                    &mut size,
                    buf.as_mut_ptr() as *mut c_void,
                ) {
                    if let Some(pos) = buf.iter().position(|x| *x == 0) {
                        // Shrink the buffer to the null terminator.
                        buf.resize(pos, 0);
                    }

                    if let Ok(value) = String::from_utf8(buf) {
                        return Ok(value);
                    }
                }
            }
            Err(Error::Other("failed to retrieve OS version".into()))
        }
    }

    pub(crate) fn distribution_id() -> String {
        std::env::consts::OS.to_owned()
    }

    pub(crate) fn distribution_id_like() -> Vec<String> {
        Vec::new()
    }

    pub(crate) fn kernel_name() -> Option<&'static str> {
        Some("Darwin")
    }

    pub(crate) fn cpu_arch() -> Option<String> {
        let mut arch_str: [u8; 32] = [0; 32];
        let mut mib = [libc::CTL_HW as _, libc::HW_MACHINE as _];

        unsafe {
            if get_sys_value(
                mem::size_of::<[u8; 32]>(),
                arch_str.as_mut_ptr() as *mut _,
                &mut mib,
            ) {
                CStr::from_bytes_until_nul(&arch_str)
                    .ok()
                    .and_then(|res| match res.to_str() {
                        Ok(arch) => Some(arch.to_string()),
                        Err(_) => None,
                    })
            } else {
                None
            }
        }
    }

    pub(crate) fn physical_core_count() -> Result<usize, Error> {
        let mut physical_core_count = 0;

        unsafe {
            if get_sys_value_by_name(
                b"hw.physicalcpu\0",
                &mut mem::size_of::<u32>(),
                &mut physical_core_count as *mut usize as *mut c_void,
            ) {
                Ok(physical_core_count)
            } else {
                Err(Error::Other(
                    "failed to retrieve physical core count".into(),
                ))
            }
        }
    }

    // Comment in the XNU source: https://github.com/apple-oss-distributions/xnu/blob/main/bsd/kern/kern_resource.c#L1643
    pub(crate) fn open_files_limit() -> Result<usize, Error> {
        let rlim_cur = unsafe {
            getrlimit()
                .ok_or(Error::Other("failed to retrieve open files limit".into()))?
                .rlim_cur
        };

        let mut maxfilesperproc: c_int = 0;
        let mut len = std::mem::size_of::<c_int>();
        let ret = unsafe {
            get_sys_value_by_name(
                b"kern.maxfilesperproc\0",
                &mut len,
                &mut maxfilesperproc as *mut _ as *mut c_void,
            )
        };

        if ret && maxfilesperproc >= 0 {
            Ok(std::cmp::min(rlim_cur as usize, maxfilesperproc as usize))
        } else {
            Err(Error::Other("failed to retrieve open files limit".into()))
        }
    }
}