1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use std::boxed::Box;
use std::error::Error;

/// Struct representing uname
///
/// Based on the [utsname](https://www.gnu.org/software/libc/manual/html_node/Platform-Type.html#Platform-Type) struct in GNU libc
#[derive(Debug)]
pub struct UtsName {
    /// The name of the operating system in use.
    pub sysname: String,

    /// The current release level of the operating system implementation.
    pub release: String,

    /// The current version level within the release of the operating system.
    pub version: String,

    /// The description of the type of hardware that is in use.
    pub machine: String,

    /// The host name of this particular computer.
    ///
    /// Returns the same value as the `hostname` command on the command line.
    pub nodename: String,

    /// The NIS or YP domain name.
    pub domainname: String,
}

/// Represents an error when creating an instance of UtsName
#[derive(Debug)]
pub struct UnameError;

impl std::fmt::Display for UnameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid uname.")
    }
}

impl Error for UnameError {
    fn description(&self) -> &str {
        "Error initializing UtsName (EFAULT)."
    }
}

impl UtsName {
    /// Initializes UtsName with the fields populated.
    ///
    /// Returns an instance of UtsName if successful and an Error object if failed.
    ///
    /// # Examples
    /// ```
    /// assert!(rpsutil::system::UtsName::new().is_ok())
    /// ```
    pub fn new() -> Result<UtsName, Box<Error>> {
        let b_utsname: Box<libc::utsname>;
        let code: libc::c_int;

        unsafe {
            let r_utsname = Box::into_raw(Box::new(Self::c_utsname()));
            code = libc::uname(r_utsname);

            if code != 0 {
                return Err(Box::new(UnameError));
            }

            b_utsname = Box::from_raw(r_utsname);
        }

        Ok(UtsName {
            sysname: Self::char_ary_to_string(&b_utsname.sysname)?,
            release: Self::char_ary_to_string(&b_utsname.release)?,
            version: Self::char_ary_to_string(&b_utsname.version)?,
            machine: Self::char_ary_to_string(&b_utsname.machine)?,
            nodename: Self::char_ary_to_string(&b_utsname.nodename)?,
            domainname: Self::char_ary_to_string(&b_utsname.domainname)?,
        })
    }

    // Creates an instance of the libc utsname struct with all fields populated with dummy values
    fn c_utsname() -> libc::utsname {
        libc::utsname {
            sysname: [' ' as libc::c_char; 65],
            release: [' ' as libc::c_char; 65],
            version: [' ' as libc::c_char; 65],
            machine: [' ' as libc::c_char; 65],
            nodename: [' ' as libc::c_char; 65],
            domainname: [' ' as libc::c_char; 65],
        }
    }

    fn char_ary_to_string(c_ary: &[libc::c_char]) -> Result<String, Box<Error>> {
        let (index, _val) = c_ary
            .iter()
            .enumerate()
            .find(|&(_i, ele)| ele == &(0 as libc::c_char)) // check if the element is a null char
            .expect("byte array representation of string should have a null terminator.");

        let c_slice: &[u8] =
            unsafe { std::slice::from_raw_parts(c_ary.as_ptr() as *const u8, index) };

        Ok(String::from_utf8(c_slice.to_vec())?)
    }
}

/// Get the name of the host
///
/// [reference](https://www.gnu.org/software/libc/manual/html_node/Host-Identification.html#Host-Identification)
///
/// # Examples
///
/// ```
/// match rpsutil::system::hostname() {
///     Ok(name) => println!("hostname: {}", name),
///     Err(err) => println!("err: {}", err),
/// }
/// ```
pub fn hostname() -> Result<String, String> {
    let len = (libc::_SC_HOST_NAME_MAX + 1) as usize;
    let rstr = std::boxed::Box::new(String::new());
    let cstr: std::ffi::CString;

    unsafe {
        let name = std::boxed::Box::into_raw(rstr) as *mut i8;
        let code = libc::gethostname(name, len);

        if code != 0 {
            return Err(format!("name is too long > {}", len));
        }

        cstr = std::ffi::CString::from_raw(name as *mut libc::c_char);
    }

    match cstr.to_str() {
        Err(err) => Err(format!("{}", err)),
        Ok(val) => Ok(String::from(val)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_hostname() {
        assert!(hostname().is_ok());
    }

    #[test]
    fn test_uname_error() {
        let err = UnameError {};
        assert_eq!(err.description(), "Error initializing UtsName (EFAULT).");
    }
}