Skip to content

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.

9.7 KB
Raw Blame
//! "Safely remove" for a disk on an outside bus (a USB hard disk or SSD), asked of Windows' device manager itself.
//!
//! WHY (issue 622, 2026-12-05, an external SSD formatted exFAT). The shell's "eject" verb, which removes a USB stick or a card
//! well, answered for this disk with a box of its own ("An error occurred while ejecting" and a name of garbage letters) and said
//! nothing a program can read: not whether the disk was in use, and not by whom. The device manager's own request
//! (`CM_Request_Device_Eject`, what "Safely Remove Hardware" asks) puts up no window and, when it is refused, names the kind of
//! refusal and often WHO refused: a program, a service, or a device with files still open. That name goes into the error, so the
//! log and the message can say it.
//!
//! HOW. The drive letter's volume says which disk it is on (its device number); the disk with that number is looked up among
//! the disk devices that are present; the request goes to that disk's parent, the USB device, so that the whole thing is
//! released as when its cable is to be pulled. Everything before the request only reads.

use windows::Win32::Devices::DeviceAndDriverInstallation::{
    CM_Get_Device_IDW, CM_Get_Parent, CM_Request_Device_EjectW, CR_SUCCESS, DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, PNP_VETO_TYPE,
    SP_DEVICE_INTERFACE_DATA, SP_DEVICE_INTERFACE_DETAIL_DATA_W, SP_DEVINFO_DATA, SetupDiDestroyDeviceInfoList,
    SetupDiEnumDeviceInterfaces, SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW,
};
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::{GUID_DEVINTERFACE_DISK, IOCTL_STORAGE_GET_DEVICE_NUMBER};
use windows::core::PCWSTR;

/// The number Windows gives the disk behind `device` (a volume as `\\.\D:`, or a disk's interface path): the N of
/// `PhysicalDriveN`. Opened without access rights; nothing is read from the disk.
fn disk_number(device: PCWSTR) -> Option<u32> {
    // STORAGE_DEVICE_NUMBER: the device's type, its number, the partition's number
    let mut out = [0u32; 3];
    // SAFETY: the handle is opened and closed here; the output buffer is 12 bytes and the call is told so
    unsafe {
        let h = CreateFileW(device, 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_GET_DEVICE_NUMBER, None, 0, Some(out.as_mut_ptr() as *mut _), 12, Some(&mut got), None);
        let _ = CloseHandle(h);
        ok.ok()?;
    }
    // (7: a disk. A disc drive or a virtual thing has another type, and its numbers count separately)
    (out[0] == 7).then_some(out[1])
}

/// The device node of the disk drive `letter` is on, when it is one disk that is present (not a spanned volume, not a disc).
fn disk_node(letter: char) -> Option<u32> {
    let volume = crate::wide::wide(format!(r"\\.\{}:", letter.to_ascii_uppercase()));
    let wanted = disk_number(PCWSTR(volume.as_ptr()))?;
    let mut found = None;
    // SAFETY: the device list is made and destroyed here. Each structure's size field is set as the API asks; the detail buffer
    // is as long as the API said it needs, aligned for the structure, and the path read from it is NUL-ended by the API.
    unsafe {
        let set = SetupDiGetClassDevsW(Some(&GUID_DEVINTERFACE_DISK), PCWSTR::null(), None, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE).ok()?;
        for index in 0..256u32 {
            let mut iface = SP_DEVICE_INTERFACE_DATA { cbSize: std::mem::size_of::<SP_DEVICE_INTERFACE_DATA>() as u32, ..Default::default() };
            if SetupDiEnumDeviceInterfaces(set, None, &GUID_DEVINTERFACE_DISK, index, &mut iface).is_err() {
                break;
            }
            let mut need = 0u32;
            let _ = SetupDiGetDeviceInterfaceDetailW(set, &iface, None, 0, Some(&mut need), None);
            if need == 0 {
                continue;
            }
            let mut buf = vec![0u64; need as usize / 8 + 2];
            let detail = buf.as_mut_ptr() as *mut SP_DEVICE_INTERFACE_DETAIL_DATA_W;
            (*detail).cbSize = std::mem::size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32;
            let mut info = SP_DEVINFO_DATA { cbSize: std::mem::size_of::<SP_DEVINFO_DATA>() as u32, ..Default::default() };
            if SetupDiGetDeviceInterfaceDetailW(set, &iface, Some(detail), need, None, Some(&mut info)).is_err() {
                continue;
            }
            let path = PCWSTR(std::ptr::addr_of!((*detail).DevicePath) as *const u16);
            if disk_number(path) == Some(wanted) {
                found = Some(info.DevInst);
                break;
            }
        }
        let _ = SetupDiDestroyDeviceInfoList(set);
    }
    found
}

/// The device above `node` (a USB disk's parent is the USB device itself).
fn parent_of(node: u32) -> Option<u32> {
    let mut parent = 0u32;
    // SAFETY: writes one number
    (unsafe { CM_Get_Parent(&mut parent, node, 0) } == CR_SUCCESS).then_some(parent)
}

/// A device node's id (`USB\VID_...\serial`), for the log.
fn id_of(node: u32) -> String {
    let mut buf = [0u16; 512];
    // SAFETY: the buffer's length is its own
    if unsafe { CM_Get_Device_IDW(node, &mut buf, 0) } == CR_SUCCESS { crate::wide::from_wide(&buf) } else { String::new() }
}

/// What a refusal's kind means, in words (`PNP_VETO_TYPE`).
pub fn veto_words(kind: i32) -> &'static str {
    match kind {
        2 => "a program still has it open, waiting to close",
        3 => "a program refused",
        4 => "a Windows service refused",
        5 => "files or folders on it are still open",
        6 => "a device on it refused",
        7 => "a driver refused",
        8 => "the device does not take this request",
        10 => "the device cannot be turned off",
        12 => "the rights to remove it are missing",
        13 => "it is already removed",
        _ => "Windows refused",
    }
}

/// What the lookups find for drive `letter`, without asking for anything (for a look by hand: `examples/eject_probe`).
pub fn describe(letter: char) -> String {
    match disk_node(letter) {
        None => format!("{letter}: no single disk device found for it"),
        Some(disk) => {
            let parent = parent_of(disk);
            format!("{letter}: disk {} | its parent {}", id_of(disk), parent.map(id_of).unwrap_or_else(|| "(none)".into()))
        }
    }
}

/// Asks Windows to let the disk of drive `letter` go, as "Safely Remove Hardware" does. `Ok` when Windows agreed (the drive
/// letter goes a moment later). Blocking: Windows asks every program that watches the disk first. Refused, the error says how
/// and, when Windows names one, by whom.
pub fn eject(letter: char) -> anyhow::Result<()> {
    let disk = disk_node(letter).ok_or_else(|| anyhow::anyhow!("{letter}: its disk device was not found"))?;
    let mut refused = None;
    // (the USB device first, then the disk itself where the parent takes no such request)
    for node in [parent_of(disk), Some(disk)].into_iter().flatten() {
        let mut kind = PNP_VETO_TYPE(0);
        let mut name = [0u16; 260];
        // SAFETY: the name buffer's length is its own; the kind is one number
        let r = unsafe { CM_Request_Device_EjectW(node, Some(&mut kind), Some(&mut name), 0) };
        if r == CR_SUCCESS && kind.0 == 0 {
            log::info!("eject: {letter}: Windows let {} go", id_of(node));
            return Ok(());
        }
        let who = crate::wide::from_wide(&name);
        log::warn!("eject: {letter}: {} was not let go: result {:#x}, {} ({}){}", id_of(node), r.0, veto_words(kind.0), kind.0, if who.is_empty() { String::new() } else { format!(": {who}") });
        // (the first refusal that names its kind is the one to tell: the second try is only a fallback)
        if refused.is_none() && kind.0 != 0 {
            refused = Some((kind.0, who));
        }
        // refused because it is in use: asking the disk itself would be refused the same way
        if matches!(kind.0, 2..=7) {
            break;
        }
    }
    match refused {
        Some((kind, who)) if who.is_empty() => anyhow::bail!("{letter}: {}", veto_words(kind)),
        Some((kind, who)) => anyhow::bail!("{letter}: {}: {who}", veto_words(kind)),
        None => anyhow::bail!("{letter}: Windows did not take the request"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// On the PC the tests run on: the system drive is on a disk, that disk is found among the present ones, and it has a parent.
    /// Nothing is asked to go.
    #[test]
    fn the_system_drives_disk_is_found_without_asking_for_anything() {
        let letter = std::env::var("SystemDrive").ok().and_then(|s| s.chars().next()).unwrap_or('C');
        let Some(disk) = disk_node(letter) else {
            // (a system drive on a spanned or virtual volume has no single disk: nothing to check then)
            return;
        };
        assert!(!id_of(disk).is_empty());
        assert!(parent_of(disk).is_some());
        assert!(describe(letter).contains("disk "));
    }

    #[test]
    fn a_letter_with_no_drive_has_no_disk() {
        // (a letter nothing is mounted on; the loop looks for one)
        let free = ('D'..='Z').rev().find(|l| !std::path::Path::new(&format!("{l}:\\")).exists());
        if let Some(l) = free {
            assert!(disk_node(l).is_none());
            assert!(eject(l).is_err(), "nothing is asked of a drive that is not there");
        }
    }

    #[test]
    fn a_refusal_is_said_in_words() {
        assert_eq!(veto_words(5), "files or folders on it are still open");
        assert_eq!(veto_words(3), "a program refused");
        assert_eq!(veto_words(99), "Windows refused");
    }
}