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: u64,
pub instances: 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: u64,
pub boot_timestamp: u64,
pub boot_mode: BootMode,
pub kernel_cmdline: String,
pub user_count: u32,
pub loaded_modules: Vec<KernelModule>,
pub timezone: String,
pub locale: String,
pub is_64bit: bool,
pub secure_boot: bool,
}
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: 0,
boot_timestamp: 0,
boot_mode: BootMode::Unknown,
kernel_cmdline: String::new(),
user_count: 0,
loaded_modules: Vec::new(),
timezone: String::new(),
locale: String::new(),
is_64bit: cfg!(target_pointer_width = "64"),
secure_boot: false,
},
};
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();
}
}
if let Ok(content) = std::fs::read_to_string("/proc/uptime") {
if let Some(secs_str) = content.split_whitespace().next() {
if let Ok(secs) = secs_str.parse::<f64>() {
self.info.uptime_seconds = secs as u64;
}
}
}
if let Ok(content) = std::fs::read_to_string("/proc/stat") {
for line in content.lines() {
if let Some(rest) = line.strip_prefix("btime ") {
if let Ok(ts) = rest.trim().parse() {
self.info.boot_timestamp = ts;
}
}
}
}
self.info.boot_mode = if std::path::Path::new("/sys/firmware/efi").exists() {
BootMode::UEFI
} else {
BootMode::BIOS
};
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 = text.contains("SecureBoot enabled");
}
if let Ok(content) = std::fs::read_to_string("/proc/cmdline") {
self.info.kernel_cmdline = content.trim().to_string();
}
if let Ok(output) = std::process::Command::new("who").output() {
let text = String::from_utf8(output.stdout).unwrap_or_default();
self.info.user_count = text.lines().count() as u32;
}
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().unwrap_or(0);
let instances = parts[2].parse().unwrap_or(0);
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: u32 = plat::read_registry_string(CURRENT_VERSION, "CurrentBuildNumber")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
if let Some(product) = plat::read_registry_string(CURRENT_VERSION, "ProductName") {
self.info.os_name = if build >= 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)) = (major, minor) {
self.info.os_version = format!("{major}.{minor}.{build}");
}
if build > 0 {
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() };
self.info.uptime_seconds = uptime_ms / 1000;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
self.info.boot_timestamp = now.saturating_sub(self.info.uptime_seconds);
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().unwrap_or(false);
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();
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 = boot_sec;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
self.info.uptime_seconds = now.saturating_sub(boot_sec);
}
}
}
self.info.boot_mode = BootMode::UEFI;
if let Ok(output) = std::process::Command::new("system_profiler")
.args(["SPHardwareDataType"])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
self.info.secure_boot = text.contains("Apple M") || text.contains("Apple T2");
}
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: u32 = parts[1].parse().unwrap_or(0);
let size: u64 =
u64::from_str_radix(parts[3].trim_start_matches("0x"), 16).unwrap_or(0);
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: 0,
boot_timestamp: 0,
boot_mode: BootMode::Unknown,
kernel_cmdline: String::new(),
user_count: 0,
loaded_modules: Vec::new(),
timezone: String::new(),
locale: String::new(),
is_64bit: cfg!(target_pointer_width = "64"),
secure_boot: false,
},
})
}
}
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: 0,
instances: 1,
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 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: 3600,
boot_timestamp: 1700000000,
boot_mode: BootMode::UEFI,
kernel_cmdline: "root=/dev/sda1".into(),
user_count: 1,
loaded_modules: Vec::new(),
timezone: "America/New_York".into(),
locale: "en_US.UTF-8".into(),
is_64bit: true,
secure_boot: true,
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("Ubuntu"));
let _: OsInfo = serde_json::from_str(&json).unwrap();
}
#[test]
fn test_kernel_module_serialization() {
let module = KernelModule {
name: "nvidia".into(),
size_bytes: 1048576,
instances: 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();
}
}