#![deny(clippy::undocumented_unsafe_blocks)]
use std::ffi::OsStr;
use std::fs::File;
use std::io;
use std::mem::offset_of;
use std::mem::size_of;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::AsHandle;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::os::windows::io::RawHandle;
use std::ptr::null;
use std::ptr::null_mut;
use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES;
use windows_sys::Wdk::Storage::FileSystem::FILE_CREATE;
use windows_sys::Wdk::Storage::FileSystem::FILE_DIRECTORY_FILE;
use windows_sys::Wdk::Storage::FileSystem::FILE_INFORMATION_CLASS;
use windows_sys::Wdk::Storage::FileSystem::FILE_NON_DIRECTORY_FILE;
use windows_sys::Wdk::Storage::FileSystem::FILE_OPEN;
use windows_sys::Wdk::Storage::FileSystem::FILE_OPEN_REPARSE_POINT;
use windows_sys::Wdk::Storage::FileSystem::FILE_RENAME_INFORMATION;
use windows_sys::Wdk::Storage::FileSystem::FILE_SYNCHRONOUS_IO_NONALERT;
use windows_sys::Wdk::Storage::FileSystem::FileDispositionInformation;
use windows_sys::Wdk::Storage::FileSystem::FileDispositionInformationEx;
use windows_sys::Wdk::Storage::FileSystem::FileRenameInformation;
use windows_sys::Wdk::Storage::FileSystem::FileRenameInformationEx;
use windows_sys::Wdk::Storage::FileSystem::NtCreateFile;
use windows_sys::Wdk::Storage::FileSystem::NtSetInformationFile;
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
use windows_sys::Win32::Foundation::ERROR_NOT_SUPPORTED;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::OBJ_CASE_INSENSITIVE;
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
use windows_sys::Win32::Foundation::UNICODE_STRING;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_ACCESS_RIGHTS;
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_FLAG_DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_FLAG_POSIX_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_INFO;
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_INFO_EX;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAGS_AND_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::SYNCHRONIZE;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
use windows_sys::Win32::System::WindowsProgramming::FILE_RENAME_FLAG_POSIX_SEMANTICS;
use windows_sys::Win32::System::WindowsProgramming::FILE_RENAME_FLAG_REPLACE_IF_EXISTS;
use super::Leaf;
#[derive(Debug, Clone, Copy)]
pub(super) enum Disposition {
Open,
Create,
}
#[derive(Debug, Clone, Copy)]
pub(super) enum Kind {
Any,
Directory,
NonDirectory,
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Request {
pub(super) access: FILE_ACCESS_RIGHTS,
pub(super) disposition: Disposition,
pub(super) kind: Kind,
pub(super) attributes: FILE_FLAGS_AND_ATTRIBUTES,
}
impl Request {
pub(super) const fn open(access: FILE_ACCESS_RIGHTS) -> Self {
Self {
access,
disposition: Disposition::Open,
kind: Kind::Any,
attributes: 0,
}
}
}
const SHARE_ALL: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
fn wide(name: &OsStr) -> Vec<u16> {
name.encode_wide().collect()
}
fn length_u32(len: usize) -> io::Result<u32> {
u32::try_from(len).map_err(|_| io::Error::from(io::ErrorKind::InvalidFilename))
}
fn nt_error(status: i32) -> io::Error {
let code = unsafe { RtlNtStatusToDosError(status) };
io::Error::from_raw_os_error(code.cast_signed())
}
pub(super) fn create_at(
dir: BorrowedHandle<'_>,
name: Leaf<'_>,
request: Request,
) -> io::Result<OwnedHandle> {
let mut name_units = wide(name.as_os_str());
let name_bytes = u16::try_from(name_units.len().saturating_mul(size_of::<u16>()))
.map_err(|_| io::Error::from(io::ErrorKind::InvalidFilename))?;
let object_name = UNICODE_STRING {
Length: name_bytes,
MaximumLength: name_bytes,
Buffer: name_units.as_mut_ptr(),
};
let attributes = OBJECT_ATTRIBUTES {
Length: length_u32(size_of::<OBJECT_ATTRIBUTES>())?,
RootDirectory: dir.as_raw_handle(),
ObjectName: &raw const object_name,
Attributes: OBJ_CASE_INSENSITIVE,
SecurityDescriptor: null(),
SecurityQualityOfService: null(),
};
let disposition = match request.disposition {
Disposition::Open => FILE_OPEN,
Disposition::Create => FILE_CREATE,
};
let kind = match request.kind {
Kind::Any => 0,
Kind::Directory => FILE_DIRECTORY_FILE,
Kind::NonDirectory => FILE_NON_DIRECTORY_FILE,
};
let mut handle: HANDLE = null_mut();
let mut status_block = IO_STATUS_BLOCK::default();
let status = unsafe {
NtCreateFile(
&raw mut handle,
request.access | SYNCHRONIZE,
&raw const attributes,
&raw mut status_block,
null(),
request.attributes,
SHARE_ALL,
disposition,
kind | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
null(),
0,
)
};
if status < 0 {
return Err(nt_error(status));
}
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}
struct InfoBuffer {
words: Vec<u64>,
len: u32,
}
impl InfoBuffer {
fn new(bytes: &[u8], min_len: usize) -> io::Result<Self> {
let len = bytes.len().max(min_len);
let mut words = vec![0_u64; len.div_ceil(size_of::<u64>())];
for (word, chunk) in words.iter_mut().zip(bytes.chunks(size_of::<u64>())) {
let mut raw = [0_u8; size_of::<u64>()];
if let Some(head) = raw.get_mut(..chunk.len()) {
head.copy_from_slice(chunk);
}
*word = u64::from_ne_bytes(raw);
}
Ok(Self {
words,
len: length_u32(len)?,
})
}
}
fn put(bytes: &mut [u8], offset: usize, value: &[u8]) -> io::Result<()> {
bytes
.get_mut(offset..offset.saturating_add(value.len()))
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?
.copy_from_slice(value);
Ok(())
}
fn set_info(
handle: BorrowedHandle<'_>,
class: FILE_INFORMATION_CLASS,
info: &InfoBuffer,
) -> io::Result<()> {
let mut status_block = IO_STATUS_BLOCK::default();
let status = unsafe {
NtSetInformationFile(
handle.as_raw_handle(),
&raw mut status_block,
info.words.as_ptr().cast(),
info.len,
class,
)
};
if status < 0 {
Err(nt_error(status))
} else {
Ok(())
}
}
fn rename_info(root: RawHandle, name: &[u16], flags: u32) -> io::Result<InfoBuffer> {
let name_bytes = name.len().saturating_mul(size_of::<u16>());
let name_offset = offset_of!(FILE_RENAME_INFORMATION, FileName);
let mut bytes = vec![
0_u8;
name_offset
.saturating_add(name_bytes)
.saturating_add(size_of::<u16>())
];
put(
&mut bytes,
offset_of!(FILE_RENAME_INFORMATION, Anonymous),
&flags.to_ne_bytes(),
)?;
put(
&mut bytes,
offset_of!(FILE_RENAME_INFORMATION, RootDirectory),
&root.addr().to_ne_bytes(),
)?;
put(
&mut bytes,
offset_of!(FILE_RENAME_INFORMATION, FileNameLength),
&length_u32(name_bytes)?.to_ne_bytes(),
)?;
for (index, unit) in name.iter().enumerate() {
let at = name_offset.saturating_add(index.saturating_mul(size_of::<u16>()));
put(&mut bytes, at, &unit.to_ne_bytes())?;
}
InfoBuffer::new(&bytes, size_of::<FILE_RENAME_INFORMATION>())
}
fn has_code(err: &io::Error, code: u32) -> bool {
err.raw_os_error().map(i32::cast_unsigned) == Some(code)
}
fn lacks_ex_classes(err: &io::Error) -> bool {
has_code(err, ERROR_INVALID_PARAMETER) || has_code(err, ERROR_NOT_SUPPORTED)
}
pub(super) fn rename_within(
dir: BorrowedHandle<'_>,
from: Leaf<'_>,
to: Leaf<'_>,
) -> io::Result<()> {
let source = create_at(dir, from, Request::open(DELETE | FILE_READ_ATTRIBUTES))?;
let target = wide(to.as_os_str());
let root = dir.as_raw_handle();
let posix = rename_info(
root,
&target,
FILE_RENAME_FLAG_REPLACE_IF_EXISTS | FILE_RENAME_FLAG_POSIX_SEMANTICS,
)?;
match set_info(source.as_handle(), FileRenameInformationEx, &posix) {
Err(err) if lacks_ex_classes(&err) => {
let legacy = rename_info(root, &target, FILE_RENAME_FLAG_REPLACE_IF_EXISTS)?;
set_info(source.as_handle(), FileRenameInformation, &legacy)
}
other => other,
}
}
pub(super) fn remove_file(dir: BorrowedHandle<'_>, name: Leaf<'_>) -> io::Result<()> {
let file = File::from(create_at(
dir,
name,
Request::open(DELETE | FILE_READ_ATTRIBUTES),
)?);
if file.metadata()?.is_dir() {
return Err(io::Error::from(io::ErrorKind::IsADirectory));
}
let posix = InfoBuffer::new(
&(FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS).to_ne_bytes(),
size_of::<FILE_DISPOSITION_INFO_EX>(),
)?;
match set_info(file.as_handle(), FileDispositionInformationEx, &posix) {
Err(err) if lacks_ex_classes(&err) => {
let legacy = InfoBuffer::new(&[1], size_of::<FILE_DISPOSITION_INFO>())?;
set_info(file.as_handle(), FileDispositionInformation, &legacy)
}
other => other,
}
}