use serde::{Deserialize, Serialize};
#[cfg(target_os = "windows")]
mod windows_speed;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UsbSpeed {
Low,
Full,
High,
Super,
SuperPlus,
SuperPlusx2,
Usb4,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UsbDeviceClass {
Audio,
Communication,
Hid,
Printer,
MassStorage,
Hub,
Video,
Wireless,
Vendor,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsbDevice {
pub address: String,
pub bus_number: Option<u8>,
pub port_number: Option<u8>,
pub vendor_id: Option<u16>,
pub product_id: Option<u16>,
pub manufacturer: Option<String>,
pub product: Option<String>,
pub description: Option<String>,
pub serial_number: Option<String>,
pub class: UsbDeviceClass,
pub speed: UsbSpeed,
}
fn class_from_code(code: u8) -> UsbDeviceClass {
match code {
0x01 => UsbDeviceClass::Audio,
0x02 => UsbDeviceClass::Communication,
0x03 => UsbDeviceClass::Hid,
0x07 => UsbDeviceClass::Printer,
0x08 => UsbDeviceClass::MassStorage,
0x09 => UsbDeviceClass::Hub,
0x0e => UsbDeviceClass::Video,
0xe0 => UsbDeviceClass::Wireless,
0xff => UsbDeviceClass::Vendor,
_ => UsbDeviceClass::Unknown,
}
}
#[cfg(target_os = "windows")]
fn class_from_device_ids(hardware: &[String], compatible: &[String]) -> Option<UsbDeviceClass> {
fn code_after(haystack: &str, marker: &str) -> Option<u8> {
let rest = haystack.split(marker).nth(1)?;
let hex: String = rest.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
(!hex.is_empty())
.then(|| u8::from_str_radix(&hex, 16).ok())
.flatten()
}
let upper: Vec<String> = compatible.iter().map(|i| i.to_uppercase()).collect();
for id in &upper {
if let Some(code) = code_after(id, "DEVCLASS_") {
if code != 0 {
return Some(class_from_code(code));
}
}
}
for id in &upper {
if let Some(code) = code_after(id, "&CLASS_") {
if code != 0 {
return Some(class_from_code(code));
}
}
}
if hardware
.iter()
.chain(compatible.iter())
.map(|id| id.to_uppercase())
.any(|id| id.contains("ROOT_HUB") || id.ends_with("_HUB"))
{
return Some(UsbDeviceClass::Hub);
}
None
}
fn normalise_address(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for ch in raw.chars() {
if ch.is_ascii_alphanumeric() {
out.extend(ch.to_lowercase());
} else if !out.ends_with('_') {
out.push('_');
}
}
out.trim_matches('_').to_string()
}
pub struct UsbMonitor {
devices: Vec<UsbDevice>,
}
impl UsbMonitor {
pub fn new() -> Result<Self, crate::error::IronError> {
let mut monitor = Self {
devices: Vec::new(),
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), crate::error::IronError> {
self.devices.clear();
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
Ok(())
}
pub fn devices(&self) -> &[UsbDevice] {
&self.devices
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), crate::error::IronError> {
let wmi = Self::wmi_enumerate_usb();
if let Ok(devices) = &wmi {
self.devices.clone_from(devices);
}
if !self.devices.is_empty() {
return Ok(());
}
let registry = Self::registry_enumerate_usb();
if let Ok(devices) = ®istry {
self.devices.clone_from(devices);
}
match (wmi, registry) {
(Err(wmi_err), Err(registry_err)) => Err(crate::error::IronError::System(format!(
"no USB enumeration succeeded: WMI said {wmi_err}; the registry walk said \
{registry_err}"
))),
_ => Ok(()),
}
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), crate::error::IronError> {
use std::fs;
use std::path::Path;
let usb_path = Path::new("/sys/bus/usb/devices");
if usb_path.exists() {
let entries = fs::read_dir(usb_path).map_err(|e| {
crate::error::IronError::System(format!("cannot read {usb_path:?}: {e}"))
})?;
for entry in entries.flatten() {
if let Ok(name) = entry.file_name().into_string() {
if !name.contains('-') || name.contains(':') {
continue;
}
let path = entry.path();
let vendor_id =
read_usb_attr(&path, "idVendor").and_then(|v| u16::try_from(v).ok());
let product_id =
read_usb_attr(&path, "idProduct").and_then(|v| u16::try_from(v).ok());
let manufacturer = read_usb_string(&path, "manufacturer");
let product = read_usb_string(&path, "product");
let serial = read_usb_string(&path, "serial");
let speed = match read_usb_string(&path, "speed").as_deref() {
Some("1.5") => UsbSpeed::Low,
Some("12") => UsbSpeed::Full,
Some("480") => UsbSpeed::High,
Some("5000") => UsbSpeed::Super,
Some("10000") => UsbSpeed::SuperPlus,
Some("20000") => UsbSpeed::SuperPlusx2,
_ => UsbSpeed::Unknown,
};
let class_code = read_usb_attr(&path, "bDeviceClass");
let class = class_code
.and_then(|c| u8::try_from(c).ok())
.map(class_from_code)
.unwrap_or(UsbDeviceClass::Unknown);
let parts: Vec<&str> = name.split('-').collect();
let bus_number = parts.first().and_then(|s| s.parse().ok());
let port_number = parts
.get(1)
.and_then(|s| s.split('.').next())
.and_then(|s| s.parse().ok());
self.devices.push(UsbDevice {
address: normalise_address(&name),
bus_number,
port_number,
vendor_id,
product_id,
manufacturer,
product,
description: None,
serial_number: serial,
class,
speed,
});
}
}
}
Ok(())
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), crate::error::IronError> {
let stdout = crate::core::command::capture(
"system_profiler",
&["SPUSBDataType", "-detailLevel", "full"],
)?;
let mut current_name: Option<String> = None;
let mut current_vendor_id: Option<u16> = None;
let mut current_product_id: Option<u16> = None;
let mut current_manufacturer: Option<String> = None;
let mut current_serial: Option<String> = None;
let mut current_speed: UsbSpeed = UsbSpeed::Unknown;
let mut current_location = String::new();
let mut bus_number: Option<u8> = None;
let mut port_number: Option<u8> = None;
let mut device_idx: u8 = 0;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("USB") && !trimmed.is_empty() {
if let Some(name) = current_name.take() {
device_idx += 1;
self.devices.push(UsbDevice {
address: normalise_address(¤t_location),
bus_number,
port_number,
vendor_id: current_vendor_id,
product_id: current_product_id,
manufacturer: current_manufacturer.take(),
product: Some(name),
description: None,
serial_number: current_serial.take(),
class: UsbDeviceClass::Unknown,
speed: current_speed,
});
current_vendor_id = None;
current_product_id = None;
current_speed = UsbSpeed::Unknown;
current_location.clear();
}
current_name = Some(trimmed.trim_end_matches(':').to_string());
} else if let Some((key, val)) = trimmed.split_once(':') {
let key = key.trim();
let val = val.trim();
match key {
"Vendor ID" => {
if let Some(hex) = val
.strip_prefix("0x")
.and_then(|s| s.split_whitespace().next())
{
current_vendor_id = u16::from_str_radix(hex, 16).ok();
}
}
"Product ID" => {
if let Some(hex) = val
.strip_prefix("0x")
.and_then(|s| s.split_whitespace().next())
{
current_product_id = u16::from_str_radix(hex, 16).ok();
}
}
"Manufacturer" => {
current_manufacturer = Some(val.to_string());
}
"Serial Number" => {
current_serial = Some(val.to_string());
}
"Speed" => {
current_speed = speed_from_profiler(val);
}
"Location ID" => {
current_location = val.to_string();
if let Some(hex) = val
.strip_prefix("0x")
.and_then(|s| s.split_whitespace().next())
{
if let Ok(loc) = u32::from_str_radix(hex, 16) {
bus_number = Some(((loc >> 24) & 0xFF) as u8);
port_number = Some(((loc >> 20) & 0xF) as u8);
}
}
}
_ => {}
}
}
}
if let Some(name) = current_name.take() {
device_idx += 1;
self.devices.push(UsbDevice {
address: normalise_address(¤t_location),
bus_number,
port_number,
vendor_id: current_vendor_id,
product_id: current_product_id,
manufacturer: current_manufacturer.take(),
product: Some(name),
description: None,
serial_number: current_serial.take(),
class: UsbDeviceClass::Unknown,
speed: current_speed,
});
}
Ok(())
}
}
impl Default for UsbMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
devices: Vec::new(),
})
}
}
#[cfg(target_os = "windows")]
impl UsbMonitor {
fn wmi_enumerate_usb() -> Result<Vec<UsbDevice>, crate::error::IronError> {
use std::process::Command;
let mut devices = Vec::new();
let speeds = windows_speed::negotiated_speeds();
let output = Command::new("powershell")
.args([
"-NoProfile",
"-Command",
concat!(
"Get-CimInstance Win32_PnPEntity | ",
"Where-Object { $_.PNPDeviceID -like 'USB*' } | ",
"Select-Object Name, Manufacturer, PNPDeviceID, Description, ",
"Status, HardwareID, CompatibleID | ConvertTo-Json -Compress"
),
])
.output()
.map_err(|e| crate::error::IronError::Other(format!("WMI query failed: {}", e)))?;
if !output.status.success() {
return Err(crate::error::IronError::System(format!(
"WMI USB query exited with {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
let stdout = String::from_utf8_lossy(&output.stdout);
if stdout.trim().is_empty() {
return Ok(devices);
}
let json = serde_json::from_str::<serde_json::Value>(stdout.trim()).map_err(|e| {
crate::error::IronError::System(format!("WMI USB query output did not parse: {e}"))
})?;
let items = if json.is_array() {
json.as_array().cloned().unwrap_or_default()
} else {
vec![json]
};
for item in items.iter() {
let name = item.get("Name").and_then(|v| v.as_str()).unwrap_or("");
let manufacturer = item.get("Manufacturer").and_then(|v| v.as_str());
let pnp_id = item
.get("PNPDeviceID")
.and_then(|v| v.as_str())
.unwrap_or("");
let description = item.get("Description").and_then(|v| v.as_str());
let (vid, pid) = parse_vid_pid(pnp_id);
let string_array = |field: &str| -> Vec<String> {
item.get(field)
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default()
};
let hardware = string_array("HardwareID");
let compatible = string_array("CompatibleID");
let class =
class_from_device_ids(&hardware, &compatible).unwrap_or(UsbDeviceClass::Unknown);
let speed = speeds
.get(&pnp_id.to_uppercase())
.copied()
.unwrap_or(UsbSpeed::Unknown);
let serial = pnp_id
.split('\\')
.nth(2)
.filter(|s| s.len() > 4 && !s.contains('&'))
.map(|s| s.to_string());
devices.push(UsbDevice {
address: normalise_address(pnp_id),
bus_number: None,
port_number: None,
vendor_id: vid,
product_id: pid,
manufacturer: manufacturer.map(|s| s.to_string()),
product: if name.is_empty() {
None
} else {
Some(name.to_string())
},
description: description.map(|s| s.to_string()),
serial_number: serial,
class,
speed,
});
}
Ok(devices)
}
fn registry_enumerate_usb() -> Result<Vec<UsbDevice>, crate::error::IronError> {
use std::process::Command;
let mut devices = Vec::new();
let output = Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"Get-CimInstance Win32_USBControllerDevice | ForEach-Object { \
[PSCustomObject]@{Dependent=$_.Dependent.ToString()} } | ConvertTo-Json -Compress",
])
.output()
.map_err(|e| crate::error::IronError::Other(format!("Registry query failed: {}", e)))?;
if !output.status.success() {
return Err(crate::error::IronError::System(format!(
"registry USB query exited with {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
let stdout = String::from_utf8_lossy(&output.stdout);
if stdout.trim().is_empty() {
return Ok(devices);
}
let json = serde_json::from_str::<serde_json::Value>(stdout.trim()).map_err(|e| {
crate::error::IronError::System(format!("registry USB query output did not parse: {e}"))
})?;
let items = if json.is_array() {
json.as_array().cloned().unwrap_or_default()
} else {
vec![json]
};
for item in items.iter() {
let dep = item.get("Dependent").and_then(|v| v.as_str()).unwrap_or("");
let (vid, pid) = parse_vid_pid(dep);
if vid.is_some() || pid.is_some() {
devices.push(UsbDevice {
address: normalise_address(dep),
bus_number: None,
port_number: None,
vendor_id: vid,
product_id: pid,
manufacturer: None,
product: None,
description: None,
serial_number: None,
class: UsbDeviceClass::Unknown,
speed: UsbSpeed::Unknown,
});
}
}
Ok(devices)
}
}
#[cfg(target_os = "windows")]
pub(crate) fn parse_vid_pid(pnp_id: &str) -> (Option<u16>, Option<u16>) {
let upper = pnp_id.to_uppercase();
let vid = upper
.find("VID_")
.and_then(|i| u16::from_str_radix(&upper[i + 4..][..4.min(upper.len() - i - 4)], 16).ok());
let pid = upper
.find("PID_")
.and_then(|i| u16::from_str_radix(&upper[i + 4..][..4.min(upper.len() - i - 4)], 16).ok());
(vid, pid)
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn speed_from_profiler(val: &str) -> UsbSpeed {
if val.contains("480") {
UsbSpeed::High
} else if val.contains("20 Gb") {
UsbSpeed::SuperPlusx2
} else if val.contains("10 Gb") {
UsbSpeed::SuperPlus
} else if val.contains("5 Gb") {
UsbSpeed::Super
} else if val.contains("1.5") {
UsbSpeed::Low
} else if val.contains("12 Mb") {
UsbSpeed::Full
} else {
UsbSpeed::Unknown
}
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn parse_hex_attr(raw: &str) -> Option<u32> {
u32::from_str_radix(raw.trim(), 16).ok()
}
#[cfg(target_os = "linux")]
fn read_usb_attr(path: &std::path::Path, attr: &str) -> Option<u32> {
std::fs::read_to_string(path.join(attr))
.ok()
.and_then(|s| parse_hex_attr(&s))
}
#[cfg(target_os = "linux")]
fn read_usb_string(path: &std::path::Path, attr: &str) -> Option<String> {
std::fs::read_to_string(path.join(attr))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UsbEvent {
Connected(UsbDevice),
Disconnected(UsbDevice),
}
impl UsbMonitor {
pub fn poll_events(&mut self) -> Result<Vec<UsbEvent>, crate::error::IronError> {
let old_devices = self.devices.clone();
self.refresh()?;
let mut events = Vec::new();
for old in &old_devices {
if !self.devices.iter().any(|d| device_matches(d, old)) {
events.push(UsbEvent::Disconnected(old.clone()));
}
}
for new in &self.devices {
if !old_devices.iter().any(|d| device_matches(d, new)) {
events.push(UsbEvent::Connected(new.clone()));
}
}
Ok(events)
}
}
fn device_matches(a: &UsbDevice, b: &UsbDevice) -> bool {
a.vendor_id == b.vendor_id
&& a.product_id == b.product_id
&& a.bus_number == b.bus_number
&& a.port_number == b.port_number
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_usb_monitor_creation() {
match UsbMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_usb_monitor_devices() {
let monitor = UsbMonitor::new().unwrap();
let _devices = monitor.devices();
}
#[cfg(target_os = "windows")]
#[test]
fn an_entry_with_no_ids_is_not_given_zeros() {
assert_eq!(
parse_vid_pid(r"USB\ROOT_HUB30\9&EBA7CE&0&0"),
(None, None),
"a root hub carries no VID_ or PID_ at all"
);
assert_eq!(
parse_vid_pid(r"USB\VID_046D&PID_C548\5&2E6429FC&0&3"),
(Some(0x046d), Some(0xc548)),
"a real device's ids are read"
);
assert_eq!(
parse_vid_pid(r"USB\VID_0000&PID_0000\6&1"),
(Some(0), Some(0)),
"an id of literally 0000 is a value, not an absence"
);
}
#[test]
fn test_usb_device_serialization() {
let device = UsbDevice {
address: "1_4_2".into(),
bus_number: Some(1),
port_number: Some(2),
vendor_id: Some(0x1234),
product_id: Some(0x5678),
manufacturer: Some("Test Manufacturer".to_string()),
product: Some("Test Product".to_string()),
description: None,
serial_number: Some("ABC123".to_string()),
class: UsbDeviceClass::MassStorage,
speed: UsbSpeed::High,
};
let json = serde_json::to_string(&device).unwrap();
let deserialized: UsbDevice = serde_json::from_str(&json).unwrap();
assert_eq!(device.vendor_id, deserialized.vendor_id);
assert_eq!(device.product_id, deserialized.product_id);
assert_eq!(device.serial_number, deserialized.serial_number);
}
#[test]
fn test_usb_speed_variants() {
let speeds = [
UsbSpeed::Low,
UsbSpeed::Full,
UsbSpeed::High,
UsbSpeed::Super,
UsbSpeed::SuperPlus,
UsbSpeed::SuperPlusx2,
UsbSpeed::Usb4,
UsbSpeed::Unknown,
];
for speed in speeds {
let json = serde_json::to_string(&speed).unwrap();
let deserialized: UsbSpeed = serde_json::from_str(&json).unwrap();
assert_eq!(speed, deserialized);
}
}
#[cfg(target_os = "windows")]
#[test]
fn a_root_hub_is_a_hub_by_the_identifier_windows_puts_in_its_hardware_ids() {
let hardware = [
r"USB\ROOT_HUB30&VID1022&PID43FD&REV0001".to_string(),
r"USB\ROOT_HUB30&VID1022&PID43FD".to_string(),
r"USB\ROOT_HUB30".to_string(),
];
assert_eq!(
class_from_device_ids(&hardware, &[]),
Some(UsbDeviceClass::Hub),
"a root hub declares itself in its hardware ids and carries no \
compatible ids at all"
);
}
#[cfg(target_os = "windows")]
#[test]
fn an_interface_class_still_wins_over_the_hardware_ids_beside_it() {
let hardware = [
r"USB\VID_046D&PID_C548&REV_0503&MI_01".to_string(),
r"USB\VID_046D&PID_C548&MI_01".to_string(),
];
let compatible = [
r"USB\COMPAT_VID_046d&Class_03&SubClass_01&Prot_02".to_string(),
r"USB\Class_03".to_string(),
];
assert_eq!(
class_from_device_ids(&hardware, &compatible),
Some(UsbDeviceClass::Hid)
);
}
#[cfg(target_os = "windows")]
#[test]
fn a_composite_parent_and_a_usbstor_disk_both_decline() {
let composite_hw = [r"USB\VID_046D&PID_C548&REV_0503".to_string()];
let composite_co = [
r"USB\COMPAT_VID_046D&DevClass_00&SubClass_00&Prot00".to_string(),
r"USB\DevClass_00".to_string(),
r"USB\COMPOSITE".to_string(),
];
assert_eq!(
class_from_device_ids(&composite_hw, &composite_co),
None,
"class 00 is the device saying its interfaces answer this, not a class"
);
let stor_hw = [
r"USBSTOR\DiskLinux___File-Stor_Gadget0515".to_string(),
r"USBSTOR\GenDisk".to_string(),
];
let stor_co = [
r"USBSTOR\Disk".to_string(),
r"USBSTOR\RAW".to_string(),
"GenDisk".to_string(),
];
assert_eq!(
class_from_device_ids(&stor_hw, &stor_co),
None,
"a storage-stack child node has no USB descriptor to declare a class"
);
}
#[test]
fn test_usb_class_variants() {
let classes = [
UsbDeviceClass::Audio,
UsbDeviceClass::Communication,
UsbDeviceClass::Hid,
UsbDeviceClass::Printer,
UsbDeviceClass::MassStorage,
UsbDeviceClass::Hub,
UsbDeviceClass::Video,
UsbDeviceClass::Wireless,
UsbDeviceClass::Vendor,
UsbDeviceClass::Unknown,
];
for class in classes {
let json = serde_json::to_string(&class).unwrap();
let deserialized: UsbDeviceClass = serde_json::from_str(&json).unwrap();
assert_eq!(class, deserialized);
}
}
#[test]
fn profiler_speed_lines_map_to_their_generation() {
assert_eq!(speed_from_profiler("480 Mb/s"), UsbSpeed::High);
assert_eq!(speed_from_profiler("12 Mb/s"), UsbSpeed::Full);
assert_eq!(speed_from_profiler("1.5 Mb/s"), UsbSpeed::Low);
assert_eq!(speed_from_profiler("5 Gb/s"), UsbSpeed::Super);
assert_eq!(speed_from_profiler("10 Gb/s"), UsbSpeed::SuperPlus);
assert_eq!(speed_from_profiler("20 Gb/s"), UsbSpeed::SuperPlusx2);
assert_eq!(speed_from_profiler("40 Gb/s"), UsbSpeed::Unknown);
}
#[test]
fn hex_attr_is_none_when_not_hex() {
assert_eq!(parse_hex_attr("046d\n"), Some(0x046d));
assert_eq!(parse_hex_attr(""), None);
assert_eq!(parse_hex_attr("not-hex"), None);
}
}