Fichiers
verifetat/src-tauri/src/smart_reader.rs
T
2026-10-11 01:55:32 +02:00

1070 lignes
41 KiB
Rust

use crate::models::{
BusProtocol, DiskInfo, DriveType, RawNvmeHealth, RawSmartAttribute, SmartAttributes,
};
use std::process::Command;
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::{CloseHandle, GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
};
use windows_sys::Win32::System::IO::DeviceIoControl;
use windows_sys::Win32::Security::{GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
// --- Win32 IOCTL Constants ---
const IOCTL_STORAGE_QUERY_PROPERTY: u32 = 0x002D1400;
const IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: u32 = 0x000700A0;
const IOCTL_DISK_GET_LENGTH_INFO: u32 = 0x0007405C;
const _SMART_GET_VERSION: u32 = 0x00074080;
const SMART_RCV_DRIVE_DATA: u32 = 0x0007C088;
const STORAGE_DEVICE_PROPERTY: u32 = 0;
const STORAGE_DEVICE_SEEK_PENALTY_PROPERTY: u32 = 7;
const STORAGE_DEVICE_PROTOCOL_SPECIFIC_PROPERTY: u32 = 18;
const STORAGE_DEVICE_PROTOCOL_NVME: u32 = 17;
const NVME_DATA_TYPE_LOG_PAGE: u32 = 1;
const NVME_LOG_PAGE_HEALTH_INFO: u32 = 2;
#[repr(C)]
struct StoragePropertyQuery {
property_id: u32,
query_type: u32,
additional_parameters: [u8; 1],
}
#[repr(C)]
struct StorageDeviceDescriptor {
version: u32,
size: u32,
device_type: u8,
device_type_modifier: u8,
removable_media: u8,
command_queueing: u8,
vendor_id_offset: u32,
product_id_offset: u32,
product_revision_offset: u32,
serial_number_offset: u32,
bus_type: u32,
raw_properties_length: u32,
raw_device_properties: [u8; 1],
}
#[repr(C)]
struct DeviceSeekPenaltyDescriptor {
version: u32,
size: u32,
incurs_seek_penalty: u8,
}
#[repr(C)]
struct StorageProtocolSpecificData {
protocol_type: u32,
data_type: u32,
protocol_data_request_value: u32,
protocol_data_request_sub_value: u32,
protocol_data_offset: u32,
protocol_data_length: u32,
fixed_protocol_return_data: u32,
protocol_data_request_sub_value2: u32,
protocol_data_request_sub_value3: u32,
protocol_data_request_sub_value4: u32,
}
#[repr(C, packed)]
struct IdeRegs {
b_features_reg: u8,
b_sector_count_reg: u8,
b_sector_number_reg: u8,
b_cyl_low_reg: u8,
b_cyl_high_reg: u8,
b_drive_head_reg: u8,
b_command_reg: u8,
b_reserved: u8,
}
#[repr(C, packed)]
struct SendCmdInParams {
c_buffer_size: u32,
ir_drive_regs: IdeRegs,
b_drive_number: u8,
b_reserved: [u8; 3],
dw_reserved: [u32; 4],
b_buffer: [u8; 1],
}
#[repr(C, packed)]
struct DriverStatus {
b_driver_error: u8,
b_ide_status: u8,
b_reserved: [u8; 2],
dw_reserved: [u32; 2],
}
#[repr(C, packed)]
struct SendCmdOutParams {
c_buffer_size: u32,
driver_status: DriverStatus,
b_buffer: [u8; 512],
}
pub struct SmartReader;
impl SmartReader {
/// Vérifie si le processus actuel dispose des privilèges Administrateur (requis pour IOCTL SMART direct)
pub fn is_elevated() -> bool {
unsafe {
let mut token: HANDLE = null_mut();
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) != 0 {
let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
let mut size = 0u32;
let res = GetTokenInformation(
token,
TokenElevation,
&mut elevation as *mut _ as *mut _,
std::mem::size_of::<TOKEN_ELEVATION>() as u32,
&mut size,
);
CloseHandle(token);
return res != 0 && elevation.TokenIsElevated != 0;
}
}
false
}
/// Formate des octets en Go ou To
pub fn format_size(bytes: u64) -> String {
let gb = (bytes as f64) / 1_000_000_000.0;
if gb >= 1000.0 {
let tb = gb / 1000.0;
format!("{:.2} To", tb)
} else {
format!("{:.1} Go", gb)
}
}
/// Convertit le BusType Win32 en enum BusProtocol
fn parse_bus_type(bus_type: u32) -> BusProtocol {
match bus_type {
11 => BusProtocol::Sata,
17 => BusProtocol::Nvme,
7 => BusProtocol::Usb,
1 => BusProtocol::Scsi,
10 => BusProtocol::Sas,
3 => BusProtocol::Ata,
8 => BusProtocol::Raid,
_ => BusProtocol::Unknown,
}
}
/// Collecte les informations de tous les disques physiques connectés au système
pub fn scan_disks() -> Vec<DiskInfo> {
let mut disks = Vec::new();
let wmi_data = Self::fetch_wmi_disks_info();
// On teste les PhysicalDrive de 0 à 31
for i in 0..32 {
let drive_path = format!(r"\\.\PhysicalDrive{}", i);
let drive_path_w: Vec<u16> = drive_path.encode_utf16().chain(std::iter::once(0)).collect();
let handle = unsafe {
CreateFileW(
drive_path_w.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
null_mut(),
OPEN_EXISTING,
0,
null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
// Essai en lecture seule si échec en lecture/écriture
let handle_ro = unsafe {
CreateFileW(
drive_path_w.as_ptr(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
null_mut(),
OPEN_EXISTING,
0,
null_mut(),
)
};
if handle_ro == INVALID_HANDLE_VALUE {
// Si WMI a trouvé ce disque, on l'utilise
if let Some(wmi_disk) = wmi_data.iter().find(|d| d.index == i) {
disks.push(wmi_disk.clone());
}
continue;
} else {
let disk = Self::inspect_drive(handle_ro, i, &wmi_data);
disks.push(disk);
unsafe { CloseHandle(handle_ro) };
}
} else {
let disk = Self::inspect_drive(handle, i, &wmi_data);
disks.push(disk);
unsafe { CloseHandle(handle) };
}
}
// Si aucun disque n'a pu être ouvert par CreateFile (ex: permissions restreintes), on utilise la totalité des disques WMI
if disks.is_empty() && !wmi_data.is_empty() {
return wmi_data;
}
disks
}
/// Inspecte un disque physique via ses descripteurs IOCTL et ses registres SMART
fn inspect_drive(handle: HANDLE, index: u32, wmi_data: &[DiskInfo]) -> DiskInfo {
let wmi_match = wmi_data.iter().find(|d| d.index == index);
// 1. Détection modèle, numéro de série et bus via StorageDeviceProperty
let mut model = String::new();
let mut serial = String::new();
let mut bus_protocol = BusProtocol::Unknown;
let mut query = StoragePropertyQuery {
property_id: STORAGE_DEVICE_PROPERTY,
query_type: 0,
additional_parameters: [0],
};
let mut buffer = [0u8; 1024];
let mut bytes_returned = 0u32;
let success = unsafe {
DeviceIoControl(
handle,
IOCTL_STORAGE_QUERY_PROPERTY,
&mut query as *mut _ as *mut _,
std::mem::size_of::<StoragePropertyQuery>() as u32,
buffer.as_mut_ptr() as *mut _,
buffer.len() as u32,
&mut bytes_returned,
null_mut(),
)
};
if success != 0 && bytes_returned >= std::mem::size_of::<StorageDeviceDescriptor>() as u32 {
let desc = unsafe { &*(buffer.as_ptr() as *const StorageDeviceDescriptor) };
bus_protocol = Self::parse_bus_type(desc.bus_type);
if desc.product_id_offset > 0 && (desc.product_id_offset as usize) < buffer.len() {
let bytes = &buffer[desc.product_id_offset as usize..];
if let Some(pos) = bytes.iter().position(|&b| b == 0) {
model = String::from_utf8_lossy(&bytes[..pos]).trim().to_string();
}
}
if desc.serial_number_offset > 0 && (desc.serial_number_offset as usize) < buffer.len() {
let bytes = &buffer[desc.serial_number_offset as usize..];
if let Some(pos) = bytes.iter().position(|&b| b == 0) {
serial = String::from_utf8_lossy(&bytes[..pos]).trim().to_string();
}
}
}
// 2. Détection SSD vs HDD via Seek Penalty
let mut incurs_seek_penalty = true;
let mut seek_query = StoragePropertyQuery {
property_id: STORAGE_DEVICE_SEEK_PENALTY_PROPERTY,
query_type: 0,
additional_parameters: [0],
};
let mut seek_desc = DeviceSeekPenaltyDescriptor {
version: 0,
size: 0,
incurs_seek_penalty: 1,
};
let seek_success = unsafe {
DeviceIoControl(
handle,
IOCTL_STORAGE_QUERY_PROPERTY,
&mut seek_query as *mut _ as *mut _,
std::mem::size_of::<StoragePropertyQuery>() as u32,
&mut seek_desc as *mut _ as *mut _,
std::mem::size_of::<DeviceSeekPenaltyDescriptor>() as u32,
&mut bytes_returned,
null_mut(),
)
};
if seek_success != 0 {
incurs_seek_penalty = seek_desc.incurs_seek_penalty != 0;
}
// 3. Détermination du type de lecteur
let drive_type = if bus_protocol == BusProtocol::Nvme {
DriveType::Nvme
} else if !incurs_seek_penalty {
DriveType::Ssd
} else {
DriveType::Hdd
};
// 4. Capacité du disque : méthode 1 via IOCTL_DISK_GET_LENGTH_INFO (directe et précise)
let mut size_bytes: u64 = 0;
let mut length_info = 0i64;
let length_success = unsafe {
DeviceIoControl(
handle,
IOCTL_DISK_GET_LENGTH_INFO,
null_mut(),
0,
&mut length_info as *mut _ as *mut _,
std::mem::size_of::<i64>() as u32,
&mut bytes_returned,
null_mut(),
)
};
if length_success != 0 && length_info > 0 {
size_bytes = length_info as u64;
} else {
// Méthode 2 via DISK_GEOMETRY_EX (DiskSize est à l'offset 24..32, après DISK_GEOMETRY de 24 octets)
let mut geom_buffer = [0u8; 256];
let geom_success = unsafe {
DeviceIoControl(
handle,
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
null_mut(),
0,
geom_buffer.as_mut_ptr() as *mut _,
geom_buffer.len() as u32,
&mut bytes_returned,
null_mut(),
)
};
if geom_success != 0 && bytes_returned >= 32 {
let disk_size_bytes = &geom_buffer[24..32];
let s = u64::from_le_bytes(disk_size_bytes.try_into().unwrap_or([0; 8]));
if s > 0 {
size_bytes = s;
}
}
}
// 5. Lecture des attributs SMART
let mut smart = SmartAttributes {
power_on_hours: 0,
power_cycles: 0,
reallocated_sectors: 0,
pending_sectors: 0,
uncorrectable_sectors: 0,
crc_errors: 0,
temperature_celsius: None,
ssd_wear_percentage: None,
nvme_available_spare: None,
nvme_critical_warning: None,
unsafe_shutdowns: None,
raw_ata_attributes: Vec::new(),
raw_nvme_health: None,
};
// Tentative de lecture NVMe ou SATA ATA
if bus_protocol == BusProtocol::Nvme {
Self::read_nvme_smart(handle, &mut smart);
} else {
Self::read_ata_smart(handle, &mut smart);
}
// Fallback / Enrichissement avec WMI si disponible
let mut rpm = None;
let mut is_system_drive = false;
let mut mount_points = Vec::new();
if let Some(wmi) = wmi_match {
if model.is_empty() {
model = wmi.model.clone();
}
if serial.is_empty() {
serial = wmi.serial_number.clone();
}
if size_bytes == 0 {
size_bytes = wmi.size_bytes;
}
if bus_protocol == BusProtocol::Unknown {
bus_protocol = wmi.bus_protocol.clone();
}
rpm = wmi.rpm;
is_system_drive = wmi.is_system_drive;
mount_points = wmi.mount_points.clone();
// Si les attributs SMART bas niveau n'ont pas pu être lus (ex: permissions), enrichir avec WMI
if smart.power_on_hours == 0 && wmi.smart.power_on_hours > 0 {
smart = wmi.smart.clone();
}
}
if drive_type == DriveType::Hdd && rpm.is_none() {
rpm = Some(7200); // Standard par défaut si non spécifié
} else if drive_type == DriveType::Ssd || drive_type == DriveType::Nvme {
rpm = None; // Pas de rotation pour mémoire flash
}
if model.is_empty() {
model = format!("Disque Physique {}", index);
}
let size_formatted = Self::format_size(size_bytes);
DiskInfo {
device_id: format!(r"\\.\PhysicalDrive{}", index),
index,
model,
serial_number: serial,
size_bytes,
size_formatted,
drive_type,
bus_protocol,
rpm,
is_system_drive,
mount_points,
smart,
}
}
/// Lecture du log SMART / Health NVMe
fn read_nvme_smart(handle: HANDLE, smart: &mut SmartAttributes) {
let buffer_size = 4096;
let mut in_buffer = vec![0u8; buffer_size];
#[repr(C)]
struct ProtocolQuery {
query: StoragePropertyQuery,
protocol: StorageProtocolSpecificData,
}
let mut p_query = ProtocolQuery {
query: StoragePropertyQuery {
property_id: STORAGE_DEVICE_PROTOCOL_SPECIFIC_PROPERTY,
query_type: 0,
additional_parameters: [0],
},
protocol: StorageProtocolSpecificData {
protocol_type: STORAGE_DEVICE_PROTOCOL_NVME,
data_type: NVME_DATA_TYPE_LOG_PAGE,
protocol_data_request_value: NVME_LOG_PAGE_HEALTH_INFO,
protocol_data_request_sub_value: 0,
protocol_data_offset: std::mem::size_of::<StorageProtocolSpecificData>() as u32,
protocol_data_length: 512,
fixed_protocol_return_data: 0,
protocol_data_request_sub_value2: 0,
protocol_data_request_sub_value3: 0,
protocol_data_request_sub_value4: 0,
},
};
let mut bytes_returned = 0u32;
let success = unsafe {
DeviceIoControl(
handle,
IOCTL_STORAGE_QUERY_PROPERTY,
&mut p_query as *mut _ as *mut _,
std::mem::size_of::<ProtocolQuery>() as u32,
in_buffer.as_mut_ptr() as *mut _,
in_buffer.len() as u32,
&mut bytes_returned,
null_mut(),
)
};
if success != 0 && bytes_returned >= 512 {
let offset = (std::mem::size_of::<StorageProtocolSpecificData>()).min(in_buffer.len() - 512);
let log = &in_buffer[offset..];
// Byte 0: Critical warning
smart.nvme_critical_warning = Some(log[0] as u32);
// Bytes 1..2: Température en Kelvin
let temp_kelvin = u16::from_le_bytes([log[1], log[2]]);
if temp_kelvin >= 273 && temp_kelvin <= 373 {
smart.temperature_celsius = Some((temp_kelvin as i32) - 273);
}
// Byte 3: Available spare (%)
smart.nvme_available_spare = Some(log[3] as u32);
// Byte 5: Percentage used (% d'usure)
smart.ssd_wear_percentage = Some(log[5] as u32);
// Bytes 112..128: Power cycles (16 octets, on prend les 8 premiers)
if log.len() >= 128 {
let cycles = u64::from_le_bytes(log[112..120].try_into().unwrap_or([0; 8]));
smart.power_cycles = cycles;
}
// Bytes 128..144: Power on hours
if log.len() >= 144 {
let hours = u64::from_le_bytes(log[128..136].try_into().unwrap_or([0; 8]));
smart.power_on_hours = hours;
}
// Bytes 144..160: Unsafe shutdowns
if log.len() >= 160 {
let shutdowns = u64::from_le_bytes(log[144..152].try_into().unwrap_or([0; 8]));
smart.unsafe_shutdowns = Some(shutdowns);
}
// Bytes 160..176: Media and data integrity errors
if log.len() >= 176 {
let media_errors = u64::from_le_bytes(log[160..168].try_into().unwrap_or([0; 8]));
smart.uncorrectable_sectors = media_errors;
}
// Capture intégrale de la télémétrie brute NVMe
if log.len() >= 512 {
let raw_nvme = RawNvmeHealth {
critical_warning: log[0],
temperature_celsius: smart.temperature_celsius.unwrap_or(0),
available_spare_percentage: log[3],
percentage_used: log[5],
data_units_read: u128::from_le_bytes(log[32..48].try_into().unwrap_or([0; 16])),
data_units_written: u128::from_le_bytes(log[48..64].try_into().unwrap_or([0; 16])),
host_read_commands: u128::from_le_bytes(log[64..80].try_into().unwrap_or([0; 16])),
host_write_commands: u128::from_le_bytes(log[80..96].try_into().unwrap_or([0; 16])),
controller_busy_time_minutes: u128::from_le_bytes(log[96..112].try_into().unwrap_or([0; 16])),
power_cycles: u128::from_le_bytes(log[112..128].try_into().unwrap_or([0; 16])),
power_on_hours: u128::from_le_bytes(log[128..144].try_into().unwrap_or([0; 16])),
unsafe_shutdowns: u128::from_le_bytes(log[144..160].try_into().unwrap_or([0; 16])),
media_and_data_integrity_errors: u128::from_le_bytes(log[160..176].try_into().unwrap_or([0; 16])),
number_of_error_information_log_entries: u128::from_le_bytes(log[176..192].try_into().unwrap_or([0; 16])),
};
smart.raw_nvme_health = Some(raw_nvme);
}
}
}
/// Nom officiel de l'attribut ATA SMART standardisé
pub fn get_ata_attribute_name(id: u8) -> &'static str {
match id {
0x01 => "Read Error Rate",
0x02 => "Throughput Performance",
0x03 => "Spin-Up Time",
0x04 => "Start/Stop Count",
0x05 => "Reallocated Sectors Count",
0x07 => "Seek Error Rate",
0x08 => "Seek Time Performance",
0x09 => "Power-On Hours",
0x0A => "Spin Retry Count",
0x0B => "Calibration Retry Count",
0x0C => "Power Cycle Count",
0x0D => "Soft Read Error Rate",
0xAA => "Available Reserved Space / Bad Blocks",
0xAB => "Program Fail Count",
0xAC => "Erase Fail Count",
0xAD => "Average P/E Cycle Count",
0xAE => "Unexpected Power Loss Count",
0xAF => "Power Loss Protection Failure",
0xB1 => "Wear Range Delta",
0xB2 => "Used Reserved Block Count",
0xB4 => "Remaining Reserved Block Count",
0xB7 => "SATA Downshift Error Count",
0xB8 => "End-to-End Error / IOEDC",
0xBB => "Reported Uncorrectable Errors",
0xBC => "Command Timeout",
0xBD => "High Fly Writes",
0xBE => "Airflow Temperature",
0xBF => "G-Sense Shock Error Rate",
0xC0 => "Power-Off Retract Count",
0xC1 => "Load/Unload Cycle Count",
0xC2 => "Temperature",
0xC3 => "Hardware ECC Recovered",
0xC4 => "Reallocation Event Count",
0xC5 => "Current Pending Sector Count",
0xC6 => "Offline Uncorrectable Sector Count",
0xC7 => "UltraDMA CRC Error Count",
0xC8 => "Multi-Zone Error Rate",
0xCA => "Percentage Life Used",
0xDC => "Disk Shift",
0xE7 => "SSD Life Left",
0xE8 => "Endurance Remaining / Available Reserved Space",
0xE9 => "Media Wearout Indicator",
0xEA => "SLC NAND Writes",
0xF1 => "Total Host Writes (GB/LBA)",
0xF2 => "Total Host Reads (GB/LBA)",
0xF9 => "Total NAND Writes (GB)",
_ => "Attribut Constructeur",
}
}
/// Lecture de la table SMART ATA pour disques SATA (HDD et SSD SATA)
fn read_ata_smart(handle: HANDLE, smart: &mut SmartAttributes) {
let mut cmd_in = SendCmdInParams {
c_buffer_size: 512,
ir_drive_regs: IdeRegs {
b_features_reg: 0xD0, // SMART READ DATA
b_sector_count_reg: 1,
b_sector_number_reg: 1,
b_cyl_low_reg: 0x4F,
b_cyl_high_reg: 0xC2,
b_drive_head_reg: 0xA0,
b_command_reg: 0xB0, // SMART_CMD
b_reserved: 0,
},
b_drive_number: 0,
b_reserved: [0; 3],
dw_reserved: [0; 4],
b_buffer: [0; 1],
};
let mut cmd_out: SendCmdOutParams = unsafe { std::mem::zeroed() };
let mut bytes_returned = 0u32;
let success = unsafe {
DeviceIoControl(
handle,
SMART_RCV_DRIVE_DATA,
&mut cmd_in as *mut _ as *mut _,
std::mem::size_of::<SendCmdInParams>() as u32,
&mut cmd_out as *mut _ as *mut _,
std::mem::size_of::<SendCmdOutParams>() as u32,
&mut bytes_returned,
null_mut(),
)
};
if success != 0 && bytes_returned >= 512 {
let buf = &cmd_out.b_buffer;
let mut e9_wear: Option<u32> = None;
let mut e7_wear: Option<u32> = None;
let mut ca_wear: Option<u32> = None;
let mut a9_wear: Option<u32> = None;
let mut b4_wear: Option<u32> = None;
// Chaque attribut SMART fait 12 octets, à partir de l'offset 2
// 30 attributs possibles (offset 2 à 362)
for i in 0..30 {
let offset = 2 + (i * 12);
if offset + 12 > buf.len() {
break;
}
let attr_id = buf[offset];
if attr_id == 0 {
continue;
}
let current_val = buf[offset + 3];
let worst_val = buf[offset + 4];
// Valeur brute sur 6 octets (offset + 5 à offset + 10)
let raw_val = u64::from_le_bytes([
buf[offset + 5],
buf[offset + 6],
buf[offset + 7],
buf[offset + 8],
buf[offset + 9],
buf[offset + 10],
0,
0,
]);
// Stockage de l'attribut complet pour export JSON et affichage CLI
smart.raw_ata_attributes.push(RawSmartAttribute {
id: attr_id,
id_hex: format!("0x{:02X}", attr_id),
name: Self::get_ata_attribute_name(attr_id).to_string(),
current: current_val,
worst: worst_val,
threshold: None,
raw_value: raw_val,
raw_hex: format!("{:012X}", raw_val),
});
match attr_id {
0x05 => smart.reallocated_sectors = raw_val,
0x09 => smart.power_on_hours = raw_val,
0x0C => smart.power_cycles = raw_val,
0xC5 => smart.pending_sectors = raw_val,
0xC6 => smart.uncorrectable_sectors = raw_val,
0xBB => {
if smart.uncorrectable_sectors == 0 && raw_val > 0 {
smart.uncorrectable_sectors = raw_val;
}
}
0xC7 => smart.crc_errors = raw_val,
0xAE => smart.unsafe_shutdowns = Some(raw_val),
0xC2 | 0xBE => {
let temp = (raw_val & 0xFF) as i32;
if temp > 0 && temp < 100 {
smart.temperature_celsius = Some(temp);
}
}
0xE9 => {
// Media Wearout Indicator (SanDisk, Intel, Crucial, etc.)
// La valeur courante normalisée représente la santé restante de 100 à 0
if current_val > 0 && current_val <= 100 {
e9_wear = Some(100 - (current_val as u32));
}
}
0xE7 => {
// SSD Life Left (Kingston, Samsung, Crucial, etc.)
if current_val > 0 && current_val <= 100 {
e7_wear = Some(100 - (current_val as u32));
} else {
let r = (raw_val & 0xFF) as u32;
if r <= 100 {
e7_wear = Some(100 - r);
}
}
}
0xCA => {
// Percentage Life Used (Micron, etc.)
let r = (raw_val & 0xFF) as u32;
if r <= 100 {
ca_wear = Some(r);
}
}
0xA9 => {
// Percentage Lifetime Remaining
if current_val > 0 && current_val <= 100 {
a9_wear = Some(100 - (current_val as u32));
}
}
0xB4 => {
// Remaining Reserved Block Count
if current_val > 0 && current_val <= 100 {
b4_wear = Some(100 - (current_val as u32));
}
}
_ => {}
}
}
// Résolution prioritaire de l'usure Flash
// 0xB8 est explicitement exclu car il s'agit d'End-to-End Error / IOEDC (zéro erreur = parfait)
smart.ssd_wear_percentage = e9_wear
.or(e7_wear)
.or(ca_wear)
.or(a9_wear)
.or(b4_wear);
}
}
/// Résout un disque selon une lettre (ex: "C:", "D", "c"), un index (ex: "0", "1"),
/// ou un chemin (ex: "\\.\PhysicalDrive0", "PhysicalDrive0")
pub fn resolve_disk<'a>(target: &str, disks: &'a [DiskInfo]) -> Option<&'a DiskInfo> {
let trimmed = target.trim().trim_matches('"').trim_matches('\'');
let lower = trimmed.to_lowercase();
// 1. Essai par index numérique direct (ex: "0", "1")
if let Ok(idx) = lower.parse::<u32>() {
if let Some(d) = disks.iter().find(|d| d.index == idx) {
return Some(d);
}
}
// 2. Essai par lettre de lecteur (ex: "C:", "C", "D:", "d")
let letter_normalized = if lower.len() == 1 && lower.chars().next().map_or(false, |c| c.is_ascii_alphabetic()) {
format!("{}:", lower.to_uppercase())
} else if lower.len() == 2 && lower.ends_with(':') && lower.chars().next().map_or(false, |c| c.is_ascii_alphabetic()) {
lower.to_uppercase()
} else if lower.len() >= 2 && lower.chars().nth(1) == Some(':') {
lower[..2].to_uppercase()
} else {
String::new()
};
if !letter_normalized.is_empty() {
for d in disks {
if d.mount_points.iter().any(|m| m.eq_ignore_ascii_case(&letter_normalized)) {
return Some(d);
}
}
if letter_normalized == "C:" {
if let Some(d) = disks.iter().find(|d| d.is_system_drive) {
return Some(d);
}
}
}
// 3. Essai par nom de device (ex: "\\.\PhysicalDrive0", "PhysicalDrive0")
for d in disks {
if d.device_id.eq_ignore_ascii_case(trimmed)
|| d.device_id.replace(r"\\.\", "").eq_ignore_ascii_case(trimmed)
{
return Some(d);
}
}
// 4. Essai par numéro de série
for d in disks {
if !d.serial_number.is_empty() && d.serial_number.eq_ignore_ascii_case(trimmed) {
return Some(d);
}
}
None
}
/// Récupère des données de disques via PowerShell CIM / WMI
fn fetch_wmi_disks_info() -> Vec<DiskInfo> {
let mut list = Vec::new();
let ps_script = r#"
$ErrorActionPreference = 'SilentlyContinue'
$sysDisk = -1
try {
$driveLetter = (Get-CimInstance Win32_OperatingSystem).SystemDrive.Replace(':','')
$sysDisk = (Get-Partition -DriveLetter $driveLetter).DiskNumber
} catch {}
$diskPartitions = @{}
try {
Get-Partition | Where-Object { $_.DriveLetter } | ForEach-Object {
$dn = [int]$_.DiskNumber
if (-not $diskPartitions.ContainsKey($dn)) {
$diskPartitions[$dn] = @()
}
$diskPartitions[$dn] += ($_.DriveLetter + ':')
}
} catch {}
$disks = Get-CimInstance -Namespace root\Microsoft\Windows\Storage -ClassName MSFT_PhysicalDisk
$arr = @()
if ($disks) {
foreach ($d in $disks) {
$devId = [int]$d.DeviceId
$letters = if ($diskPartitions.ContainsKey($devId)) { $diskPartitions[$devId] } else { @() }
$arr += [PSCustomObject]@{
DeviceId = $devId
FriendlyName = [string]$d.FriendlyName
SerialNumber = if ($d.SerialNumber) { ($d.SerialNumber.ToString()).Trim() } else { '' }
Size = [string]$d.Size
MediaType = [string]$d.MediaType
BusType = [string]$d.BusType
SpindleSpeed = [string]$d.SpindleSpeed
IsSystem = ($devId -eq [int]$sysDisk)
MountPoints = $letters
}
}
}
$arr | ConvertTo-Json -Compress
"#;
use std::os::windows::process::CommandExt;
let output = Command::new("powershell")
.creation_flags(0x08000000) // CREATE_NO_WINDOW
.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", ps_script])
.output();
if let Ok(out) = output {
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !text.is_empty() {
if let Ok(json_val) = serde_json::from_str::<serde_json::Value>(&text) {
let items = if json_val.is_array() {
json_val.as_array().unwrap().clone()
} else if json_val.is_object() {
vec![json_val]
} else {
Vec::new()
};
for it in items {
let dev_id = it.get("DeviceId").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
let name = it.get("FriendlyName").and_then(|v| v.as_str()).unwrap_or("Disque").to_string();
let serial = it.get("SerialNumber").and_then(|v| v.as_str()).unwrap_or("").to_string();
// Parse Size (depuis string ou number)
let size = it.get("Size")
.and_then(|v| {
if let Some(s) = v.as_str() {
s.parse::<u64>().ok()
} else {
v.as_u64().or_else(|| v.as_f64().map(|f| f as u64))
}
})
.unwrap_or(0);
// Parse MediaType (string "SSD", "HDD" ou int)
let media_type_str = it.get("MediaType").and_then(|v| v.as_str()).unwrap_or("");
let bus_type_str = it.get("BusType").and_then(|v| v.as_str()).unwrap_or("");
let spindle_str = it.get("SpindleSpeed").and_then(|v| v.as_str()).unwrap_or("");
let is_sys = it.get("IsSystem").and_then(|v| v.as_bool()).unwrap_or(false);
// Parse MountPoints (peut être un tableau JSON ou une chaîne unique selon PowerShell)
let mut mount_points: Vec<String> = match it.get("MountPoints") {
Some(v) if v.is_array() => v
.as_array()
.unwrap()
.iter()
.filter_map(|x| x.as_str().map(|s| s.to_string()))
.collect(),
Some(v) if v.is_string() => {
let s = v.as_str().unwrap_or("").trim();
if !s.is_empty() {
vec![s.to_string()]
} else {
Vec::new()
}
}
_ => Vec::new(),
};
if is_sys && !mount_points.iter().any(|m| m.eq_ignore_ascii_case("C:")) {
mount_points.push("C:".to_string());
}
let mut bus_protocol = match bus_type_str.to_lowercase().as_str() {
s if s.contains("sata") => BusProtocol::Sata,
s if s.contains("nvme") => BusProtocol::Nvme,
s if s.contains("usb") => BusProtocol::Usb,
s if s.contains("scsi") => BusProtocol::Scsi,
s if s.contains("sas") => BusProtocol::Sas,
_ => BusProtocol::Unknown,
};
let (drive_type, rpm) = if media_type_str.eq_ignore_ascii_case("SSD") || media_type_str == "4" {
if bus_protocol == BusProtocol::Nvme {
(DriveType::Nvme, None)
} else {
(DriveType::Ssd, None)
}
} else if media_type_str.eq_ignore_ascii_case("HDD") || media_type_str == "3" {
let r = spindle_str.parse::<u32>().ok().filter(|&s| s > 0 && s < 20_000).or(Some(7200));
(DriveType::Hdd, r)
} else if bus_protocol == BusProtocol::Nvme {
(DriveType::Nvme, None)
} else {
(DriveType::Hdd, Some(7200))
};
if drive_type == DriveType::Nvme {
bus_protocol = BusProtocol::Nvme;
}
let size_formatted = Self::format_size(size);
list.push(DiskInfo {
device_id: format!(r"\\.\PhysicalDrive{}", dev_id),
index: dev_id,
model: name,
serial_number: serial,
size_bytes: size,
size_formatted,
drive_type,
bus_protocol,
rpm,
is_system_drive: is_sys,
mount_points,
smart: SmartAttributes {
power_on_hours: 0,
power_cycles: 0,
reallocated_sectors: 0,
pending_sectors: 0,
uncorrectable_sectors: 0,
crc_errors: 0,
temperature_celsius: None,
ssd_wear_percentage: None,
nvme_available_spare: None,
nvme_critical_warning: None,
unsafe_shutdowns: None,
raw_ata_attributes: Vec::new(),
raw_nvme_health: None,
},
});
}
}
}
}
list
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_live_scan() {
let wmi = SmartReader::fetch_wmi_disks_info();
println!("WMI DISKS COUNT: {}", wmi.len());
for d in &wmi {
println!("WMI: index={} model='{}' size='{}' bytes={} sys={} mounts={:?}", d.index, d.model, d.size_formatted, d.size_bytes, d.is_system_drive, d.mount_points);
}
let disks = SmartReader::scan_disks();
assert!(!disks.is_empty());
}
#[test]
fn test_resolve_disk_by_various_inputs() {
let dummy_smart = SmartAttributes {
power_on_hours: 100,
power_cycles: 10,
reallocated_sectors: 0,
pending_sectors: 0,
uncorrectable_sectors: 0,
crc_errors: 0,
temperature_celsius: Some(30),
ssd_wear_percentage: None,
nvme_available_spare: None,
nvme_critical_warning: None,
unsafe_shutdowns: None,
raw_ata_attributes: Vec::new(),
raw_nvme_health: None,
};
let disks = vec![
DiskInfo {
device_id: r"\\.\PhysicalDrive0".to_string(),
index: 0,
model: "SanDisk SD7SB6S128G1001".to_string(),
serial_number: "161601802225".to_string(),
size_bytes: 128000000000,
size_formatted: "128.0 Go".to_string(),
drive_type: DriveType::Ssd,
bus_protocol: BusProtocol::Sata,
rpm: None,
is_system_drive: false,
mount_points: vec!["D:".to_string()],
smart: dummy_smart.clone(),
},
DiskInfo {
device_id: r"\\.\PhysicalDrive1".to_string(),
index: 1,
model: "Samsung SSD 990 PRO 1TB".to_string(),
serial_number: "S6B0NJ0W123456".to_string(),
size_bytes: 1000000000000,
size_formatted: "1.00 To".to_string(),
drive_type: DriveType::Nvme,
bus_protocol: BusProtocol::Nvme,
rpm: None,
is_system_drive: true,
mount_points: vec!["C:".to_string()],
smart: dummy_smart,
},
];
// Résolution par lettre
assert_eq!(SmartReader::resolve_disk("C:", &disks).unwrap().index, 1);
assert_eq!(SmartReader::resolve_disk("c", &disks).unwrap().index, 1);
assert_eq!(SmartReader::resolve_disk("D:", &disks).unwrap().index, 0);
assert_eq!(SmartReader::resolve_disk("d", &disks).unwrap().index, 0);
// Résolution par index
assert_eq!(SmartReader::resolve_disk("0", &disks).unwrap().index, 0);
assert_eq!(SmartReader::resolve_disk("1", &disks).unwrap().index, 1);
// Résolution par device path
assert_eq!(SmartReader::resolve_disk(r"\\.\PhysicalDrive0", &disks).unwrap().index, 0);
assert_eq!(SmartReader::resolve_disk("PhysicalDrive1", &disks).unwrap().index, 1);
// Cible inexistante
assert!(SmartReader::resolve_disk("Z:", &disks).is_none());
assert!(SmartReader::resolve_disk("99", &disks).is_none());
}
#[test]
fn test_ata_attribute_naming() {
assert_eq!(SmartReader::get_ata_attribute_name(0x05), "Reallocated Sectors Count");
assert_eq!(SmartReader::get_ata_attribute_name(0xE9), "Media Wearout Indicator");
assert_eq!(SmartReader::get_ata_attribute_name(0xB8), "End-to-End Error / IOEDC");
assert_eq!(SmartReader::get_ata_attribute_name(0xC5), "Current Pending Sector Count");
}
}