use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::{Path, PathBuf};
use wtf_string::Wtf16String;
use windows_sys::Win32::Foundation::{
ERROR_DIRECTORY, ERROR_FILE_NOT_FOUND, ERROR_INVALID_FUNCTION, ERROR_INVALID_NAME,
ERROR_NOT_SUPPORTED, ERROR_PATH_NOT_FOUND, HANDLE, INVALID_HANDLE_VALUE,
};
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, CreateFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_CASE_SENSITIVE_INFO,
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY, FILE_NAME_NORMALIZED,
FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FileCaseSensitiveInfo,
GetFileInformationByHandle, GetFileInformationByHandleEx, GetFinalPathNameByHandleW,
GetVolumeInformationByHandleW, OPEN_EXISTING, VOLUME_NAME_DOS,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OpenFailure {
NotFound,
NotADirectory,
Unsupported,
Retryable,
InvalidPath,
RetryUnavailable,
}
impl OpenFailure {
pub fn is_retryable(self) -> bool {
match self {
OpenFailure::NotFound | OpenFailure::Unsupported | OpenFailure::Retryable => true,
OpenFailure::NotADirectory
| OpenFailure::InvalidPath
| OpenFailure::RetryUnavailable => false,
}
}
}
#[derive(Debug)]
pub struct OpenError {
failure: OpenFailure,
source: std::io::Error,
}
impl OpenError {
pub(crate) fn new(failure: OpenFailure, source: std::io::Error) -> Self {
Self { failure, source }
}
pub(crate) fn synthetic(failure: OpenFailure, code: u32) -> Self {
Self::new(
failure,
std::io::Error::from_raw_os_error(
i32::try_from(code).expect("a WIN32_ERROR always fits an i32"),
),
)
}
pub fn failure(&self) -> OpenFailure {
self.failure
}
pub fn code(&self) -> FailureCode {
win32_code(&self.source)
}
pub(crate) fn detail(&self) -> FaultDetail {
FaultDetail {
failure: self.failure,
code: self.code(),
}
}
}
impl std::fmt::Display for OpenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}: {}", self.failure, self.source)
}
}
impl std::error::Error for OpenError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FailureCode {
Win32(u32),
HResult(i32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FaultDetail {
pub failure: OpenFailure,
pub code: FailureCode,
}
impl FaultDetail {
pub(crate) fn synthetic(failure: OpenFailure, code: u32) -> Self {
Self {
failure,
code: FailureCode::Win32(code),
}
}
pub(crate) fn retry_unavailable(error: &std::io::Error) -> Self {
Self {
failure: OpenFailure::RetryUnavailable,
code: win32_code(error),
}
}
}
pub(crate) fn win32_code(error: &std::io::Error) -> FailureCode {
let code = error.raw_os_error().unwrap_or(0);
FailureCode::Win32(u32::try_from(code).unwrap_or(0))
}
pub(crate) fn classify_detail(error: &std::io::Error) -> FaultDetail {
FaultDetail {
failure: classify(error),
code: win32_code(error),
}
}
pub(crate) fn classify(error: &std::io::Error) -> OpenFailure {
let Some(code) = error.raw_os_error() else {
return OpenFailure::Retryable;
};
let Ok(code) = u32::try_from(code) else {
return OpenFailure::Retryable;
};
match code {
ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => OpenFailure::NotFound,
ERROR_DIRECTORY => OpenFailure::NotADirectory,
ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED => OpenFailure::Unsupported,
ERROR_INVALID_NAME => OpenFailure::InvalidPath,
_ => OpenFailure::Retryable,
}
}
pub(crate) fn wide_path(path: &Path) -> Result<Wtf16String, OpenError> {
let wide = Wtf16String::from_os_str(path.as_os_str());
if wide.has_interior_nul() {
return Err(OpenError::synthetic(
OpenFailure::InvalidPath,
ERROR_INVALID_NAME,
));
}
Ok(wide)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct DirectoryId {
volume_serial: u32,
file_index: u64,
}
fn identify(handle: HANDLE) -> Result<DirectoryId, OpenError> {
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
let ok = unsafe { GetFileInformationByHandle(handle, &mut info) };
if ok == 0 {
let source = std::io::Error::last_os_error();
return Err(OpenError::new(classify(&source), source));
}
if info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == 0 {
return Err(OpenError::synthetic(
OpenFailure::NotADirectory,
ERROR_DIRECTORY,
));
}
Ok(DirectoryId {
volume_serial: info.dwVolumeSerialNumber,
file_index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
})
}
const FILE_CS_FLAG_CASE_SENSITIVE_DIR: u32 = 0x0000_0001;
fn is_case_sensitive_dir(handle: HANDLE) -> bool {
let mut info = FILE_CASE_SENSITIVE_INFO { Flags: 0 };
let ok = unsafe {
GetFileInformationByHandleEx(
handle,
FileCaseSensitiveInfo,
std::ptr::from_mut(&mut info).cast(),
u32::try_from(size_of::<FILE_CASE_SENSITIVE_INFO>())
.expect("this fixed, small struct's size always fits a u32"),
)
};
ok != 0 && info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0
}
pub struct DirectoryHandle {
handle: OwnedHandle,
identity: DirectoryId,
case_sensitive: bool,
}
impl DirectoryHandle {
pub fn open(path: &Path) -> Result<Self, OpenError> {
let wide = wide_path(path)?;
let raw = unsafe {
CreateFileW(
wide.as_terminated_ptr(),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
std::ptr::null(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
std::ptr::null_mut(),
)
};
if raw == INVALID_HANDLE_VALUE {
let source = std::io::Error::last_os_error();
return Err(OpenError::new(classify(&source), source));
}
let handle = unsafe { OwnedHandle::from_raw_handle(raw) };
let identity = identify(handle.as_raw_handle())?;
let case_sensitive = is_case_sensitive_dir(handle.as_raw_handle());
Ok(Self {
handle,
identity,
case_sensitive,
})
}
pub(crate) fn identity(&self) -> DirectoryId {
self.identity
}
pub(crate) fn is_case_sensitive(&self) -> bool {
self.case_sensitive
}
pub(crate) fn volume_identity(&self) -> Result<VolumeIdentity, OpenError> {
volume_identity(self.as_raw())
}
pub(crate) fn canonical_path(&self) -> Result<PathBuf, OpenError> {
canonical_path(self.as_raw())
}
pub(crate) fn into_handle(self) -> OwnedHandle {
self.handle
}
pub(crate) fn as_raw(&self) -> HANDLE {
self.handle.as_raw_handle()
}
}
impl std::fmt::Debug for DirectoryHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DirectoryHandle")
.field("handle", &self.as_raw())
.finish()
}
}
#[derive(Clone, Debug)]
pub struct VolumeIdentity {
volume_serial: u32,
filesystem_name: Wtf16String,
volume_label: Wtf16String,
}
impl PartialEq for VolumeIdentity {
fn eq(&self, other: &Self) -> bool {
self.volume_serial == other.volume_serial
}
}
impl Eq for VolumeIdentity {}
impl VolumeIdentity {
#[must_use]
pub fn filesystem_name(&self) -> String {
self.filesystem_name.to_string_lossy()
}
#[must_use]
pub fn volume_label(&self) -> String {
self.volume_label.to_string_lossy()
}
#[cfg(any(test, feature = "test-util"))]
pub(crate) fn synthetic(volume_serial: u32, filesystem_name: &str, volume_label: &str) -> Self {
Self {
volume_serial,
filesystem_name: Wtf16String::from_os_str(std::ffi::OsStr::new(filesystem_name)),
volume_label: Wtf16String::from_os_str(std::ffi::OsStr::new(volume_label)),
}
}
#[cfg(feature = "test-util")]
#[must_use]
pub fn for_test(volume_serial: u32, filesystem_name: &str, volume_label: &str) -> Self {
Self::synthetic(volume_serial, filesystem_name, volume_label)
}
}
fn volume_identity(handle: HANDLE) -> Result<VolumeIdentity, OpenError> {
const BUFFER_UNITS: usize = 261;
let mut volume_label = [0u16; BUFFER_UNITS];
let mut filesystem_name = [0u16; BUFFER_UNITS];
let mut volume_serial = 0u32;
let ok = unsafe {
GetVolumeInformationByHandleW(
handle,
volume_label.as_mut_ptr(),
u32::try_from(volume_label.len()).expect("a fixed small buffer size fits a u32"),
&mut volume_serial,
std::ptr::null_mut(),
std::ptr::null_mut(),
filesystem_name.as_mut_ptr(),
u32::try_from(filesystem_name.len()).expect("a fixed small buffer size fits a u32"),
)
};
if ok == 0 {
let source = std::io::Error::last_os_error();
return Err(OpenError::new(classify(&source), source));
}
Ok(VolumeIdentity {
volume_serial,
filesystem_name: Wtf16String::from_units(trim_nul(&filesystem_name)),
volume_label: Wtf16String::from_units(trim_nul(&volume_label)),
})
}
fn trim_nul(units: &[u16]) -> &[u16] {
units
.iter()
.position(|&unit| unit == 0)
.map_or(units, |end| &units[..end])
}
fn canonical_path(handle: HANDLE) -> Result<PathBuf, OpenError> {
let mut buffer = vec![0u16; 512];
loop {
let written = unsafe {
GetFinalPathNameByHandleW(
handle,
buffer.as_mut_ptr(),
u32::try_from(buffer.len()).unwrap_or(u32::MAX),
VOLUME_NAME_DOS | FILE_NAME_NORMALIZED,
)
};
if written == 0 {
let source = std::io::Error::last_os_error();
return Err(OpenError::new(classify(&source), source));
}
let written = written as usize;
if written < buffer.len() {
buffer.truncate(written);
return Ok(PathBuf::from(std::ffi::OsString::from_wide(&buffer)));
}
buffer.resize(written, 0);
}
}
#[cfg(test)]
mod tests;