sysinfolinux 0.1.0

Library to get system information such as processes, CPUs, disks, components and networks on Linux
// Take a look at the license at the top of the repository in the LICENSE file.

#[cfg(any(feature = "disk", feature = "system"))]
use std::fs::File;
#[cfg(any(feature = "disk", feature = "system"))]
use std::io::{self, Read, Seek};
#[cfg(any(feature = "disk", feature = "system"))]
use std::path::Path;

#[cfg(feature = "system")]
pub(crate) fn get_all_data_from_file(file: &mut File, size: usize) -> io::Result<Vec<u8>> {
    let mut buf = Vec::with_capacity(size);
    file.rewind()?;
    file.read_to_end(&mut buf)?;
    Ok(buf)
}

#[cfg(any(feature = "disk", feature = "system"))]
pub(crate) fn get_all_utf8_data_from_file(file: &mut File, size: usize) -> io::Result<String> {
    let mut buf = String::with_capacity(size);
    file.rewind()?;
    file.read_to_string(&mut buf)?;
    Ok(buf)
}

#[cfg(any(feature = "disk", feature = "system"))]
pub(crate) fn get_all_utf8_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Result<String> {
    let mut file = File::open(file_path.as_ref())?;
    get_all_utf8_data_from_file(&mut file, size)
}

/// This type is used in `retrieve_all_new_process_info` because we have a "parent" path and
/// from it, we `pop`/`join` every time because it's more memory efficient than using `Path::join`.
#[cfg(feature = "system")]
pub(crate) struct PathHandler(std::path::PathBuf);

#[cfg(feature = "system")]
impl PathHandler {
    pub(crate) fn new<P: AsRef<Path>>(path: P) -> Self {
        // `path` is the "parent" for all paths which will follow so we add a fake element at
        // the end since every `PathHandler::replace_and_join` call will first call `pop`
        // internally.
        Self(path.as_ref().join("a"))
    }

    pub(crate) fn as_path(&self) -> &Path {
        &self.0
    }
}

#[cfg(feature = "system")]
pub(crate) trait PathPush {
    fn replace_and_join(&mut self, p: &str) -> &Path;
}

#[cfg(feature = "system")]
impl PathPush for PathHandler {
    fn replace_and_join(&mut self, p: &str) -> &Path {
        self.0.pop();
        self.0.push(p);
        self.as_path()
    }
}

// This implementation allows to skip one allocation that is done in `PathHandler`.
#[cfg(feature = "system")]
impl PathPush for std::path::PathBuf {
    fn replace_and_join(&mut self, p: &str) -> &Path {
        self.push(p);
        self.as_path()
    }
}

#[cfg(feature = "system")]
pub(crate) fn to_u64(v: &[u8]) -> u64 {
    let mut x = 0;

    for c in v {
        x *= 10;
        x += u64::from(c - b'0');
    }
    x
}

/// Converts a path to a NUL-terminated `Vec<u8>` suitable for use with C functions.
#[cfg(feature = "disk")]
pub(crate) fn to_cpath(path: &std::path::Path) -> Vec<u8> {
    use std::{ffi::OsStr, os::unix::ffi::OsStrExt};

    let path_os: &OsStr = path.as_ref();
    let mut cpath = path_os.as_bytes().to_vec();
    cpath.push(0);
    cpath
}

#[cfg(feature = "user")]
pub(crate) fn cstr_to_rust(c: *const libc::c_char) -> Option<String> {
    cstr_to_rust_with_size(c, None)
}

#[cfg(any(feature = "disk", feature = "system", feature = "user"))]
#[allow(dead_code)]
pub(crate) fn cstr_to_rust_with_size(
    c: *const libc::c_char,
    size: Option<usize>,
) -> Option<String> {
    if c.is_null() {
        return None;
    }
    let (mut s, max) = match size {
        Some(len) => (Vec::with_capacity(len), len as isize),
        None => (Vec::new(), isize::MAX),
    };
    let mut i = 0;
    unsafe {
        loop {
            let value = *c.offset(i) as u8;
            if value == 0 {
                break;
            }
            s.push(value);
            i += 1;
            if i >= max {
                break;
            }
        }
        String::from_utf8(s).ok()
    }
}

#[cfg(feature = "system")]
pub(crate) fn wait_process(pid: crate::Pid) -> Option<std::process::ExitStatus> {
    use std::os::unix::process::ExitStatusExt;

    let mut status = 0;
    // attempt waiting
    unsafe {
        if retry_eintr!(libc::waitpid(pid.0, &mut status, 0)) < 0 {
            // attempt failed (non-child process) so loop until process ends
            let duration = std::time::Duration::from_millis(10);
            while libc::kill(pid.0, 0) == 0 {
                std::thread::sleep(duration);
            }
        }
        Some(std::process::ExitStatus::from_raw(status))
    }
}

#[cfg(feature = "system")]
#[allow(clippy::useless_conversion)]
pub(crate) fn realpath<P: AsRef<std::path::Path>>(path: P) -> Option<std::path::PathBuf> {
    let path = path.as_ref();
    match std::fs::read_link(path) {
        Ok(path) => Some(path),
        Err(_e) => {
            sysinfo_debug!("failed to get real path for {:?}: {:?}", path, _e);
            None
        }
    }
}