use serde::{Deserialize, Serialize};
use crate::error::IronError;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum OsFamily {
Linux,
Windows,
MacOS,
FreeBSD,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BootMode {
UEFI,
BIOS,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelModule {
pub name: String,
pub size_bytes: Option<u64>,
pub instances: Option<u32>,
pub used_by: Vec<String>,
pub state: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OsInfo {
pub os_family: OsFamily,
pub os_name: String,
pub os_version: String,
pub os_build: String,
pub kernel_version: String,
pub kernel_full: String,
pub architecture: String,
pub hostname: String,
pub domain: String,
pub uptime_seconds: Option<u64>,
pub boot_timestamp: Option<u64>,
pub boot_mode: BootMode,
pub kernel_cmdline: String,
pub user_count: Option<u32>,
pub loaded_modules: Vec<KernelModule>,
pub timezone: String,
pub locale: String,
pub is_64bit: bool,
pub secure_boot: Option<bool>,
}
#[cfg(any(target_os = "linux", test))]
fn parse_mokutil_sb_state(text: &str) -> Option<bool> {
if text.contains("SecureBoot enabled") {
Some(true)
} else if text.contains("SecureBoot disabled") {
Some(false)
} else {
None
}
}
#[cfg(any(target_os = "linux", test))]
fn parse_proc_uptime(text: &str) -> Option<u64> {
let secs: f64 = text.split_whitespace().next()?.parse().ok()?;
Some(secs as u64)
}
#[cfg(any(target_os = "linux", test))]
fn parse_btime(text: &str) -> Option<u64> {
text.lines()
.find_map(|line| line.strip_prefix("btime "))
.and_then(|rest| rest.trim().parse().ok())
}
#[cfg(any(target_os = "linux", test))]
fn parse_who_count(text: &str) -> u32 {
text.lines().count() as u32
}
pub struct OsInfoMonitor {
info: OsInfo,
}
impl OsInfoMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self {
info: OsInfo {
os_family: OsFamily::Unknown,
os_name: String::new(),
os_version: String::new(),
os_build: String::new(),
kernel_version: String::new(),
kernel_full: String::new(),
architecture: String::new(),
hostname: String::new(),
domain: String::new(),
uptime_seconds: None,
boot_timestamp: None,
boot_mode: BootMode::Unknown,
kernel_cmdline: String::new(),
user_count: None,
loaded_modules: Vec::new(),
timezone: String::new(),
locale: String::new(),
is_64bit: cfg!(target_pointer_width = "64"),
secure_boot: None,
},
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.info.loaded_modules.clear();
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
if self.info.hostname.is_empty() {
if let Ok(output) = std::process::Command::new("hostname").output() {
self.info.hostname = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
}
}
Ok(())
}
pub fn info(&self) -> &OsInfo {
&self.info
}
pub fn modules(&self) -> &[KernelModule] {
&self.info.loaded_modules
}
pub fn module_count(&self) -> usize {
self.info.loaded_modules.len()
}
pub fn find_module(&self, name: &str) -> Option<&KernelModule> {
self.info.loaded_modules.iter().find(|m| m.name == name)
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), IronError> {
self.info.os_family = OsFamily::Linux;
let os_release = match std::fs::read_to_string("/etc/os-release") {
Ok(c) => Some(c),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => {
return Err(IronError::System(format!(
"cannot read /etc/os-release: {e}"
)))
}
};
if let Some(content) = os_release {
for line in content.lines() {
if let Some(val) = line.strip_prefix("PRETTY_NAME=") {
self.info.os_name = val.trim_matches('"').to_string();
} else if let Some(val) = line.strip_prefix("VERSION_ID=") {
self.info.os_version = val.trim_matches('"').to_string();
} else if let Some(val) = line.strip_prefix("BUILD_ID=") {
self.info.os_build = val.trim_matches('"').to_string();
}
}
}
if let Ok(content) = std::fs::read_to_string("/proc/version") {
self.info.kernel_full = content.trim().to_string();
if let Some(ver) = content.split_whitespace().nth(2) {
self.info.kernel_version = ver.to_string();
}
}
if let Ok(output) = std::process::Command::new("uname").arg("-m").output() {
self.info.architecture = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
}
if let Ok(content) = std::fs::read_to_string("/etc/hostname") {
self.info.hostname = content.trim().to_string();
}
if let Ok(content) = std::fs::read_to_string("/proc/sys/kernel/domainname") {
let d = content.trim();
if d != "(none)" {
self.info.domain = d.to_string();
}
}
self.info.uptime_seconds = std::fs::read_to_string("/proc/uptime")
.ok()
.and_then(|content| parse_proc_uptime(&content));
self.info.boot_timestamp = None;
if self.info.uptime_seconds.is_some() {
self.info.boot_timestamp = std::fs::read_to_string("/proc/stat")
.ok()
.and_then(|content| parse_btime(&content));
}
self.info.boot_mode = if std::path::Path::new("/sys/firmware/efi").exists() {
BootMode::UEFI
} else {
BootMode::BIOS
};
self.info.secure_boot = None;
if let Ok(output) = std::process::Command::new("mokutil")
.arg("--sb-state")
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
self.info.secure_boot = parse_mokutil_sb_state(&text);
}
if let Ok(content) = std::fs::read_to_string("/proc/cmdline") {
self.info.kernel_cmdline = content.trim().to_string();
}
self.info.user_count = std::process::Command::new("who")
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| parse_who_count(&String::from_utf8_lossy(&output.stdout)));
if let Ok(content) = std::fs::read_to_string("/proc/modules") {
for line in content.lines() {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 4 {
let name = parts[0].to_string();
let size_bytes = parts[1].parse().ok();
let instances = parts[2].parse().ok();
let used_by: Vec<String> = if parts[3] == "-" {
Vec::new()
} else {
parts[3]
.trim_end_matches(',')
.split(',')
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect()
};
let state = parts.get(4).unwrap_or(&"").to_string();
self.info.loaded_modules.push(KernelModule {
name,
size_bytes,
instances,
used_by,
state,
});
}
}
}
if let Ok(tz) = std::fs::read_link("/etc/localtime") {
let path = tz.to_string_lossy().to_string();
if let Some(pos) = path.find("zoneinfo/") {
self.info.timezone = path[pos + 9..].to_string();
}
}
if self.info.timezone.is_empty() {
if let Ok(content) = std::fs::read_to_string("/etc/timezone") {
self.info.timezone = content.trim().to_string();
}
}
if let Ok(val) = std::env::var("LANG") {
self.info.locale = val;
}
Ok(())
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
use crate::platform::windows as plat;
self.info.os_family = OsFamily::Windows;
const CURRENT_VERSION: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
let build: Option<u32> = plat::read_registry_string(CURRENT_VERSION, "CurrentBuildNumber")
.and_then(|s| s.parse().ok());
if let Some(product) = plat::read_registry_string(CURRENT_VERSION, "ProductName") {
self.info.os_name = if build.is_some_and(|b| b >= 22000) {
product.replace("Windows 10", "Windows 11")
} else {
product
};
}
let major = plat::read_registry_u32(CURRENT_VERSION, "CurrentMajorVersionNumber");
let minor = plat::read_registry_u32(CURRENT_VERSION, "CurrentMinorVersionNumber");
if let (Some(major), Some(minor), Some(build)) = (major, minor, build) {
self.info.os_version = format!("{major}.{minor}.{build}");
}
if let Some(build) = build {
self.info.os_build = build.to_string();
}
let ubr = plat::read_registry_u32(CURRENT_VERSION, "UBR");
if !self.info.os_version.is_empty() {
self.info.kernel_version = match ubr {
Some(ubr) => format!("{}.{ubr}", self.info.os_version),
None => self.info.os_version.clone(),
};
self.info.kernel_full =
format!("Microsoft Windows [Version {}]", self.info.kernel_version);
}
if let Some(name) = windows_computer_name() {
self.info.hostname = name;
}
let (arch, is_64bit) = windows_native_architecture();
self.info.architecture = arch;
self.info.is_64bit = is_64bit;
let uptime_ms = unsafe { windows::Win32::System::SystemInformation::GetTickCount64() };
let uptime = uptime_ms / 1000;
self.info.uptime_seconds = Some(uptime);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
self.info.boot_timestamp = Some(now.saturating_sub(uptime));
self.info.boot_mode = match plat::firmware_type() {
Some(crate::boot_config::BootType::Uefi) => BootMode::UEFI,
Some(crate::boot_config::BootType::Legacy) => BootMode::BIOS,
_ => BootMode::Unknown,
};
self.info.secure_boot = plat::secure_boot_enabled();
if let Some(tz) = windows_timezone_key() {
self.info.timezone = tz;
}
if let Some(locale) = windows_user_locale() {
self.info.locale = locale;
}
self.info.loaded_modules = windows_running_drivers();
self.info.user_count = None;
Ok(())
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), IronError> {
self.info.os_family = OsFamily::MacOS;
{
let text = crate::core::command::capture("sw_vers", &[])?;
for line in text.lines() {
if let Some(val) = line.strip_prefix("ProductName:") {
self.info.os_name = val.trim().to_string();
} else if let Some(val) = line.strip_prefix("ProductVersion:") {
self.info.os_version = val.trim().to_string();
} else if let Some(val) = line.strip_prefix("BuildVersion:") {
self.info.os_build = val.trim().to_string();
}
}
}
if let Ok(output) = std::process::Command::new("uname").arg("-r").output() {
self.info.kernel_version = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
}
if let Ok(output) = std::process::Command::new("uname").arg("-v").output() {
self.info.kernel_full = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
}
if let Ok(output) = std::process::Command::new("uname").arg("-m").output() {
self.info.architecture = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
}
if let Ok(output) = std::process::Command::new("hostname").output() {
self.info.hostname = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
}
if let Ok(output) = std::process::Command::new("sysctl")
.args(["-n", "kern.boottime"])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
if let Some(sec_str) = text
.split("sec = ")
.nth(1)
.and_then(|s| s.split(',').next())
{
if let Ok(boot_sec) = sec_str.trim().parse::<u64>() {
self.info.boot_timestamp = Some(boot_sec);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
self.info.uptime_seconds = Some(now.saturating_sub(boot_sec));
}
}
}
self.info.boot_mode = BootMode::Unknown;
self.info.secure_boot = None;
if let Ok(tz) = std::fs::read_link("/etc/localtime") {
let path = tz.to_string_lossy().to_string();
if let Some(pos) = path.find("zoneinfo/") {
self.info.timezone = path[pos + 9..].to_string();
}
}
if let Ok(val) = std::env::var("LANG") {
self.info.locale = val;
}
if let Ok(output) = std::process::Command::new("kextstat").args(["-l"]).output() {
let text = String::from_utf8(output.stdout).unwrap_or_default();
for line in text.lines().skip(1) {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 6 {
let name = parts[5].to_string();
let refs: Option<u32> = parts[1].parse().ok();
let size: Option<u64> =
u64::from_str_radix(parts[3].trim_start_matches("0x"), 16).ok();
self.info.loaded_modules.push(KernelModule {
name,
size_bytes: size,
instances: refs,
used_by: Vec::new(),
state: "Live".to_string(),
});
}
}
}
Ok(())
}
}
impl Default for OsInfoMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
info: OsInfo {
os_family: OsFamily::Unknown,
os_name: String::new(),
os_version: String::new(),
os_build: String::new(),
kernel_version: String::new(),
kernel_full: String::new(),
architecture: String::new(),
hostname: String::new(),
domain: String::new(),
uptime_seconds: None,
boot_timestamp: None,
boot_mode: BootMode::Unknown,
kernel_cmdline: String::new(),
user_count: None,
loaded_modules: Vec::new(),
timezone: String::new(),
locale: String::new(),
is_64bit: cfg!(target_pointer_width = "64"),
secure_boot: None,
},
})
}
}
impl std::fmt::Display for OsFamily {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Linux => write!(f, "Linux"),
Self::Windows => write!(f, "Windows"),
Self::MacOS => write!(f, "macOS"),
Self::FreeBSD => write!(f, "FreeBSD"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
impl std::fmt::Display for BootMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UEFI => write!(f, "UEFI"),
Self::BIOS => write!(f, "BIOS"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(target_os = "windows")]
fn windows_computer_name() -> Option<String> {
use windows::Win32::System::SystemInformation::{ComputerNameNetBIOS, GetComputerNameExW};
let mut len: u32 = 0;
let _ =
unsafe { GetComputerNameExW(ComputerNameNetBIOS, windows::core::PWSTR::null(), &mut len) };
if len == 0 {
return None;
}
let mut buffer = vec![0u16; len as usize + 1];
unsafe {
GetComputerNameExW(
ComputerNameNetBIOS,
windows::core::PWSTR(buffer.as_mut_ptr()),
&mut len,
)
}
.ok()?;
buffer.truncate(len as usize);
let name = String::from_utf16_lossy(&buffer);
let name = name.trim().to_string();
if name.is_empty() {
None
} else {
Some(name)
}
}
#[cfg(target_os = "windows")]
fn windows_native_architecture() -> (String, bool) {
use windows::Win32::System::SystemInformation::{GetNativeSystemInfo, SYSTEM_INFO};
use windows::Win32::System::SystemInformation::{
PROCESSOR_ARCHITECTURE_AMD64, PROCESSOR_ARCHITECTURE_ARM, PROCESSOR_ARCHITECTURE_ARM64,
PROCESSOR_ARCHITECTURE_INTEL,
};
let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() };
unsafe { GetNativeSystemInfo(&mut info) };
let arch = unsafe { info.Anonymous.Anonymous.wProcessorArchitecture };
match arch {
PROCESSOR_ARCHITECTURE_AMD64 => ("x86_64".to_string(), true),
PROCESSOR_ARCHITECTURE_ARM64 => ("aarch64".to_string(), true),
PROCESSOR_ARCHITECTURE_ARM => ("arm".to_string(), false),
PROCESSOR_ARCHITECTURE_INTEL => ("x86".to_string(), false),
_ => (
std::env::consts::ARCH.to_string(),
cfg!(target_pointer_width = "64"),
),
}
}
#[cfg(target_os = "windows")]
fn windows_timezone_key() -> Option<String> {
use windows::Win32::System::Time::{
GetDynamicTimeZoneInformation, DYNAMIC_TIME_ZONE_INFORMATION,
};
let mut tz = DYNAMIC_TIME_ZONE_INFORMATION::default();
if unsafe { GetDynamicTimeZoneInformation(&mut tz) } == u32::MAX {
return None;
}
let key: String = String::from_utf16_lossy(&tz.TimeZoneKeyName)
.trim_end_matches('\0')
.trim()
.to_string();
if key.is_empty() {
None
} else {
Some(key)
}
}
#[cfg(target_os = "windows")]
fn windows_user_locale() -> Option<String> {
use windows::Win32::Globalization::GetUserDefaultLocaleName;
let mut buffer = [0u16; 85]; let len = unsafe { GetUserDefaultLocaleName(&mut buffer) };
if len <= 1 {
return None;
}
Some(String::from_utf16_lossy(&buffer[..(len as usize - 1)]))
}
#[cfg(target_os = "windows")]
fn windows_running_drivers() -> Vec<KernelModule> {
let Ok(drivers) = crate::motherboard::get_running_drivers() else {
return Vec::new();
};
drivers
.into_iter()
.map(|(name, state)| KernelModule {
name,
size_bytes: None,
instances: None,
used_by: Vec::new(),
state,
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_os_info_creation() {
match OsInfoMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_os_info_default() {
let monitor = OsInfoMonitor::default();
let info = monitor.info();
assert!(!info.hostname.is_empty() || info.os_family == OsFamily::Unknown);
}
#[test]
fn test_os_info_has_data() {
if let Ok(monitor) = OsInfoMonitor::new() {
let info = monitor.info();
assert_ne!(info.os_family, OsFamily::Unknown);
assert!(!info.kernel_version.is_empty());
}
}
#[test]
fn proc_uptime_is_the_first_field_and_absent_when_malformed() {
assert_eq!(parse_proc_uptime("123456.78 987654.32\n"), Some(123456));
assert_eq!(parse_proc_uptime(""), None);
assert_eq!(parse_proc_uptime("garbage"), None);
}
#[test]
fn btime_is_read_from_proc_stat_and_absent_without_the_line() {
let stat = "cpu 100 0 200 300 0 0 0 0 0 0\nbtime 1700000000\nprocesses 42\n";
assert_eq!(parse_btime(stat), Some(1_700_000_000));
assert_eq!(parse_btime("cpu 1 2 3\nprocesses 42\n"), None);
}
#[test]
fn who_counts_sessions_and_an_empty_listing_is_zero() {
let who = concat!(
"alice tty2 2026-10-24 08:01 (:0)\n",
"bob pts/0 2026-10-24 09:14 (10.0.0.5)\n"
);
assert_eq!(parse_who_count(who), 2);
assert_eq!(parse_who_count(""), 0);
}
#[test]
fn test_os_family_display() {
assert_eq!(OsFamily::Linux.to_string(), "Linux");
assert_eq!(OsFamily::Windows.to_string(), "Windows");
assert_eq!(BootMode::UEFI.to_string(), "UEFI");
}
#[test]
fn test_os_info_serialization() {
let info = OsInfo {
os_family: OsFamily::Linux,
os_name: "Ubuntu 22.04".into(),
os_version: "22.04".into(),
os_build: "".into(),
kernel_version: "6.8.0".into(),
kernel_full: "Linux version 6.8.0".into(),
architecture: "x86_64".into(),
hostname: "myhost".into(),
domain: "".into(),
uptime_seconds: Some(3600),
boot_timestamp: Some(1700000000),
boot_mode: BootMode::UEFI,
kernel_cmdline: "root=/dev/sda1".into(),
user_count: Some(1),
loaded_modules: Vec::new(),
timezone: "America/New_York".into(),
locale: "en_US.UTF-8".into(),
is_64bit: true,
secure_boot: Some(true),
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("Ubuntu"));
let _: OsInfo = serde_json::from_str(&json).unwrap();
}
#[test]
fn mokutil_output_is_read_only_when_it_states_the_mode() {
assert_eq!(parse_mokutil_sb_state("SecureBoot enabled\n"), Some(true));
assert_eq!(parse_mokutil_sb_state("SecureBoot disabled\n"), Some(false));
assert_eq!(
parse_mokutil_sb_state("This system doesn't support Secure Boot\n"),
None
);
assert_eq!(parse_mokutil_sb_state(""), None);
}
#[test]
fn test_kernel_module_serialization() {
let module = KernelModule {
name: "nvidia".into(),
size_bytes: Some(1048576),
instances: Some(1),
used_by: vec!["nvidia_uvm".into()],
state: "Live".into(),
};
let json = serde_json::to_string(&module).unwrap();
assert!(json.contains("nvidia"));
let _: KernelModule = serde_json::from_str(&json).unwrap();
}
}