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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use super::{run, Error};
use std::fs;
use std::process::Command;

const HOSTNAME: &str = "/proc/sys/kernel/hostname";
const DOMAINNAME: &str = "/proc/sys/kernel/domainname";
const CPU: &str = "/proc/cpuinfo";
const MEM: &str = "/proc/meminfo";
const UPTIME: &str = "/proc/uptime";
const KERNEL: &str = "/proc/sys/kernel/osrelease";

const MODEL_NAME: &str = "model name";
const CPU_CORES: &str = "cpu cores";
const CPU_CLOCK: &str = "cpu MHz";
const TOTAL_MEM: &str = "MemTotal:";
const TOTAL_SWAP: &str = "SwapTotal:";

fn ip(iface: &str) -> Result<serde_json::Value, Error> {
    let mut _ip = Command::new("ip");
    let mut cmd = if iface == "" {
        _ip.arg("-j").arg("address").arg("show")
    } else {
        _ip.arg("-j").arg("address").arg("show").arg(&iface)
    };
    Ok(serde_json::from_str::<serde_json::Value>(&run(&mut cmd)?)
        .map_err(|e| Error::CommandParseError(e.to_string()))?)
}

pub(crate) fn default_iface() -> Result<String, Error> {
    let mut cmd = Command::new("route");
    Ok(run(&mut cmd)?
        .split('\n')
        .filter(|l| l.starts_with("default"))
        .collect::<String>()
        .split_ascii_whitespace()
        .last()
        .unwrap()
        .to_string())
}

pub(crate) fn hostname() -> Result<String, Error> {
    Ok(fs::read_to_string(HOSTNAME)
        .map_err(|e| Error::FileReadError(HOSTNAME.to_string(), e.to_string()))?
        .trim()
        .to_string())
}

pub(crate) fn domainname() -> Result<String, Error> {
    Ok(fs::read_to_string(DOMAINNAME)
        .map_err(|e| Error::FileReadError(DOMAINNAME.to_string(), e.to_string()))?
        .trim()
        .to_string())
}

pub(crate) fn ipv4(iface: &str) -> Result<String, Error> {
    let out = ip(&iface)?;
    let ip = &out[0]["addr_info"][0]["local"];
    if ip.is_string() {
        // It's ok to unwrap here because we know it's a string
        return Ok(ip.as_str().map(|s| s.to_string()).unwrap());
    }

    Err(Error::CommandParseError(format!("ip address '{:?}' was not a string", ip)))
}

pub(crate) fn mac(iface: &str) -> Result<String, Error> {
    let out = ip(&iface)?;
    let mac = &out[0]["address"];
    if mac.is_string() {
        // It's ok to unwrap here because we know it's a string
        return Ok(mac.as_str().map(|s| s.to_string()).unwrap());
    }

    Err(Error::CommandParseError(format!("mac address '{:?}' was not a string", mac)))
}

pub(crate) fn interfaces() -> Result<Vec<String>, Error> {
    let out = ip("")?;
    if !out.is_array() {
        return Err(Error::CommandParseError("invalid 'ip' command output".to_string()));
    }

    // It's ok to unwrap here because we check that out is an array and all non-string values are filtered out
    Ok(out
        .as_array()
        .unwrap()
        .iter()
        .filter(|v| v["ifname"].is_string())
        .map(|v| v["ifname"].as_str().unwrap().to_string())
        .collect())
}

pub(crate) fn ipv6(_iface: &str) -> Result<String, Error> {
    todo!()
}

pub(crate) fn cpu() -> Result<String, Error> {
    Ok(fs::read_to_string(CPU)
        .map_err(|e| Error::FileReadError(CPU.to_string(), e.to_string()))?
        .split('\n')
        .filter(|l| l.starts_with(MODEL_NAME))
        .take(1)
        .collect::<String>()
        .split(':')
        .skip(1)
        .take(1)
        .collect::<String>()
        .trim()
        .to_string())
}

pub(crate) fn cpu_cores() -> Result<u16, Error> {
    Ok(fs::read_to_string(CPU)
        .map_err(|e| Error::FileReadError(CPU.to_string(), e.to_string()))?
        .split('\n')
        .filter(|l| l.starts_with(CPU_CORES))
        .take(1)
        .collect::<String>()
        .split(':')
        .skip(1)
        .take(1)
        .collect::<String>()
        .trim()
        .parse::<u16>()
        .map_err(|e| Error::CommandParseError(e.to_string()))?)
}

pub(crate) fn cpu_clock() -> Result<f32, Error> {
    Ok(fs::read_to_string(CPU)
        .map_err(|e| Error::FileReadError(CPU.to_string(), e.to_string()))?
        .split('\n')
        .filter(|l| l.starts_with(CPU_CLOCK))
        .take(1)
        .collect::<String>()
        .split(':')
        .skip(1)
        .take(1)
        .collect::<String>()
        .trim()
        .parse::<f32>()
        .map_err(|e| Error::CommandParseError(e.to_string()))?)
}

pub(crate) fn arch() -> Result<String, Error> {
    run(Command::new("uname").arg("-m"))
}

pub(crate) fn memory() -> Result<usize, Error> {
    Ok(fs::read_to_string(MEM)
        .map_err(|e| Error::FileReadError(MEM.to_string(), e.to_string()))?
        .split('\n')
        .filter(|l| l.starts_with(TOTAL_MEM))
        .collect::<String>()
        .split_ascii_whitespace()
        .skip(1)
        .take(1)
        .collect::<String>()
        .parse::<usize>()
        .map_err(|e| Error::CommandParseError(e.to_string()))? as usize)
}

pub(crate) fn swap() -> Result<usize, Error> {
    Ok(fs::read_to_string(MEM)
        .map_err(|e| Error::FileReadError(MEM.to_string(), e.to_string()))?
        .split('\n')
        .filter(|l| l.starts_with(TOTAL_SWAP))
        .collect::<String>()
        .split_ascii_whitespace()
        .skip(1)
        .take(1)
        .collect::<String>()
        .parse::<usize>()
        .map_err(|e| Error::CommandParseError(e.to_string()))? as usize)
}

pub(crate) fn uptime() -> Result<u64, Error> {
    Ok(fs::read_to_string(UPTIME)
        .map_err(|e| Error::FileReadError(UPTIME.to_string(), e.to_string()))?
        .split_ascii_whitespace()
        .take(1)
        .collect::<String>()
        .parse::<f64>()
        .map_err(|e| Error::CommandParseError(e.to_string()))? as u64)
}

pub fn kernel_version() -> Result<String, Error> {
    Ok(fs::read_to_string(KERNEL).map_err(|e| Error::FileReadError(UPTIME.to_string(), e.to_string()))?)
}