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.

15.5 KB
Raw Blame
//! Which programs hold a file open: Windows' Restart Manager, the same service installers ask before they replace a file. It needs
//! no administrator rights and sees the programs of every user that hold one of the files (a Discord request, 2026-11-28: "see what's
//! locking your files or folders").
//!
//! A folder is asked about through the files in it (Restart Manager knows files, not folders): the first [`MAX_FILES`] of them, a
//! few levels deep, which is where the file a program has open usually is.

use std::path::{Path, PathBuf};

use windows::Win32::Foundation::{CloseHandle, ERROR_MORE_DATA, ERROR_SUCCESS, HANDLE, HWND, LPARAM, WPARAM};
use windows::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS};
use windows::Win32::System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, PROCESS_VM_READ, TerminateProcess};
use windows::Win32::UI::WindowsAndMessaging::{EnumWindows, GW_OWNER, GetWindow, GetWindowThreadProcessId, IsWindowVisible, PostMessageW, WM_CLOSE};
use windows_core::BOOL;
use windows::Win32::System::RestartManager::{CCH_RM_SESSION_KEY, RM_PROCESS_INFO, RmEndSession, RmGetList, RmRegisterResources, RmStartSession};
use windows::core::{PCWSTR, PWSTR};

use crate::wide::wide;

/// At most this many files of a folder are asked about.
pub const MAX_FILES: usize = 2000;
/// ... found no deeper than this under the folder.
const MAX_DEPTH: usize = 4;

/// A program that holds one of the files open.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Locker {
    pub pid: u32,
    /// The program's name as Windows tells it ("Microsoft Word", "notepad.exe").
    pub name: String,
}

/// The programs that hold `paths` (files, or folders through their files) open, and for folders also the programs working in them
/// ([`working_in`]). Blocking: off the UI thread.
pub fn who_holds(paths: &[PathBuf]) -> anyhow::Result<Vec<Locker>> {
    let dirs: Vec<PathBuf> = paths.iter().filter(|p| p.is_dir()).cloned().collect();
    let mut out = holding_files(paths)?;
    for l in working_in(&dirs) {
        if !out.iter().any(|o| o.pid == l.pid) {
            out.push(l);
        }
    }
    out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
    Ok(out)
}

fn holding_files(paths: &[PathBuf]) -> anyhow::Result<Vec<Locker>> {
    let files = files_of(paths);
    if files.is_empty() {
        return Ok(Vec::new());
    }
    let mut session = 0u32;
    let mut key = [0u16; CCH_RM_SESSION_KEY as usize + 1];
    let r = unsafe { RmStartSession(&mut session, None, PWSTR(key.as_mut_ptr())) };
    anyhow::ensure!(r == ERROR_SUCCESS, "Restart Manager did not start: {}", r.0);
    let out = list(session, &files);
    unsafe {
        let _ = RmEndSession(session);
    }
    out
}

fn list(session: u32, files: &[PathBuf]) -> anyhow::Result<Vec<Locker>> {
    let wides: Vec<Vec<u16>> = files.iter().map(|f| wide(f)).collect();
    let names: Vec<PCWSTR> = wides.iter().map(|w| PCWSTR(w.as_ptr())).collect();
    // (registered in parts: one call with thousands of names is refused on some systems)
    for part in names.chunks(256) {
        let r = unsafe { RmRegisterResources(session, Some(part), None, None) };
        anyhow::ensure!(r == ERROR_SUCCESS, "Restart Manager did not take the files: {}", r.0);
    }
    let mut infos: Vec<RM_PROCESS_INFO> = Vec::new();
    for _ in 0..4 {
        let (mut needed, mut count, mut reasons) = (0u32, infos.len() as u32, 0u32);
        let ptr = if infos.is_empty() { None } else { Some(infos.as_mut_ptr()) };
        let r = unsafe { RmGetList(session, &mut needed, &mut count, ptr, &mut reasons) };
        if r == ERROR_SUCCESS {
            infos.truncate(count as usize);
            return Ok(lockers_of(&infos));
        }
        anyhow::ensure!(r == ERROR_MORE_DATA, "Restart Manager gave no list: {}", r.0);
        // (programs may open the files meanwhile: room for a few more)
        infos = vec![RM_PROCESS_INFO::default(); needed as usize + 4];
    }
    anyhow::bail!("the list of programs kept changing")
}

fn lockers_of(infos: &[RM_PROCESS_INFO]) -> Vec<Locker> {
    let mut out: Vec<Locker> = Vec::new();
    for i in infos {
        let n = i.strAppName.iter().position(|&c| c == 0).unwrap_or(i.strAppName.len());
        let name = String::from_utf16_lossy(&i.strAppName[..n]);
        let pid = i.Process.dwProcessId;
        if !out.iter().any(|l| l.pid == pid) {
            out.push(Locker { pid, name });
        }
    }
    out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
    out
}

/// The files to ask about: each file as it is, a folder's files (see the module).
fn files_of(paths: &[PathBuf]) -> Vec<PathBuf> {
    let mut out = Vec::new();
    for p in paths {
        if p.is_dir() {
            walk(p, 0, &mut out);
        } else {
            out.push(p.clone());
        }
        if out.len() >= MAX_FILES {
            out.truncate(MAX_FILES);
            break;
        }
    }
    out
}

fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
    let Ok(rd) = std::fs::read_dir(dir) else { return };
    let mut sub = Vec::new();
    for e in rd.flatten() {
        if out.len() >= MAX_FILES {
            return;
        }
        let Ok(t) = e.file_type() else { continue };
        if t.is_dir() {
            // (not into links: a junction can lead anywhere, even back up)
            if !t.is_symlink() {
                sub.push(e.path());
            }
        } else {
            out.push(e.path());
        }
    }
    if depth < MAX_DEPTH {
        for d in sub {
            walk(&d, depth + 1, out);
        }
    }
}

// (from ntdll: the documented way to find a process's PEB, where its working folder is kept)
#[link(name = "ntdll")]
unsafe extern "system" {
    fn NtQueryInformationProcess(process: HANDLE, class: u32, info: *mut core::ffi::c_void, len: u32, ret: *mut u32) -> i32;
}

/// The programs whose working folder is one of `dirs` or inside one (a terminal or an editor opened there): Windows won't rename,
/// move or delete such a folder ("Folder In Use"), and Restart Manager, which knows open files, doesn't see it. Read from each
/// process's own block of parameters; the processes this user can't read (other users', the system's) are left out.
pub fn working_in(dirs: &[PathBuf]) -> Vec<Locker> {
    let mut out = Vec::new();
    if dirs.is_empty() {
        return out;
    }
    let dirs: Vec<String> = dirs.iter().map(|d| d.to_string_lossy().trim_end_matches('\\').to_lowercase()).collect();
    for (pid, name) in processes() {
        if pid <= 4 {
            continue;
        }
        if let Some(cwd) = working_folder(pid) {
            if dirs.iter().any(|d| inside(&cwd, d)) {
                out.push(Locker { pid, name });
            }
        }
    }
    out
}

/// Whether the folder `cwd` is `dir` (lower case, no trailing backslash) or inside it.
fn inside(cwd: &str, dir: &str) -> bool {
    let cwd = cwd.trim_end_matches('\\').to_lowercase();
    cwd == dir || cwd.strip_prefix(dir).is_some_and(|rest| rest.starts_with('\\'))
}

/// Every process with its program's file name.
fn processes() -> Vec<(u32, String)> {
    let mut out = Vec::new();
    // SAFETY: the snapshot handle is used and closed here; `dwSize` is set as the API asks.
    unsafe {
        let Ok(snap) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { return out };
        let mut e = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
        let mut more = Process32FirstW(snap, &mut e).is_ok();
        while more {
            let n = e.szExeFile.iter().position(|&c| c == 0).unwrap_or(e.szExeFile.len());
            out.push((e.th32ProcessID, String::from_utf16_lossy(&e.szExeFile[..n])));
            more = Process32NextW(snap, &mut e).is_ok();
        }
        let _ = CloseHandle(snap);
    }
    out
}

/// A 64-bit process's working folder: PEB, then its parameters, then `CurrentDirectory.DosPath` (offsets of 64-bit Windows,
/// unchanged since Vista). `None` when the process can't be read.
fn working_folder(pid: u32) -> Option<String> {
    #[repr(C)]
    #[derive(Default)]
    struct Basic {
        exit_status: isize,
        peb: usize,
        affinity: usize,
        priority: isize,
        pid: usize,
        parent: usize,
    }
    // SAFETY: plain reads of another process's memory into buffers of the given sizes; the handle is closed here.
    unsafe {
        let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, false, pid).ok()?;
        let read = |at: usize, buf: *mut core::ffi::c_void, len: usize| {
            let mut got = 0usize;
            ReadProcessMemory(h, at as *const _, buf, len, Some(&mut got)).is_ok() && got == len
        };
        let r = (|| {
            let mut b = Basic::default();
            let mut ret = 0u32;
            if NtQueryInformationProcess(h, 0, &mut b as *mut _ as *mut _, std::mem::size_of::<Basic>() as u32, &mut ret) != 0 || b.peb == 0 {
                return None;
            }
            let mut params = 0usize;
            if !read(b.peb + 0x20, &mut params as *mut _ as *mut _, 8) || params == 0 {
                return None;
            }
            let (mut len, mut buf) = (0u16, 0usize);
            if !read(params + 0x38, &mut len as *mut _ as *mut _, 2) || !read(params + 0x40, &mut buf as *mut _ as *mut _, 8) || len == 0 || buf == 0 {
                return None;
            }
            let mut text = vec![0u16; (len / 2) as usize];
            read(buf, text.as_mut_ptr() as *mut _, len as usize).then(|| String::from_utf16_lossy(&text))
        })();
        let _ = CloseHandle(h);
        r
    }
}

/// Whether the app offers to close `l`: not this program, not Windows' own shell (closing explorer.exe takes the taskbar and the
/// desktop with it), not the system's processes.
pub fn can_close(l: &Locker) -> bool {
    const NEVER: [&str; 10] =
        ["explorer.exe", "windows explorer", "csrss.exe", "wininit.exe", "winlogon.exe", "services.exe", "lsass.exe", "svchost.exe", "dwm.exe", "system"];
    l.pid != std::process::id() && l.pid > 4 && !NEVER.contains(&l.name.to_lowercase().as_str())
}

/// Asks the program to close as its own close button would: `WM_CLOSE` to each of its visible top-level windows (it may still ask
/// to save). Returns how many windows were asked; 0 when it has none of its own (a shell inside a terminal, a background program).
pub fn ask_to_close(pid: u32) -> usize {
    unsafe extern "system" fn each(h: HWND, lp: LPARAM) -> BOOL {
        // SAFETY: `lp` points at the (pid, count) pair below for the length of EnumWindows.
        unsafe {
            let st = &mut *(lp.0 as *mut (u32, usize));
            let mut pid = 0u32;
            GetWindowThreadProcessId(h, Some(&mut pid));
            // (a window owned by a hidden one counts as the program's own: a Windows Forms dialog's owner is a hidden "parking"
            // window, so the form people see has an owner)
            let free = GetWindow(h, GW_OWNER).map_or(true, |o| o.is_invalid() || !IsWindowVisible(o).as_bool());
            if pid == st.0 && IsWindowVisible(h).as_bool() && free {
                let _ = PostMessageW(Some(h), WM_CLOSE, WPARAM(0), LPARAM(0));
                st.1 += 1;
            }
        }
        BOOL(1)
    }
    let mut st = (pid, 0usize);
    // SAFETY: the callback only reads windows and posts a message.
    unsafe {
        let _ = EnumWindows(Some(each), LPARAM(&mut st as *mut _ as isize));
    }
    st.1
}

/// Ends the program at once (unsaved work in it is lost): only on the user's explicit "Force close".
pub fn end(pid: u32) -> anyhow::Result<()> {
    // SAFETY: the handle is closed here.
    unsafe {
        let h = OpenProcess(PROCESS_TERMINATE, false, pid)?;
        let r = TerminateProcess(h, 1);
        let _ = CloseHandle(h);
        r?;
    }
    Ok(())
}

/// Whether the process is still running.
pub fn running(pid: u32) -> bool {
    // SAFETY: the handle is closed here.
    unsafe {
        let Ok(h) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else { return false };
        let mut code = 0u32;
        let alive = GetExitCodeProcess(h, &mut code).is_ok() && code == 259;
        let _ = CloseHandle(h);
        alive
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    /// A file this test holds open is reported with this process; once closed, nothing holds it.
    #[test]
    fn a_file_held_open_names_the_program_that_holds_it() {
        let dir = std::env::temp_dir().join(format!("rf-lockers-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("held.txt");
        let mut f = std::fs::File::create(&path).unwrap();
        f.write_all(b"x").unwrap();
        let held = super::who_holds(&[path.clone()]).unwrap();
        assert!(held.iter().any(|l| l.pid == std::process::id()), "{held:?}");
        drop(f);
        let free = super::who_holds(&[path.clone()]).unwrap();
        assert!(!free.iter().any(|l| l.pid == std::process::id()), "{free:?}");
        // a folder is asked about through its files
        let f2 = std::fs::File::open(&path).unwrap();
        let by_folder = super::who_holds(&[dir.clone()]).unwrap();
        assert!(by_folder.iter().any(|l| l.pid == std::process::id()), "{by_folder:?}");
        drop(f2);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A program whose working folder is inside a folder holds the folder: it is named for the folder and for its parent, not
    /// for a folder beside it.
    #[test]
    fn a_program_working_in_a_folder_is_named_for_it() {
        use std::os::windows::process::CommandExt;
        let base = std::env::temp_dir().join(format!("rf-lockers-cwd-{}", std::process::id()));
        let inner = base.join("work").join("deeper");
        std::fs::create_dir_all(&inner).unwrap();
        std::fs::create_dir_all(base.join("worker")).unwrap();
        // (a program that waits in the folder; CREATE_NO_WINDOW)
        let mut child = std::process::Command::new("powershell")
            .args(["-NoProfile", "-NonInteractive", "-Command", "Start-Sleep 20"])
            .current_dir(&inner)
            .creation_flags(0x08000000)
            .spawn()
            .unwrap();
        let pid = child.id();
        let held = |d: &std::path::Path| super::working_in(&[d.to_path_buf()]).iter().any(|l| l.pid == pid);
        let seen = (0..100).any(|_| {
            std::thread::sleep(std::time::Duration::from_millis(50));
            held(&inner)
        });
        let (parent, beside) = (held(&base.join("work")), held(&base.join("worker")));
        let _ = child.kill();
        let _ = child.wait();
        let _ = std::fs::remove_dir_all(&base);
        assert!(seen, "the child's own folder");
        assert!(parent, "the folder around it");
        assert!(!beside, "a folder whose name only starts the same");
    }

    #[test]
    fn inside_is_the_folder_or_below_it() {
        assert!(super::inside(r"C:\A\b\", r"c:\a\b"));
        assert!(super::inside(r"C:\A\b\c", r"c:\a\b"));
        assert!(!super::inside(r"C:\A\bc", r"c:\a\b"));
    }

    /// Windows' own shell and this program are never offered for closing.
    #[test]
    fn the_shell_and_this_program_are_not_closed() {
        use super::{Locker, can_close};
        assert!(!can_close(&Locker { pid: 1234, name: "explorer.exe".into() }));
        assert!(!can_close(&Locker { pid: std::process::id(), name: "rustyfiles.exe".into() }));
        assert!(can_close(&Locker { pid: 1234, name: "Code.exe".into() }));
    }
}