//! Read-only hardware and disk probing. //! //! These functions never write. They take a `ProcessRunner` directly so they //! still work in dry-run mode (mirroring the Bash prototype, where probing is //! independent of `run_cmd`). use std::collections::HashMap; use std::path::Path; use phoebus_core::disk::{Disk, DiskKind}; use phoebus_core::hardware::{ CpuInfo, FirmwareMode, GpuInfo, GpuVendor, HardwareReport, NetworkDevice, VirtualMachine, }; use crate::command::{CommandSpec, ProcessRunner}; fn capture(runner: &dyn ProcessRunner, program: &str, args: &[&str]) -> String { let spec = CommandSpec::new("probe", program, program).args(args.iter().map(|s| s.to_string())); match runner.execute(&spec) { Ok(out) => out.stdout_lossy(), Err(_) => String::new(), } } fn read_trim(path: &str) -> Option { std::fs::read_to_string(path) .ok() .map(|s| s.trim().to_string()) } // --------------------------------------------------------------------------- // Hardware // --------------------------------------------------------------------------- pub fn probe_firmware() -> FirmwareMode { if std::path::Path::new("/sys/firmware/efi").is_dir() { FirmwareMode::Uefi } else { FirmwareMode::Bios } } pub fn probe_cpu() -> CpuInfo { let mut info = CpuInfo::default(); if let Ok(text) = std::fs::read_to_string("/proc/cpuinfo") { let mut threads = 0u32; for line in text.lines() { if line.starts_with("processor") { threads += 1; } if let Some((key, value)) = line.split_once(':') { let key = key.trim(); let value = value.trim(); match key { "vendor_id" if info.vendor.is_empty() => info.vendor = value.into(), "model name" if info.model.is_empty() => info.model = value.into(), "flags" if info.features.is_empty() => { info.features = value.split_whitespace().map(str::to_string).collect(); } _ => {} } } } info.threads = threads; } if let Ok(text) = std::fs::read_to_string("/sys/devices/system/cpu/online") { // "0-7" or "0" let text = text.trim(); if let Some((a, b)) = text.split_once('-') { if let (Ok(a), Ok(b)) = (a.parse::(), b.parse::()) { info.cores = b - a + 1; } } else if let Ok(n) = text.parse::() { info.cores = n + 1; } } if info.cores == 0 { info.cores = info.threads.max(1); } info } pub fn probe_memory_mib() -> u64 { if let Ok(text) = std::fs::read_to_string("/proc/meminfo") { for line in text.lines() { if let Some(rest) = line.strip_prefix("MemTotal:") { if let Some(kb) = rest.split_whitespace().next() { if let Ok(kb) = kb.parse::() { return kb / 1024; } } } } } 0 } fn classify_gpu(line: &str) -> GpuVendor { let lower = line.to_ascii_lowercase(); if lower.contains("nvidia") { GpuVendor::Nvidia } else if lower.contains("amd") || lower.contains("ati") || lower.contains("advanced micro") { GpuVendor::Amd } else if lower.contains("intel") { GpuVendor::Intel } else { GpuVendor::Unknown } } /// Extract `(vendor:device, pci_address)` from an `lspci -nn` line. /// /// The numeric vendor:device pair is the last `[vvvv:dddd]` tag; the class /// code (`[0300]`) has no colon and is ignored. The PCI address is the first /// whitespace-delimited field (`01:00.0`). fn parse_lspci_identity(line: &str) -> (Option, Option) { let mut pair = None; let bytes = line.as_bytes(); let mut i = 0; while i < bytes.len() { if bytes[i] == b'[' { if let Some(rel) = line[i + 1..].find(']') { let inner = &line[i + 1..i + 1 + rel]; if let Some((vendor, device)) = inner.split_once(':') { let device = &device[..device.len().min(4)]; if vendor.len() == 4 && device.len() == 4 && vendor.chars().all(|c| c.is_ascii_hexdigit()) && device.chars().all(|c| c.is_ascii_hexdigit()) { pair = Some(format!( "{}:{}", vendor.to_ascii_lowercase(), device.to_ascii_lowercase() )); } } i += 1 + rel; } } i += 1; } let address = line .split_whitespace() .next() .filter(|t| t.contains(':') && t.contains('.')) .map(str::to_string); (pair, address) } fn lspci_filter(runner: &dyn ProcessRunner, pattern: &str) -> Vec { let out = capture(runner, "lspci", &["-nn"]); out.lines() .filter(|l| { let l = l.to_ascii_lowercase(); pattern .split('|') .any(|p| l.contains(&p.to_ascii_lowercase())) }) .map(str::to_string) .collect() } pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport { let cpu = probe_cpu(); let virtual_machine = VirtualMachine::detect( capture(runner, "systemd-detect-virt", &["--vm"]).trim(), &read_trim("/sys/class/dmi/id/sys_vendor").unwrap_or_default(), &read_trim("/sys/class/dmi/id/product_name").unwrap_or_default(), ); let gpu_lines = lspci_filter( runner, "VGA compatible controller|3D controller|Display controller", ); let gpus = gpu_lines .iter() .map(|l| { let (pci_id, pci_address) = parse_lspci_identity(l); GpuInfo { vendor: classify_gpu(l), description: l.clone(), pci_id, pci_address, } }) .collect(); let mut network = Vec::new(); if let Ok(entries) = std::fs::read_dir("/sys/class/net") { for entry in entries.flatten() { let name = entry.file_name().to_string_lossy().to_string(); if name == "lo" { continue; } let base = entry.path(); let wireless = base.join("wireless").exists() || base.join("phy80211").exists(); let operstate = read_trim(&base.join("operstate").to_string_lossy()).unwrap_or_default(); network.push(NetworkDevice { name, wireless, operstate, }); } } let mut bluetooth = lspci_filter(runner, "Bluetooth"); if let Ok(out) = crate::command::capture_unleased(&mut std::process::Command::new("lsusb")) { let text = String::from_utf8_lossy(&out.stdout); for line in text .lines() .filter(|l| l.to_ascii_lowercase().contains("bluetooth")) { bluetooth.push(line.to_string()); } } let input_devices = std::fs::read_to_string("/proc/bus/input/devices") .map(|t| t.lines().filter(|l| l.starts_with("N: Name=")).count() as u32) .unwrap_or(0); let laptop = std::fs::read_dir("/sys/class/power_supply") .map(|entries| { entries .flatten() .any(|e| e.file_name().to_string_lossy().starts_with("BAT")) }) .unwrap_or(false); HardwareReport { firmware: Some(probe_firmware()), virtual_machine, cpu, memory_mib: probe_memory_mib(), gpus, network, storage_controllers: lspci_filter(runner, "SATA controller|NVMe|RAID bus controller"), audio: lspci_filter(runner, "Audio device"), bluetooth, usb_controllers: lspci_filter(runner, "USB controller"), input_devices, laptop, } } /// Enumerate NVIDIA display controllers from sysfs. /// /// `sysfs` is normally `/sys`; it is a parameter so the live driver decision /// can be exercised against a fixture without root or the real machine's /// hardware. Only display-class functions (`class >> 16 == 0x03`: VGA, 3D and /// Display controllers) from vendor `0x10de` are returned. pub fn probe_nvidia_display_devices(sysfs: &Path) -> Vec { let mut out = Vec::new(); let dir = sysfs.join("bus/pci/devices"); let Ok(entries) = std::fs::read_dir(&dir) else { return out; }; for entry in entries.flatten() { let base = entry.path(); let read = |name: &str| -> Option { std::fs::read_to_string(base.join(name)) .ok() .map(|s| s.trim().to_string()) }; let (Some(class), Some(vendor), Some(device)) = (read("class"), read("vendor"), read("device")) else { continue; }; let parse = |s: &str| u32::from_str_radix(s.trim_start_matches("0x"), 16).ok(); let (Some(class), Some(vendor), Some(device)) = (parse(&class), parse(&vendor), parse(&device)) else { continue; }; if (class >> 16) != 0x03 || vendor != 0x10de { continue; } out.push(GpuInfo { vendor: GpuVendor::Nvidia, description: format!("NVIDIA display controller {vendor:04x}:{device:04x}"), pci_id: Some(format!("{vendor:04x}:{device:04x}")), pci_address: Some(entry.file_name().to_string_lossy().to_string()), }); } out.sort_by(|a, b| a.pci_id.cmp(&b.pci_id)); out } // --------------------------------------------------------------------------- // Disks // --------------------------------------------------------------------------- /// Parse `lsblk -P` output (`KEY="value" ...`) into a map. pub fn parse_pairs(line: &str) -> HashMap { let mut map = HashMap::new(); let bytes = line.as_bytes(); let mut i = 0; while i < bytes.len() { // skip whitespace while i < bytes.len() && bytes[i].is_ascii_whitespace() { i += 1; } let key_start = i; while i < bytes.len() && bytes[i] != b'=' { i += 1; } if i >= bytes.len() { break; } let key = line[key_start..i].to_string(); i += 1; // skip '=' if i >= bytes.len() || bytes[i] != b'"' { continue; } i += 1; let mut value = String::new(); while i < bytes.len() { match bytes[i] { b'\\' if i + 1 < bytes.len() => { value.push(bytes[i + 1] as char); i += 2; } b'"' => { i += 1; break; } c => { value.push(c as char); i += 1; } } } map.insert(key, value); } map } fn read_mounts() -> Vec<(String, String)> { let mut out = Vec::new(); if let Ok(text) = std::fs::read_to_string("/proc/mounts") { for line in text.lines() { let mut parts = line.split_whitespace(); if let (Some(src), Some(mp)) = (parts.next(), parts.next()) { out.push((src.to_string(), mp.to_string())); } } } out } fn read_cmdline() -> Vec { std::fs::read_to_string("/proc/cmdline") .map(|t| t.split_whitespace().map(str::to_string).collect()) .unwrap_or_default() } fn is_block_device(path: &str) -> bool { use std::os::unix::fs::FileTypeExt; std::fs::metadata(path) .map(|m| m.file_type().is_block_device()) .unwrap_or(false) } fn disk_kind(name: &str, path: &str) -> DiskKind { if name.starts_with("sr") || path.starts_with("/dev/sr") { DiskKind::Optical } else if name.starts_with("loop") || path.starts_with("/dev/loop") { DiskKind::Loop } else if name.starts_with("dm-") || path.starts_with("/dev/mapper") { DiskKind::DeviceMapper } else { DiskKind::Physical } } /// List child partition device paths for a disk. pub fn disk_partitions(runner: &dyn ProcessRunner, disk: &str) -> Vec { let out = capture(runner, "lsblk", &["-rno", "NAME", disk]); out.lines() .skip(1) .map(|l| l.trim()) .filter(|l| !l.is_empty()) .map(|name| format!("/dev/{name}")) .collect() } fn parent_disk(runner: &dyn ProcessRunner, dev: &str) -> String { if dev.starts_with("/dev/loop") || dev.starts_with("/dev/dm-") || dev.starts_with("/dev/mapper") || dev.starts_with("/dev/sr") { return dev.to_string(); } let out = capture(runner, "lsblk", &["-no", "PKNAME", dev]); match out.lines().next().map(str::trim).filter(|s| !s.is_empty()) { Some(pk) => format!("/dev/{pk}"), None => dev.to_string(), } } fn live_source_disks(runner: &dyn ProcessRunner) -> Vec { let mut sources: Vec = Vec::new(); for tok in read_cmdline() { if let Some((key, value)) = tok.split_once('=') { if matches!(key, "root" | "cdroot" | "boot") { sources.push(value.to_string()); } } } let mounts = read_mounts(); for mp in [ "/", "/run/initramfs", "/run/live", // Debian live-boot mounts the medium here; the ISO/medium device must // be identified so the installer can label and protect it. "/run/live/medium", "/run/live/rootfs", "/mnt/cdrom", "/mnt/live", "/lib/live", ] { if let Some((src, _)) = mounts.iter().find(|(_, m)| m == mp) { sources.push(src.clone()); } } let mut disks: Vec = Vec::new(); for src in sources { if !src.starts_with("/dev/") { continue; } if !is_block_device(&src) { continue; } let disk = parent_disk(runner, &src); if !disks.contains(&disk) { disks.push(disk); } } disks } pub fn probe_disks(runner: &dyn ProcessRunner) -> Vec { // `-b` is required: without it lsblk prints human units ("30G") and the // byte parse below silently yields 0, so every disk would report 0 B. let out = capture( runner, "lsblk", &["-bdn", "-P", "-o", "NAME,MODEL,SIZE,TRAN,RM,RO"], ); let mounts = read_mounts(); let live = live_source_disks(runner); let mut disks = Vec::new(); for line in out.lines() { let pairs = parse_pairs(line); let Some(name) = pairs.get("NAME") else { continue; }; let path = format!("/dev/{name}"); let kind = disk_kind(name, &path); let size = pairs .get("SIZE") .and_then(|s| s.parse::().ok()) .unwrap_or(0); let read_only = pairs.get("RO").map(|v| v == "1").unwrap_or(false); let removable = pairs.get("RM").map(|v| v == "1").unwrap_or(false); let model = pairs .get("MODEL") .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()); let transport = pairs .get("TRAN") .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()); // Mounted when the disk or any child partition is a mount source. let mounted = mounts .iter() .any(|(src, _)| src == &path || is_partition_of(&path, src)); let live_media = live.iter().any(|d| d == &path); disks.push(Disk { path, model, size_bytes: size, transport, removable, read_only, mounted, // lsblk only lists kernel block devices, so entries are block // devices by construction. The explicit check remains available to // callers that build a `Disk` from other sources. is_block_device: true, kind, live_media, }); } disks.sort_by(|a, b| a.path.cmp(&b.path)); disks } pub fn probe_disk_layout(runner: &dyn ProcessRunner, disk: &str) -> String { capture( runner, "lsblk", &["-o", "NAME,SIZE,TYPE,FSTYPE,LABEL,MOUNTPOINTS", disk], ) } /// True when `device` is a partition of `disk` (vda -> vda1, nvme0n1 -> nvme0n1p1). pub fn is_partition_of(disk: &str, device: &str) -> bool { let Some(rest) = device.strip_prefix(disk) else { return false; }; if rest.is_empty() { return false; } if rest.chars().all(|c| c.is_ascii_digit()) { return true; } if let Some(digits) = rest.strip_prefix('p') { return !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()); } false } pub fn blkid_uuid(runner: &dyn ProcessRunner, device: &str) -> Option { let out = capture(runner, "blkid", &["-s", "UUID", "-o", "value", device]); out.lines() .next() .map(str::trim) .filter(|s| !s.is_empty()) .map(str::to_string) } pub fn blkid_partlabel(runner: &dyn ProcessRunner, device: &str) -> Option { let out = capture(runner, "blkid", &["-s", "PARTLABEL", "-o", "value", device]); out.lines() .next() .map(str::trim) .filter(|s| !s.is_empty()) .map(str::to_string) } #[cfg(test)] mod tests { use super::*; use crate::command::{CommandOutput, RecordingRunner}; #[test] fn parse_pairs_handles_quotes_and_escapes() { let line = r#"NAME="vda" MODEL="QEMU HARDDISK" SIZE="32212254720" TRAN="virtio" RM="0" RO="0""#; let pairs = parse_pairs(line); assert_eq!(pairs.get("NAME").unwrap(), "vda"); assert_eq!(pairs.get("SIZE").unwrap(), "32212254720"); assert_eq!(pairs.get("MODEL").unwrap(), "QEMU HARDDISK"); } #[test] fn probe_disks_classifies_optical_as_protected() { let runner = RecordingRunner::new(); runner.set_response( "lsblk", CommandOutput { status: 0, success: true, stdout: b"NAME=\"sr0\" MODEL=\"QEMU DVD-ROM\" SIZE=\"1073741824\" TRAN=\"sata\" RM=\"1\" RO=\"1\"\nNAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }, ); let disks = probe_disks(&runner); let sr = disks.iter().find(|d| d.path == "/dev/sr0").unwrap(); assert!(sr.is_protected()); let vda = disks.iter().find(|d| d.path == "/dev/vda").unwrap(); assert!(!vda.is_protected()); // Regression: the byte size must survive parsing (lsblk needs -b). assert_eq!(vda.size_bytes, 32_212_254_720); assert_eq!(vda.size_human(), "30.0 GiB"); } #[test] fn disk_kind_classification() { assert_eq!(disk_kind("sr0", "/dev/sr0"), DiskKind::Optical); assert_eq!(disk_kind("loop0", "/dev/loop0"), DiskKind::Loop); assert_eq!(disk_kind("dm-0", "/dev/dm-0"), DiskKind::DeviceMapper); assert_eq!(disk_kind("vda", "/dev/vda"), DiskKind::Physical); } #[test] fn lspci_identity_extracts_the_vendor_device_pair() { let nvidia = "01:00.0 VGA compatible controller [0300]: NVIDIA Corporation GA104 [GeForce RTX 3070] [10de:2482] (rev a1)"; let (pair, address) = parse_lspci_identity(nvidia); assert_eq!(pair.as_deref(), Some("10de:2482")); assert_eq!(address.as_deref(), Some("01:00.0")); assert_eq!(classify_gpu(nvidia), GpuVendor::Nvidia); let intel = "00:02.0 VGA compatible controller [0300]: Intel Corporation Device [8086:9a60] (rev 01)"; assert_eq!(parse_lspci_identity(intel).0.as_deref(), Some("8086:9a60")); // A line without a numeric pair must not fabricate one. assert_eq!( parse_lspci_identity("00:00.0 Host bridge: Intel"), (None, Some("00:00.0".into())) ); } #[test] fn sysfs_scan_finds_only_nvidia_display_controllers() { let dir = tempfile::tempdir().unwrap(); let devices = dir.path().join("bus/pci/devices"); let write = |addr: &str, class: &str, vendor: &str, device: &str| { let d = devices.join(addr); std::fs::create_dir_all(&d).unwrap(); std::fs::write(d.join("class"), class).unwrap(); std::fs::write(d.join("vendor"), vendor).unwrap(); std::fs::write(d.join("device"), device).unwrap(); }; write("0000:01:00.0", "0x030000", "0x10de", "0x2482"); // NVIDIA's HDA audio function on the same card is not a display device. write("0000:01:00.1", "0x040300", "0x10de", "0x228b"); // An Intel display controller is left to the in-tree driver. write("0000:00:02.0", "0x030000", "0x8086", "0x9a60"); let found = probe_nvidia_display_devices(dir.path()); assert_eq!(found.len(), 1); assert_eq!(found[0].pci_id.as_deref(), Some("10de:2482")); assert_eq!(found[0].pci_address.as_deref(), Some("0000:01:00.0")); } }