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.

10.6 KB
Raw Blame
//! Network locations: shares of a server (`\\server` is not listable with FindFirstFile) and the
//! user's network shortcuts. Blocking and potentially slow (SMB timeouts): off the UI thread.

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

use windows::Win32::NetworkManagement::NetManagement::NetApiBufferFree;
use windows::Win32::Storage::FileSystem::{NetShareEnum, SHARE_INFO_1, STYPE_DISKTREE, STYPE_SPECIAL};
use windows::core::PCWSTR;

use crate::wide::wide;

const MAX_PREFERRED_LENGTH: u32 = u32::MAX;
const ERROR_MORE_DATA: u32 = 234;

/// `\\server` or `\\server\` (no share part) → `Some("server")`.
pub fn server_root(path: &Path) -> Option<String> {
    let s = path.to_str()?;
    let rest = s.strip_prefix(r"\\")?;
    if rest.starts_with('?') || rest.starts_with('.') {
        return None;
    }
    let rest = rest.trim_end_matches('\\');
    (!rest.is_empty() && !rest.contains('\\')).then(|| rest.to_string())
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Share {
    pub name: String,
    pub remark: String,
}

/// Disk shares of `server` (hidden `$` and admin shares excluded). A server that refuses the list to a stranger (a Synology NAS
/// without a session yet) gets one: a connection to its `IPC$` with the credentials Windows keeps for it, or Windows' own sign-in
/// window when it has none, and the list is asked for again. Discussion 737: `\\synology` failed until a share of it had been
/// opened, which made the session; File Explorer connects first the same way.
pub fn shares(server: &str) -> std::io::Result<Vec<Share>> {
    match list_shares(server) {
        Err(e) if connect_ipc(server) => list_shares(server).map_err(|_| e),
        r => r,
    }
}

/// A connection to `\\server\IPC$` (temporary, not remembered), asking for credentials only when Windows has none that work.
fn connect_ipc(server: &str) -> bool {
    use windows::Win32::NetworkManagement::WNet::{CONNECT_INTERACTIVE, CONNECT_TEMPORARY, NETRESOURCEW, RESOURCETYPE_ANY, WNetAddConnection2W};
    let mut remote = wide(format!(r"\\{server}\IPC$"));
    let res = NETRESOURCEW { dwType: RESOURCETYPE_ANY, lpRemoteName: windows::core::PWSTR(remote.as_mut_ptr()), ..Default::default() };
    let rc = unsafe { WNetAddConnection2W(&res, PCWSTR::null(), PCWSTR::null(), CONNECT_TEMPORARY | CONNECT_INTERACTIVE) };
    if rc.0 != 0 {
        log::info!("shares: connecting to {server} failed ({})", rc.0);
    }
    rc.0 == 0
}

fn list_shares(server: &str) -> std::io::Result<Vec<Share>> {
    let w = wide(format!(r"\\{server}"));
    let mut out = Vec::new();
    let mut resume: u32 = 0;
    loop {
        let mut buf: *mut u8 = std::ptr::null_mut();
        let (mut read, mut total) = (0u32, 0u32);
        let rc = unsafe {
            NetShareEnum(PCWSTR(w.as_ptr()), 1, &mut buf, MAX_PREFERRED_LENGTH, &mut read, &mut total, Some(&mut resume))
        };
        if rc != 0 && rc != ERROR_MORE_DATA {
            if !buf.is_null() {
                unsafe { NetApiBufferFree(Some(buf as *const _)) };
            }
            return Err(std::io::Error::from_raw_os_error(rc as i32));
        }
        if !buf.is_null() {
            let items = unsafe { std::slice::from_raw_parts(buf as *const SHARE_INFO_1, read as usize) };
            for it in items {
                if it.shi1_type.0 & !STYPE_SPECIAL.0 != STYPE_DISKTREE.0 || it.shi1_type.0 & STYPE_SPECIAL.0 != 0 {
                    continue;
                }
                let name = unsafe { it.shi1_netname.to_string() }.unwrap_or_default();
                if name.is_empty() || name.ends_with('$') {
                    continue;
                }
                let remark = if it.shi1_remark.is_null() { String::new() } else { unsafe { it.shi1_remark.to_string() }.unwrap_or_default() };
                out.push(Share { name, remark });
            }
            unsafe { NetApiBufferFree(Some(buf as *const _)) };
        }
        if rc != ERROR_MORE_DATA {
            break;
        }
    }
    out.sort_by(|a, b| rf_core::sort::natural_cmp(&a.name, &b.name));
    Ok(out)
}

/// Folders under `%APPDATA%\Microsoft\Windows\Network Shortcuts` ("Add a network location").
/// Each is a folder holding `target.lnk`; returns (display name, target).
pub fn network_shortcuts() -> Vec<(String, PathBuf)> {
    let Some(dir) = std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Network Shortcuts")) else {
        return Vec::new();
    };
    let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
    let mut out: Vec<(String, PathBuf)> = rd
        .filter_map(|e| e.ok())
        .filter_map(|e| {
            let p = e.path();
            let lnk = p.join("target.lnk");
            let target = crate::shortcut::resolve(&lnk).ok()?.target;
            if target.as_os_str().is_empty() {
                return None;
            }
            Some((e.file_name().to_string_lossy().into_owned(), target))
        })
        .collect();
    out.sort_by(|a, b| rf_core::sort::natural_cmp(&a.0, &b.0));
    out
}

/// The network drives the user mapped to come back at every sign-in (`HKCU\Network\<letter>`) that are not connected now, connected
/// again with what Windows remembers for them (no window is shown: a drive whose server is away just stays away). Each letter with
/// the answer (0: connected). Blocks while a server is slow: call off the UI thread.
///
/// WHY (issue 751: with rustyfiles as the Windows shell, a VMware shared folder mapped as Z: was missing and its "network location"
/// led nowhere). Explorer connects them again at every sign-in ("Restoring network connections"); with rustyfiles as the shell,
/// Explorer does not start, so nothing did.
pub fn restore_remembered_drives() -> Vec<(char, u32)> {
    // (in mpr.dll but not in the SDK's import library: looked up at run time)
    type Restore = unsafe extern "system" fn(*mut std::ffi::c_void, *const u16, i32) -> u32;
    let restore: Option<Restore> = unsafe {
        windows::Win32::System::LibraryLoader::LoadLibraryW(windows::core::w!("mpr.dll"))
            .ok()
            .and_then(|m| windows::Win32::System::LibraryLoader::GetProcAddress(m, windows::core::s!("WNetRestoreSingleConnectionW")))
            .map(|f| std::mem::transmute::<unsafe extern "system" fn() -> isize, Restore>(f))
    };
    let Some(restore) = restore else { return Vec::new() };
    let remembered: Vec<char> = windows_registry::CURRENT_USER
        .open("Network")
        .and_then(|k| k.keys().map(|it| it.filter_map(|n| drive_letter_key(&n)).collect()))
        .unwrap_or_default();
    let present = unsafe { windows::Win32::Storage::FileSystem::GetLogicalDrives() };
    remembered
        .into_iter()
        .filter(|l| present & (1 << (*l as u32 - 'A' as u32)) == 0)
        .map(|l| {
            let device = wide(format!("{l}:"));
            (l, unsafe { restore(std::ptr::null_mut(), device.as_ptr(), 0) })
        })
        .collect()
}

/// A key under `HKCU\Network` is a drive letter (`Z`); anything else is not a mapped drive.
fn drive_letter_key(name: &str) -> Option<char> {
    let mut chars = name.chars();
    let c = chars.next()?.to_ascii_uppercase();
    (chars.next().is_none() && c.is_ascii_uppercase()).then_some(c)
}

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

    #[test]
    fn server_root_parsing() {
        assert_eq!(server_root(Path::new(r"\\nas")), Some("nas".into()));
        assert_eq!(server_root(Path::new(r"\\nas\")), Some("nas".into()));
        assert_eq!(server_root(Path::new(r"\\nas\share")), None);
        assert_eq!(server_root(Path::new(r"\\?\C:\x")), None);
        assert_eq!(server_root(Path::new(r"C:\x")), None);
    }

    #[test]
    fn local_shares() {
        // localhost always answers (may legitimately be empty without user shares)
        let r = shares("localhost");
        assert!(r.is_ok(), "{r:?}");
        eprintln!("{:?}", r.unwrap());
        eprintln!("{:?}", network_shortcuts());
    }
}

/// Windows' own "Map network drive" dialog (drive letter, folder, reconnect at sign-in,
/// other credentials). Modal to `owner`; returns when it closes.
pub fn map_drive_dialog(owner: isize) {
    use windows::Win32::Foundation::HWND;
    use windows::Win32::NetworkManagement::WNet::{RESOURCETYPE_DISK, WNetConnectionDialog};
    // SAFETY: plain Win32 dialog call on a valid (or null) owner window
    unsafe {
        let _ = WNetConnectionDialog(HWND(owner as *mut _), RESOURCETYPE_DISK.0);
    }
}

/// Windows' "Disconnect network drive" dialog.
pub fn disconnect_drive_dialog(owner: isize) {
    use windows::Win32::Foundation::HWND;
    use windows::Win32::NetworkManagement::WNet::{RESOURCETYPE_DISK, WNetDisconnectDialog};
    // SAFETY: plain Win32 dialog call on a valid (or null) owner window
    unsafe {
        let _ = WNetDisconnectDialog(Some(HWND(owner as *mut _)), RESOURCETYPE_DISK.0);
    }
}


/// What a network link is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LinkType {
    Wifi,
    Ethernet,
    Other,
}

/// The link this machine reaches the network over: its kind and rate in Mbit/s (Wi-Fi's current transmit rate, Ethernet's link
/// speed). The interface is the routing table's best one toward an outside address; nothing is sent. None without a route or a rate.
pub fn lan_link() -> Option<(LinkType, u32)> {
    use windows::Win32::NetworkManagement::IpHelper::{GetBestInterface, GetIfEntry2, MIB_IF_ROW2};
    let mut index = 0u32;
    if unsafe { GetBestInterface(u32::from_ne_bytes([8, 8, 8, 8]), &mut index) } != 0 {
        return None;
    }
    let mut row = MIB_IF_ROW2 { InterfaceIndex: index, ..Default::default() };
    unsafe { GetIfEntry2(&mut row) }.ok().ok()?;
    // IF_TYPE_IEEE80211, IF_TYPE_ETHERNET_CSMACD
    let kind = match row.Type {
        71 => LinkType::Wifi,
        6 => LinkType::Ethernet,
        _ => LinkType::Other,
    };
    let bps = row.TransmitLinkSpeed;
    (bps != u64::MAX && bps >= 1_000_000).then(|| (kind, (bps / 1_000_000).min(u64::from(u32::MAX)) as u32))
}

#[cfg(test)]
mod remembered_tests {
    #[test]
    fn only_a_single_letter_key_is_a_mapped_drive() {
        assert_eq!(super::drive_letter_key("Z"), Some('Z'));
        assert_eq!(super::drive_letter_key("z"), Some('Z'));
        assert_eq!(super::drive_letter_key("ZZ"), None);
        assert_eq!(super::drive_letter_key(""), None);
        assert_eq!(super::drive_letter_key("1"), None);
    }

    /// Reads the user's real list and connects nothing that is already there (here: none or all present). Never panics.
    #[test]
    fn restoring_with_nothing_missing_does_nothing() {
        let present = unsafe { windows::Win32::Storage::FileSystem::GetLogicalDrives() };
        for (l, _) in super::restore_remembered_drives() {
            assert_eq!(present & (1 << (l as u32 - 'A' as u32)), 0, "{l}: was there already and was asked again");
        }
    }
}