libmacchina 8.1.0

A library that can fetch all sorts of system information.
Documentation
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#![allow(clippy::unnecessary_cast)]
mod sysinfo_ffi;
mod system_properties;

use crate::extra;
use crate::shared;
use crate::traits::*;
use itertools::Itertools;
use std::ffi::{CStr, CString};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use sysinfo_ffi::sysinfo;
use system_properties::getprop;

impl From<std::str::Utf8Error> for ReadoutError {
    fn from(e: std::str::Utf8Error) -> Self {
        ReadoutError::Other(e.to_string())
    }
}
impl From<std::num::ParseFloatError> for ReadoutError {
    fn from(e: std::num::ParseFloatError) -> Self {
        ReadoutError::Other(e.to_string())
    }
}

pub struct AndroidBatteryReadout;

pub struct AndroidKernelReadout {
    utsname: Option<libc::utsname>,
}

pub struct AndroidGeneralReadout {
    sysinfo: sysinfo,
}

pub struct AndroidMemoryReadout {
    sysinfo: sysinfo,
}

pub struct AndroidProductReadout;
pub struct AndroidPackageReadout;
pub struct AndroidNetworkReadout;

impl BatteryReadout for AndroidBatteryReadout {
    fn new() -> Self {
        AndroidBatteryReadout
    }

    fn percentage(&self) -> Result<u8, ReadoutError> {
        let bat_path = Path::new("/sys/class/power_supply/battery/capacity");
        let percentage_text = extra::pop_newline(fs::read_to_string(bat_path)?);
        let percentage_parsed = percentage_text.parse::<u8>();

        match percentage_parsed {
            Ok(p) => Ok(p),
            Err(e) => Err(ReadoutError::Other(format!(
                "Could not parse the value '{}' of {} into a \
            digit: {:?}",
                percentage_text,
                bat_path.to_str().unwrap_or_default(),
                e
            ))),
        }
    }

    fn status(&self) -> Result<BatteryState, ReadoutError> {
        let bat_path = Path::new("/sys/class/power_supply/battery/status");

        let status_text = extra::pop_newline(fs::read_to_string(bat_path)?).to_lowercase();
        match &status_text[..] {
            "charging" => Ok(BatteryState::Charging),
            "discharging" | "full" => Ok(BatteryState::Discharging),
            s => Err(ReadoutError::Other(format!(
                "Got unexpected value '{}' from {}.",
                s,
                bat_path.to_str().unwrap_or_default()
            ))),
        }
    }

    fn health(&self) -> Result<u8, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }
}

impl KernelReadout for AndroidKernelReadout {
    fn new() -> Self {
        let mut __utsname: libc::utsname = unsafe { std::mem::zeroed() };
        let utsname: Option<libc::utsname> = if unsafe { libc::uname(&mut __utsname) } == -1 {
            None
        } else {
            Some(__utsname)
        };

        AndroidKernelReadout { utsname }
    }

    fn os_release(&self) -> Result<String, ReadoutError> {
        if let Some(utsname) = self.utsname {
            return Ok(unsafe { CStr::from_ptr(utsname.release.as_ptr()) }
                .to_str()
                .unwrap()
                .to_owned());
        } else {
            Err(ReadoutError::Other(String::from(
                "Failed to get os_release",
            )))
        }
    }

    fn os_type(&self) -> Result<String, ReadoutError> {
        if let Some(utsname) = self.utsname {
            return Ok(unsafe { CStr::from_ptr(utsname.sysname.as_ptr()) }
                .to_str()
                .unwrap()
                .to_owned());
        } else {
            Err(ReadoutError::Other(String::from("Failed to get os_type")))
        }
    }
}

impl GeneralReadout for AndroidGeneralReadout {
    fn new() -> Self {
        AndroidGeneralReadout {
            sysinfo: sysinfo::new(),
        }
    }

    fn backlight(&self) -> Result<usize, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn resolution(&self) -> Result<String, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn machine(&self) -> Result<String, ReadoutError> {
        let product_readout = AndroidProductReadout::new();

        let family = product_readout.family()?;
        let vendor = product_readout.vendor()?;
        let product = product_readout.product()?;

        let new_product = format!("{vendor} {family} {product}");

        if product.is_empty() || product.len() <= 15 {
            return Ok(new_product.split_whitespace().unique().join(" "));
        }

        Ok(product)
    }

    fn username(&self) -> Result<String, ReadoutError> {
        shared::username()
    }

    fn hostname(&self) -> Result<String, ReadoutError> {
        let __name: *mut std::os::raw::c_char = CString::new("").unwrap().into_raw();
        let __len: usize = libc::_SC_HOST_NAME_MAX as usize;
        let ret = unsafe { libc::gethostname(__name, __len) };
        if ret == -1 {
            Err(ReadoutError::Other(String::from("Failed to get hostname")))
        } else {
            Ok(unsafe { CStr::from_ptr(__name).to_string_lossy().into_owned() })
        }
    }

    fn distribution(&self) -> Result<String, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn desktop_environment(&self) -> Result<String, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn session(&self) -> Result<String, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn window_manager(&self) -> Result<String, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn terminal(&self) -> Result<String, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn shell(&self, format: ShellFormat, kind: ShellKind) -> Result<String, ReadoutError> {
        if let Some(shell) = std::env::var_os("SHELL") {
            if let Some(relative) = PathBuf::from(shell).file_name() {
                if let Some(str) = relative.to_str() {
                    return Ok(str.to_owned());
                }
            }
        }

        shared::shell(format, kind)
    }

    fn cpu_model_name(&self) -> Result<String, ReadoutError> {
        use std::io::{BufRead, BufReader};
        let file = fs::File::open("/proc/cpuinfo");
        let mut model: Option<String> = None;
        let mut hardware: Option<String> = None;
        let mut processor: Option<String> = None;

        let get_value_from_line = |input: String, option: &str| -> String {
            input
                .replace(option, "")
                .replace(':', "")
                .trim()
                .to_string()
        };

        if let Ok(content) = file {
            let reader = BufReader::new(content);
            for line in reader.lines().map_while(Result::ok) {
                if line.starts_with("Hardware") {
                    hardware = Some(get_value_from_line(line, "Hardware"));
                    break; // If "Hardware" information is present, the rest is not needed.
                } else if line.starts_with("Processor") {
                    processor = Some(get_value_from_line(line, "Processor"));
                } else if line.starts_with("model name") && model.is_none() {
                    model = Some(get_value_from_line(line, "model name"));
                }
            }
        }
        match (hardware, model, processor) {
            (Some(hardware), _, _) => Ok(hardware),
            (_, Some(model), _) => Ok(model),
            (_, _, Some(processor)) => Ok(processor),
            (_, _, _) => Err(ReadoutError::Other(String::from(
                "Failed to get processor model name",
            ))),
        }
    }

    fn cpu_physical_cores(&self) -> Result<usize, ReadoutError> {
        shared::cpu_physical_cores()
    }

    fn cpu_cores(&self) -> Result<usize, ReadoutError> {
        shared::cpu_cores()
    }

    fn cpu_usage(&self) -> Result<usize, ReadoutError> {
        let mut info = self.sysinfo;
        let info_ptr: *mut sysinfo = &mut info;
        let ret = unsafe { sysinfo(info_ptr) };
        if ret != -1 {
            let f_load = 1f64 / (1 << libc::SI_LOAD_SHIFT) as f64;
            let cpu_usage = info.loads[0] as f64 * f_load;
            let cpu_usage_u = (cpu_usage / num_cpus::get() as f64 * 100.0).round() as usize;
            if cpu_usage_u != 0 {
                return Ok(cpu_usage_u as usize);
            }
            Err(ReadoutError::Other("Processor usage is null.".to_string()))
        } else {
            Err(ReadoutError::Other(
                "Failed to get system statistics".to_string(),
            ))
        }
    }

    fn uptime(&self) -> Result<usize, ReadoutError> {
        let mut info = self.sysinfo;
        let info_ptr: *mut sysinfo = &mut info;
        let ret = unsafe { sysinfo(info_ptr) };
        if ret != -1 {
            Ok(info.uptime as usize)
        } else {
            Err(ReadoutError::Other(
                "Failed to get system statistics".to_string(),
            ))
        }
    }

    fn os_name(&self) -> Result<String, ReadoutError> {
        match getprop("ro.build.version.release") {
            Some(version) => Ok("Android ".to_string() + &version),
            None => Err(ReadoutError::Other(
                "Failed to get Android version".to_string(),
            )),
        }
    }

    fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn gpus(&self) -> Result<Vec<String>, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }
}

impl MemoryReadout for AndroidMemoryReadout {
    fn new() -> Self {
        AndroidMemoryReadout {
            sysinfo: sysinfo::new(),
        }
    }

    fn total(&self) -> Result<u64, ReadoutError> {
        let mut info = self.sysinfo;
        let info_ptr: *mut sysinfo = &mut info;
        let ret = unsafe { sysinfo(info_ptr) };
        if ret != -1 {
            Ok(info.totalram * info.mem_unit as u64 / 1024)
        } else {
            Err(ReadoutError::Other(
                "Failed to get system statistics".to_string(),
            ))
        }
    }

    fn free(&self) -> Result<u64, ReadoutError> {
        let mut info = self.sysinfo;
        let info_ptr: *mut sysinfo = &mut info;
        let ret = unsafe { sysinfo(info_ptr) };
        if ret != -1 {
            Ok(info.freeram * info.mem_unit as u64 / 1024)
        } else {
            Err(ReadoutError::Other(
                "Failed to get system statistics".to_string(),
            ))
        }
    }

    fn buffers(&self) -> Result<u64, ReadoutError> {
        let mut info = self.sysinfo;
        let info_ptr: *mut sysinfo = &mut info;
        let ret = unsafe { sysinfo(info_ptr) };
        if ret != -1 {
            Ok(info.bufferram * info.mem_unit as u64 / 1024)
        } else {
            Err(ReadoutError::Other(
                "Failed to get system statistics".to_string(),
            ))
        }
    }

    fn cached(&self) -> Result<u64, ReadoutError> {
        Ok(shared::get_meminfo_value("Cached"))
    }

    fn reclaimable(&self) -> Result<u64, ReadoutError> {
        Ok(shared::get_meminfo_value("SReclaimable"))
    }

    fn used(&self) -> Result<u64, ReadoutError> {
        let total = self.total().unwrap();
        let free = self.free().unwrap();
        let cached = self.cached().unwrap();
        let reclaimable = self.reclaimable().unwrap();
        let buffers = self.buffers().unwrap();

        Ok(total - free - cached - reclaimable - buffers)
    }

    fn swap_total(&self) -> Result<u64, ReadoutError> {
        return Err(ReadoutError::NotImplemented);
    }

    fn swap_free(&self) -> Result<u64, ReadoutError> {
        return Err(ReadoutError::NotImplemented);
    }

    fn swap_used(&self) -> Result<u64, ReadoutError> {
        return Err(ReadoutError::NotImplemented);
    }
}

impl ProductReadout for AndroidProductReadout {
    fn new() -> Self {
        AndroidProductReadout
    }

    fn family(&self) -> Result<String, ReadoutError> {
        getprop("ro.product.model")
            .ok_or_else(|| ReadoutError::Other("Failed to get device family property".to_string()))
    }

    fn vendor(&self) -> Result<String, ReadoutError> {
        getprop("ro.product.brand")
            .ok_or_else(|| ReadoutError::Other("Failed to get device vendor property".to_string()))
    }

    fn product(&self) -> Result<String, ReadoutError> {
        getprop("ro.build.product")
            .ok_or_else(|| ReadoutError::Other("Failed to get device product property".to_string()))
    }
}

impl PackageReadout for AndroidPackageReadout {
    fn new() -> Self {
        AndroidPackageReadout
    }

    /// Supports: pm, dpkg, cargo
    fn count_pkgs(&self) -> Vec<(PackageManager, usize)> {
        let mut packages = Vec::new();
        // Since the target is Android we can assume that pm is available
        if let Some(c) = AndroidPackageReadout::count_pm() {
            packages.push((PackageManager::Android, c));
        }

        if extra::which("dpkg") {
            if let Some(c) = AndroidPackageReadout::count_dpkg() {
                packages.push((PackageManager::Dpkg, c));
            }
        }

        if extra::which("cargo") {
            if let Some(c) = AndroidPackageReadout::count_cargo() {
                packages.push((PackageManager::Cargo, c));
            }
        }

        packages
    }
}

impl AndroidPackageReadout {
    /// Returns the number of installed apps for the system
    /// Includes all apps ( user + system )
    fn count_pm() -> Option<usize> {
        let pm_output = Command::new("pm")
            .args(["list", "packages"])
            .stdout(Stdio::piped())
            .output()
            .unwrap();

        extra::count_lines(
            String::from_utf8(pm_output.stdout)
                .expect("ERROR: \"pm list packages\" output was not valid UTF-8"),
        )
    }
    /// Return the number of installed packages for systems
    /// that have `dpkg` installed.
    /// In android that's mainly termux.
    fn count_dpkg() -> Option<usize> {
        let prefix = match std::env::var_os("PREFIX") {
            None => return None,
            Some(prefix) => prefix,
        };

        let dpkg_dir = Path::new(&prefix).join("var/lib/dpkg/info");

        extra::get_entries(&dpkg_dir).map(|entries| {
            entries
                .iter()
                .filter(|x| extra::path_extension(x).unwrap_or_default() == "list")
                .count()
        })
    }

    /// Returns the number of installed packages for systems
    /// that have `cargo` installed.
    fn count_cargo() -> Option<usize> {
        shared::count_cargo()
    }
}

impl NetworkReadout for AndroidNetworkReadout {
    fn new() -> Self {
        AndroidNetworkReadout
    }

    fn tx_bytes(&self, _: Option<&str>) -> Result<usize, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn tx_packets(&self, _: Option<&str>) -> Result<usize, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn rx_bytes(&self, _: Option<&str>) -> Result<usize, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn rx_packets(&self, _: Option<&str>) -> Result<usize, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }

    fn logical_address(&self, interface: Option<&str>) -> Result<String, ReadoutError> {
        shared::logical_address(interface)
    }

    fn physical_address(&self, _: Option<&str>) -> Result<String, ReadoutError> {
        Err(ReadoutError::NotImplemented)
    }
}