A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
use std::path::PathBuf;
use windows::Win32::Storage::FileSystem::{GetDiskFreeSpaceExW, GetDriveTypeW, GetLogicalDrives, GetVolumeInformationW};
use windows::core::PCWSTR;
use crate::wide::{from_wide, wide};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DriveKind {
Fixed,
Removable,
Network,
Optical,
RamDisk,
Unknown,
}
#[derive(Debug, Clone)]
pub struct Drive {
/// "C:\"
pub root: PathBuf,
pub letter: char,
pub label: String,
pub kind: DriveKind,
pub total: u64,
pub free: u64,
pub fs: String,
/// A fixed disk on an outside bus (USB, FireWire, SD): an external hard disk or SSD. Windows calls it fixed, not removable, and
/// File Explorer still offers to eject it (discussion 762: the eject button was missing for external hard disks).
pub external: bool,
}
impl Drive {
pub fn display_name(&self) -> String {
let label = if self.label.is_empty() {
match self.kind {
DriveKind::Removable => "USB Sürücü",
DriveKind::Network => "Ağ Sürücüsü",
DriveKind::Optical => "DVD Sürücü",
_ => "Yerel Disk",
}
.to_string()
} else {
self.label.clone()
};
format!("{label} ({}:)", self.letter)
}
pub fn used_fraction(&self) -> f32 {
if self.total == 0 { 0.0 } else { 1.0 - self.free as f32 / self.total as f32 }
}
}
// ---------------------------------------------------------------- drives that are not listed
/// The bit of a drive letter in a drive mask ('A' is bit 0), in either case; `None` for what is no drive letter.
pub fn letter_bit(letter: char) -> Option<u32> {
let l = letter.to_ascii_uppercase();
l.is_ascii_uppercase().then(|| 1u32 << (l as u8 - b'A'))
}
/// The mask of the letters as the settings keep them or a user writes them: "V", "v:", "V:\\". What is no drive letter is skipped.
pub fn mask_of_letters<S: AsRef<str>>(letters: &[S]) -> u32 {
letters.iter().filter_map(|s| s.as_ref().trim().chars().next().and_then(letter_bit)).fold(0, |m, b| m | b)
}
/// The letters of a mask, A to Z.
pub fn letters_of_mask(mask: u32) -> Vec<char> {
(0..26u8).filter(|i| mask & (1 << i) != 0).map(|i| (b'A' + i) as char).collect()
}
/// The drives the user hides in rustyfiles (Settings > Files and folders), as a mask. One value for the process, set from the
/// settings whenever they are applied.
static HIDDEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
pub fn set_hidden(mask: u32) {
HIDDEN.store(mask, std::sync::atomic::Ordering::Relaxed);
}
pub fn hidden() -> u32 {
HIDDEN.load(std::sync::atomic::Ordering::Relaxed)
}
/// The drives Explorer itself is told not to show: the `NoDrives` value of Explorer's policies, the user's and the machine's (what
/// "Hide these specified drives in My Computer" and the tweak tools write). A drive hidden there is hidden here too.
pub fn policy_hidden() -> u32 {
const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer";
let read = |root: &windows_registry::Key| root.open(KEY).ok().and_then(|k| k.get_u32("NoDrives").ok()).unwrap_or(0);
(read(windows_registry::CURRENT_USER) | read(windows_registry::LOCAL_MACHINE)) & 0x03FF_FFFF
}
/// The drives a list of places shows: all of them less the ones the user hides and the ones Explorer hides.
///
/// WHY (issue 23, LokeYourC3PH, with a picture of four drives of which one was a raw encrypted volume: "any encrypted volume which is
/// not the system volume, stills shows up, even though I can hide it in the Windows Explorer ... I would like for an option where we
/// can hide volumes in rustyfiles"). A hidden drive is only not LISTED: its address typed into the address bar opens it as before.
/// It is also not asked for its name and its size, which is where a volume that cannot be read answers slowly or with an error.
pub fn visible_drives() -> Vec<Drive> {
list_drives_except(hidden() | policy_hidden())
}
/// Whether drive letter `letter` exists in the system at all right now (one call, nothing is read from the drive): a drive the user
/// hides from the list still exists; an unplugged one does not.
pub fn letter_present(letter: char) -> bool {
let l = letter.to_ascii_uppercase();
l.is_ascii_uppercase() && unsafe { GetLogicalDrives() } & (1 << (l as u32 - 'A' as u32)) != 0
}
/// Lists drive letters. Volume info can stall on disconnected network / empty optical drives,
/// so call this off the UI thread.
pub fn list_drives() -> Vec<Drive> {
list_drives_except(0)
}
fn list_drives_except(skip: u32) -> Vec<Drive> {
let mask = unsafe { GetLogicalDrives() } & !skip;
let letters: Vec<(char, DriveKind)> = (0..26u32)
.filter(|i| mask & (1 << i) != 0)
.map(|i| {
let letter = (b'A' + i as u8) as char;
(letter, kind_of(letter))
})
.collect();
// Each drive is asked for its name and size on a thread of its own, all at once. A network drive whose server cannot be reached
// answers after seconds, and they were asked one after the other while the sidebar waited for the list (issue 194: three
// unavailable network drives, "it takes around 10 seconds before I can use it"). A network drive that has not answered by
// NETWORK_WAIT is listed without its name and size; the other kinds are waited for as before.
let asks: Vec<_> = letters
.iter()
.map(|&(letter, kind)| {
let (tx, rx) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("drive info".into()).spawn(move || {
let _ = tx.send(volume_of(letter, kind));
});
rx
})
.collect();
let deadline = std::time::Instant::now() + NETWORK_WAIT;
let mut drives: Vec<Drive> = letters
.into_iter()
.zip(asks)
.map(|((letter, kind), rx)| {
let got = if kind == DriveKind::Network { rx.recv_timeout(deadline.saturating_duration_since(std::time::Instant::now())).ok() } else { rx.recv().ok() };
got.unwrap_or_else(|| {
if kind == DriveKind::Network {
log::info!("drives: {letter}: did not answer in time (a network drive whose server is away?), listed without its name");
}
Drive { root: PathBuf::from(format!("{letter}:\\")), letter, label: String::new(), kind, total: 0, free: 0, fs: String::new(), external: false }
})
})
.collect();
// A mapped drive is named by its share, as Explorer names it ("media (\\nas) (Z:)"), not by the label of the disk behind it:
// five drives of one NAS were all "New Volume", told apart only by their letters, which a narrow sidebar cut off (issue 468)
if drives.iter().any(|d| d.kind == DriveKind::Network) {
let mapped = mapped_drives();
for d in drives.iter_mut().filter(|d| d.kind == DriveKind::Network) {
// (the name the user gave it in Explorer or here comes first: issue 729)
if let Some(name) = mapped.iter().find(|(l, _)| *l == d.letter).and_then(|(_, share)| mapped_label(share).or_else(|| share_label(share))) {
d.label = name;
}
}
}
drives
}
/// Explorer's name for a mapped share: `\\nas\media` → `media (\\nas)`; `None` for what is not `\\server\share`.
pub fn share_label(share: &str) -> Option<String> {
let rest = share.strip_prefix(r"\\")?;
let (server, path) = rest.split_once('\\')?;
let name = path.trim_end_matches('\\').rsplit('\\').next().filter(|n| !n.is_empty())?;
(!server.is_empty()).then(|| format!(r"{name} (\\{server})"))
}
/// Where Explorer keeps the name a user gave a mapped share: `MountPoints2\##nas#media`, value `_LabelFromReg`. The share's own
/// volume label belongs to the server and cannot be changed from here (SetVolumeLabel answers "not supported", issue 729); this
/// name is the one Explorer's Rename of a network drive writes, per user.
fn mount_point_key(share: &str) -> String {
format!(r"Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\{}", share.replace('\\', "#"))
}
/// The name the user gave a mapped share (`\\nas\media`), when there is one.
pub fn mapped_label(share: &str) -> Option<String> {
windows_registry::CURRENT_USER.open(mount_point_key(share)).ok()?.get_string("_LabelFromReg").ok().filter(|l| !l.trim().is_empty())
}
/// Names a mapped share as Explorer's Rename does; an empty name, or its default one, gives it back the default (`media (\\nas)`).
pub fn set_mapped_label(share: &str, label: &str) -> std::io::Result<()> {
let key = windows_registry::CURRENT_USER.create(mount_point_key(share)).map_err(std::io::Error::other)?;
let label = label.trim();
if label.is_empty() || share_label(share).as_deref() == Some(label) {
let _ = key.remove_value("_LabelFromReg");
} else {
key.set_string("_LabelFromReg", label).map_err(std::io::Error::other)?;
}
Ok(())
}
/// The share a mapped drive letter is connected to (`Z` → `\\nas\media`).
pub fn share_of(letter: char) -> Option<String> {
mapped_drives().into_iter().find(|(l, _)| l.eq_ignore_ascii_case(&letter)).map(|(_, s)| s)
}
/// How long the list waits for a network drive's name and size (`list_drives_except`).
const NETWORK_WAIT: std::time::Duration = std::time::Duration::from_millis(400);
fn kind_of(letter: char) -> DriveKind {
let w = wide(&format!("{letter}:\\"));
match unsafe { GetDriveTypeW(PCWSTR(w.as_ptr())) } {
2 => DriveKind::Removable,
3 => DriveKind::Fixed,
4 => DriveKind::Network,
5 => DriveKind::Optical,
6 => DriveKind::RamDisk,
_ => DriveKind::Unknown,
}
}
/// The letters connected to a share now, each with the share's path (`Z`, `\\nas\media`; a WSL distribution on a letter too). The
/// system keeps these itself, nothing is read from the shares; still for a worker thread, as a provider of another program may answer.
pub fn mapped_drives() -> Vec<(char, String)> {
use windows::Win32::NetworkManagement::WNet::WNetGetConnectionW;
let letters = letters_of_mask(unsafe { GetLogicalDrives() });
letters
.into_iter()
.filter(|&l| kind_of(l) == DriveKind::Network)
.filter_map(|l| {
let local = wide(&format!("{l}:"));
let mut buf = vec![0u16; 1024];
let mut len = buf.len() as u32;
let r = unsafe { WNetGetConnectionW(PCWSTR(local.as_ptr()), Some(windows::core::PWSTR(buf.as_mut_ptr())), &mut len) };
(r.0 == 0).then(|| (l, from_wide(&buf)))
})
.collect()
}
/// Whether `p` is on the network: a `\\server\share` path or a mapped network drive. One system call; nothing is read from the share.
pub fn is_network_path(p: &std::path::Path) -> bool {
let s = p.to_string_lossy();
let s = match s.strip_prefix(r"\\?\UNC\") {
Some(rest) => format!(r"\\{rest}"),
None => s.strip_prefix(r"\\?\").unwrap_or(&s).to_string(),
};
if s.starts_with(r"\\") {
return true;
}
let mut c = s.chars();
matches!((c.next(), c.next()), (Some(l), Some(':')) if l.is_ascii_alphabetic() && kind_of(l) == DriveKind::Network)
}
/// A drive with its name, file system and sizes (none for an empty DVD tray or a volume that cannot be read).
fn volume_of(letter: char, kind: DriveKind) -> Drive {
let root = format!("{letter}:\\");
let w = wide(&root);
let mut label = [0u16; 261];
let mut fs = [0u16; 261];
let has_vol = unsafe { GetVolumeInformationW(PCWSTR(w.as_ptr()), Some(&mut label), None, None, None, Some(&mut fs)) }.is_ok();
let (mut free, mut total) = (0u64, 0u64);
if has_vol {
unsafe {
let _ = GetDiskFreeSpaceExW(PCWSTR(w.as_ptr()), Some(&mut free), Some(&mut total), None);
}
}
let external = kind == DriveKind::Fixed && external_bus(letter);
Drive { root: PathBuf::from(root), letter, label: from_wide(&label), kind, total, free, fs: from_wide(&fs), external }
}
/// Whether drive `letter`'s disk sits on an outside bus: USB (7), IEEE 1394 (4), SD (12) or MMC (13). One query of the volume,
/// opened without access rights; nothing is read from the disk.
pub fn external_bus(letter: char) -> bool {
let q = [0u32.to_le_bytes(), 0u32.to_le_bytes(), [0; 4]].concat();
storage_query(std::path::Path::new(&format!("{letter}:\\")), &q, 1024).and_then(|d| u32_at(&d, 28)).is_some_and(|b| matches!(b, 4 | 7 | 12 | 13))
}
#[cfg(test)]
mod tests {
use super::{letter_bit, letters_of_mask, list_drives_except, mask_of_letters, policy_hidden};
/// Network paths are slow without touching the network; a file on the system disk is not.
#[test]
fn hidden_drives_are_a_mask_of_their_letters() {
assert_eq!(letter_bit('A'), Some(1));
assert_eq!(letter_bit('c'), Some(4));
assert_eq!(letter_bit('Z'), Some(1 << 25));
assert_eq!(letter_bit('1'), None);
assert_eq!(letter_bit('ç'), None);
assert_eq!(mask_of_letters(&["V", "c:", " Z:\\ ", "", "9", "é"]), (1 << 21) | 4 | (1 << 25));
assert_eq!(mask_of_letters::<&str>(&[]), 0);
assert_eq!(letters_of_mask((1 << 21) | 4 | 1), ['A', 'C', 'V']);
assert!(letters_of_mask(0).is_empty());
// back and forth
let letters: Vec<String> = letters_of_mask(0b1010_0100).into_iter().map(String::from).collect();
assert_eq!(mask_of_letters(&letters), 0b1010_0100);
}
/// On the PC the tests run on: a drive that is hidden is not listed and not asked anything, and the others are as they were.
#[test]
fn a_hidden_drive_is_left_out_of_the_list() {
let all: Vec<char> = list_drives_except(0).into_iter().map(|d| d.letter).collect();
let Some(&first) = all.first() else { return };
let without: Vec<char> = list_drives_except(letter_bit(first).unwrap()).into_iter().map(|d| d.letter).collect();
assert_eq!(without, all[1..]);
assert!(list_drives_except(0x03FF_FFFF).is_empty(), "every letter hidden: nothing is listed");
// (reading Explorer's policy never fails: no value is no drive)
assert_eq!(policy_hidden() & !0x03FF_FFFF, 0);
}
#[test]
fn slow_places() {
use std::path::Path;
assert!(super::slow_to_read(Path::new(r"\\nas\share\film.mkv")));
assert!(super::slow_to_read(Path::new(r"\\?\UNC\nas\share\film.mkv")));
assert!(!super::slow_to_read(&std::env::temp_dir()));
assert!(!super::slow_to_read(Path::new(r"C:\Windows\notepad.exe")));
}
#[test]
fn has_c_drive() {
let d = super::list_drives();
let c = d.iter().find(|d| d.letter == 'C').expect("C: exists");
assert!(c.total > 0 && c.free <= c.total);
}
}
/// Whether `path` is on a removable drive (USB stick, SD card).
pub fn is_removable(path: &std::path::Path) -> bool {
let s = path.to_string_lossy();
let b = s.as_bytes();
if b.len() < 2 || b[1] != b':' {
return false;
}
let root = crate::wide::wide(format!("{}:\\", b[0] as char));
// 2 = DRIVE_REMOVABLE
unsafe { GetDriveTypeW(PCWSTR(root.as_ptr())) == 2 }
}
/// Whether reading `path` may take seconds: a network share, a removable or optical disk, or a
/// cloud file whose data is not on this PC (reading it downloads it). DirectLook opens such files
/// off the UI thread.
pub fn slow_to_read(path: &std::path::Path) -> bool {
if crate::localized::is_network(path) {
return true;
}
let s = path.to_string_lossy();
let letter = match s.as_bytes() {
[l, b':', ..] => Some(*l),
[b'\\', b'\\', b'?', b'\\', l, b':', ..] => Some(*l),
_ => None,
};
if let Some(l) = letter {
let root = crate::wide::wide(format!("{}:\\", l as char));
// 2 = DRIVE_REMOVABLE, 5 = DRIVE_CDROM
if matches!(unsafe { GetDriveTypeW(PCWSTR(root.as_ptr())) }, 2 | 5) {
return true;
}
}
// FILE_ATTRIBUTE_OFFLINE, FILE_ATTRIBUTE_RECALL_ON_OPEN, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS
use std::os::windows::fs::MetadataExt;
std::fs::metadata(path).is_ok_and(|m| m.file_attributes() & (0x1000 | 0x4_0000 | 0x40_0000) != 0)
}
/// Bitmask of present drive letters (cheap; poll it to notice USB plug/unplug).
pub fn drive_mask() -> u32 {
unsafe { GetLogicalDrives() }
}
/// Whether the disk holding `path` has a seek penalty (a spinning disk): `None` when it can't
/// be told (network paths, no access). Reads the device's own property; no admin needed.
pub fn seek_penalty(path: &std::path::Path) -> Option<bool> {
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::Storage::FileSystem::{CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING};
use windows::Win32::System::IO::DeviceIoControl;
use windows::Win32::System::Ioctl::{
DEVICE_SEEK_PENALTY_DESCRIPTOR, IOCTL_STORAGE_QUERY_PROPERTY, PropertyStandardQuery, STORAGE_PROPERTY_QUERY,
StorageDeviceSeekPenaltyProperty,
};
let s = path.to_str()?;
let b = s.as_bytes();
if b.len() < 2 || b[1] != b':' || !b[0].is_ascii_alphabetic() {
return None;
}
let dev = crate::wide::wide(format!(r"\\.\{}:", b[0] as char));
unsafe {
// no access rights needed for a property query
let h = CreateFileW(
windows::core::PCWSTR(dev.as_ptr()),
0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
None,
OPEN_EXISTING,
FILE_FLAGS_AND_ATTRIBUTES(0),
None,
)
.map_err(|e| log::debug!("seek_penalty open: {e}"))
.ok()?;
let q = STORAGE_PROPERTY_QUERY { PropertyId: StorageDeviceSeekPenaltyProperty, QueryType: PropertyStandardQuery, AdditionalParameters: [0] };
let mut d = DEVICE_SEEK_PENALTY_DESCRIPTOR::default();
let mut got = 0u32;
let ok = DeviceIoControl(
h,
IOCTL_STORAGE_QUERY_PROPERTY,
Some(&q as *const _ as *const _),
std::mem::size_of::<STORAGE_PROPERTY_QUERY>() as u32,
Some(&mut d as *mut _ as *mut _),
std::mem::size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as u32,
Some(&mut got),
None,
);
let _ = CloseHandle(h);
ok.map_err(|e| log::debug!("seek_penalty ioctl: {e}")).ok()?;
Some(d.IncursSeekPenalty)
}
}
/// How a disk is attached, as Windows' storage stack reports it (`STORAGE_BUS_TYPE`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Bus {
Nvme,
Sata,
Usb,
Sd,
Raid,
Spaces,
Scsi,
Virtual,
Other(u32),
}
impl Bus {
fn from_raw(v: u32) -> Bus {
match v {
17 => Bus::Nvme,
11 | 3 => Bus::Sata,
7 => Bus::Usb,
12 | 13 => Bus::Sd,
8 => Bus::Raid,
16 => Bus::Spaces,
1 | 10 => Bus::Scsi,
14 | 15 => Bus::Virtual,
v => Bus::Other(v),
}
}
}
/// What the copy engine wants to know about the disk under a drive letter. Every part is `None` when Windows did not say.
#[derive(Debug, Clone, Default)]
pub struct DiskInfo {
pub bus: Option<Bus>,
/// The device's product name ("WD Blue SN5000 2TB").
pub model: Option<String>,
pub seek_penalty: Option<bool>,
pub removable: bool,
/// An NVMe drive's Host Memory Buffer wish, in KiB (preferred, minimum): a drive that asks for one has (almost always) no
/// DRAM of its own. `Some((0, 0))`: an NVMe drive that asks for none.
pub host_memory_buffer_kib: Option<(u32, u32)>,
}
impl DiskInfo {
/// A DRAM-less SSD: an NVMe drive that asks the PC for a host memory buffer.
pub fn dramless(&self) -> Option<bool> {
self.host_memory_buffer_kib.map(|(preferred, min)| preferred > 0 || min > 0)
}
}
/// The kind of disk a path is on, as the copy engine sizes its work for it: how many files it copies at once.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum DiskKind {
/// A spinning disk (also in a USB enclosure that doesn't say what it holds): one file at a time.
Hdd,
/// An SSD on SATA (or another bus that says it has no seek penalty).
SataSsd,
/// An NVMe SSD with DRAM of its own.
NvmeSsd,
/// An NVMe SSD that borrows the PC's memory (Host Memory Buffer) instead of having DRAM.
DramlessSsd,
/// Removable media: a USB stick, a memory card.
UsbStick,
/// A network share or a mapped network drive.
Network,
/// Windows did not say.
Unknown,
}
impl DiskKind {
/// The kinds a person can choose for a drive (Settings › Advanced), in the order they are offered.
pub const CHOICES: [DiskKind; 6] = [DiskKind::Hdd, DiskKind::SataSsd, DiskKind::NvmeSsd, DiskKind::DramlessSsd, DiskKind::UsbStick, DiskKind::Network];
}
/// What kind of disk `path` is on, from what Windows reports (no administrator rights).
pub fn disk_kind(path: &std::path::Path) -> DiskKind {
if is_network_path(path) || crate::localized::is_network(path) {
return DiskKind::Network;
}
kind_from(&disk_info(path))
}
/// The kind a [`DiskInfo`] stands for. A USB enclosure seldom passes a disk's seek penalty on: unknown there means a spinning disk.
pub fn kind_from(i: &DiskInfo) -> DiskKind {
match (i.seek_penalty, i.bus, i.removable) {
(Some(true), _, _) => DiskKind::Hdd,
(_, _, true) => DiskKind::UsbStick,
(None, Some(Bus::Usb), _) => DiskKind::Hdd,
(_, Some(Bus::Nvme), _) if i.dramless() == Some(true) => DiskKind::DramlessSsd,
(_, Some(Bus::Nvme), _) => DiskKind::NvmeSsd,
(Some(false), _, _) => DiskKind::SataSsd,
_ => DiskKind::Unknown,
}
}
#[cfg(test)]
mod disk_kind_tests {
use super::{Bus, DiskInfo, DiskKind, kind_from};
#[test]
fn what_windows_says_becomes_a_kind() {
let d = |seek, bus, removable, hmb| DiskInfo { seek_penalty: seek, bus, removable, host_memory_buffer_kib: hmb, model: None };
assert_eq!(kind_from(&d(Some(true), Some(Bus::Sata), false, None)), DiskKind::Hdd);
assert_eq!(kind_from(&d(None, Some(Bus::Usb), false, None)), DiskKind::Hdd, "a USB enclosure that doesn't say");
assert_eq!(kind_from(&d(None, Some(Bus::Usb), true, None)), DiskKind::UsbStick);
assert_eq!(kind_from(&d(Some(false), Some(Bus::Nvme), false, Some((0, 0)))), DiskKind::NvmeSsd);
assert_eq!(kind_from(&d(Some(false), Some(Bus::Nvme), false, Some((65536, 3292)))), DiskKind::DramlessSsd);
assert_eq!(kind_from(&d(Some(false), Some(Bus::Sata), false, None)), DiskKind::SataSsd);
assert_eq!(kind_from(&d(Some(false), Some(Bus::Usb), false, None)), DiskKind::SataSsd, "a USB SSD that says so");
assert_eq!(kind_from(&d(None, None, false, None)), DiskKind::Unknown);
}
}
/// One `IOCTL_STORAGE_QUERY_PROPERTY` on the volume of drive letter `path` (opened with no access rights: a property query needs
/// none), `input` in, the bytes Windows wrote out.
fn storage_query(path: &std::path::Path, input: &[u8], out_len: usize) -> Option<Vec<u8>> {
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::Storage::FileSystem::{CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING};
use windows::Win32::System::IO::DeviceIoControl;
use windows::Win32::System::Ioctl::IOCTL_STORAGE_QUERY_PROPERTY;
let s = path.to_str()?;
let b = s.strip_prefix(r"\\?\").unwrap_or(s).as_bytes();
if b.len() < 2 || b[1] != b':' || !b[0].is_ascii_alphabetic() {
return None;
}
let dev = crate::wide::wide(format!(r"\\.\{}:", b[0] as char));
let mut out = vec![0u8; out_len.max(input.len())];
unsafe {
let h = CreateFileW(windows::core::PCWSTR(dev.as_ptr()), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES(0), None).ok()?;
let mut got = 0u32;
let ok = DeviceIoControl(
h,
IOCTL_STORAGE_QUERY_PROPERTY,
Some(input.as_ptr() as *const _),
input.len() as u32,
Some(out.as_mut_ptr() as *mut _),
out.len() as u32,
Some(&mut got),
None,
);
let _ = CloseHandle(h);
ok.map_err(|e| log::debug!("storage query: {e}")).ok()?;
out.truncate(got as usize);
}
Some(out)
}
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
b.get(at..at + 4).map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]))
}
/// The disk under drive letter `path`: its bus, model, seek penalty and (NVMe) host memory buffer. No administrator rights.
pub fn disk_info(path: &std::path::Path) -> DiskInfo {
let mut info = DiskInfo { seek_penalty: seek_penalty(path), removable: is_removable(path), ..Default::default() };
// StorageDeviceProperty (0), standard query: STORAGE_DEVICE_DESCRIPTOR
let q = [0u32.to_le_bytes(), 0u32.to_le_bytes(), [0; 4]].concat();
if let Some(d) = storage_query(path, &q, 1024) {
info.bus = u32_at(&d, 28).map(Bus::from_raw);
info.removable |= d.get(10).is_some_and(|&r| r != 0);
if let Some(off) = u32_at(&d, 16).filter(|&o| o > 0 && (o as usize) < d.len()) {
let name: Vec<u8> = d[off as usize..].iter().take_while(|&&c| c != 0).copied().collect();
let name = String::from_utf8_lossy(&name).trim().to_string();
info.model = (!name.is_empty()).then_some(name);
}
}
if info.bus == Some(Bus::Nvme) {
info.host_memory_buffer_kib = nvme_host_memory_buffer(path);
}
info
}
/// An NVMe drive's Identify Controller data, HMPRE and HMMIN (bytes 272 and 276, in 4 KiB units), through the storage stack's
/// protocol-specific query (`StorageAdapterProtocolSpecificProperty`, `ProtocolTypeNvme`, `NVMeDataTypeIdentify`, CNS 1).
fn nvme_host_memory_buffer(path: &std::path::Path) -> Option<(u32, u32)> {
const IDENTIFY_LEN: u32 = 4096;
const SPECIFIC_LEN: u32 = 40; // STORAGE_PROTOCOL_SPECIFIC_DATA
let mut q = Vec::with_capacity((8 + SPECIFIC_LEN + IDENTIFY_LEN) as usize);
q.extend_from_slice(&49u32.to_le_bytes()); // StorageAdapterProtocolSpecificProperty
q.extend_from_slice(&0u32.to_le_bytes()); // PropertyStandardQuery
for v in [3u32, 1, 1, 0, SPECIFIC_LEN, IDENTIFY_LEN, 0, 0, 0, 0] {
// ProtocolTypeNvme, NVMeDataTypeIdentify, CNS controller, sub value, data offset, data length, …
q.extend_from_slice(&v.to_le_bytes());
}
q.resize((8 + SPECIFIC_LEN + IDENTIFY_LEN) as usize, 0);
let d = storage_query(path, &q, q.len())?;
// STORAGE_PROTOCOL_DATA_DESCRIPTOR: Version, Size, then the specific data, whose offset counts from itself (byte 8)
let data_at = 8 + u32_at(&d, 8 + 16)? as usize;
let hmpre = u32_at(&d, data_at + 272)?;
let hmmin = u32_at(&d, data_at + 276)?;
Some((hmpre * 4, hmmin * 4))
}
#[cfg(test)]
mod network_tests {
use super::is_network_path;
#[test]
fn a_mapped_share_is_named_as_explorer_names_it() {
assert_eq!(super::share_label(r"\\nas\media").as_deref(), Some(r"media (\\nas)"));
assert_eq!(super::share_label(r"\\RADNIK\d\").as_deref(), Some(r"d (\\RADNIK)"));
assert_eq!(super::share_label(r"\\srv\data\projects").as_deref(), Some(r"projects (\\srv)"));
assert_eq!(super::share_label(r"C:\x"), None);
assert_eq!(super::share_label(r"\\srv"), None);
assert_eq!(super::mount_point_key(r"\\nas\media"), r"Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\##nas#media");
}
use std::path::Path;
#[test]
fn shares_are_on_the_network_and_the_system_drive_is_not() {
assert!(is_network_path(Path::new(r"\\server\share\folder")));
assert!(is_network_path(Path::new(r"\\?\UNC\server\share")));
let sys = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into());
assert!(!is_network_path(Path::new(&format!(r"{sys}\Windows"))));
assert!(!is_network_path(Path::new(&format!(r"\\?\{sys}\Windows"))));
assert!(!is_network_path(Path::new("relative")));
}
}
#[cfg(test)]
mod seek_tests {
#[test]
fn system_drive_answers() {
// the system drive always exists: the query must not panic (virtual disks, as on CI
// runners, may not answer it, so the result itself isn't asserted)
let sys = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into());
let _ = super::seek_penalty(std::path::Path::new(&format!("{sys}\\")));
assert_eq!(super::seek_penalty(std::path::Path::new(r"\\server\share")), None);
}
}