use core::ffi::c_void;
use core::ptr;
use crate::fs::{
FileTimes, FileType, LockKind, Metadata, OpenOptions, RawDirEntry, Space, UnixMetadata,
};
use crate::path::{wide_to_wtf8, with_wide};
use crate::sys::io::{IoStatusBlock, Overlapped, STATUS_PENDING, completed, wait_completion};
use crate::sys::{cvt, dll, last_error};
use crate::time::Timestamp;
use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};
#[derive(Clone, Copy, Default)]
#[repr(C)]
struct FileTime {
low: u32,
high: u32,
}
#[derive(Default)]
#[repr(C)]
struct ByHandleFileInformation {
attributes: u32,
creation_time: FileTime,
last_access_time: FileTime,
last_write_time: FileTime,
volume_serial_number: u32,
file_size_high: u32,
file_size_low: u32,
number_of_links: u32,
file_index_high: u32,
file_index_low: u32,
}
#[derive(Default)]
#[repr(C)]
struct FileBasicInfo {
creation_time: i64,
last_access_time: i64,
last_write_time: i64,
change_time: i64,
attributes: u32,
}
#[derive(Default)]
#[repr(C)]
struct FileAttributeTagInfo {
attributes: u32,
reparse_tag: u32,
}
dll!("kernel32.dll" {
fn CreateFileW(
name: *const u16,
access: u32,
share: u32,
security: *const c_void,
creation: u32,
flags: u32,
template: *mut c_void,
) -> *mut c_void;
fn SetLastError(code: u32);
fn GetFileType(handle: *mut c_void) -> u32;
fn GetFileInformationByHandle(handle: *mut c_void, info: *mut ByHandleFileInformation) -> i32;
fn GetFileInformationByHandleEx(
handle: *mut c_void,
class: i32,
info: *mut c_void,
size: u32,
) -> i32;
fn SetFileInformationByHandle(
handle: *mut c_void,
class: i32,
info: *const c_void,
size: u32,
) -> i32;
fn FlushFileBuffers(handle: *mut c_void) -> i32;
fn SetFileTime(
handle: *mut c_void,
creation: *const FileTime,
access: *const FileTime,
write: *const FileTime,
) -> i32;
fn LockFileEx(
handle: *mut c_void,
flags: u32,
reserved: u32,
len_low: u32,
len_high: u32,
overlapped: *mut Overlapped,
) -> i32;
fn CreateEventW(
security: *const c_void,
manual_reset: i32,
initial_state: i32,
name: *const u16,
) -> *mut c_void;
fn UnlockFile(
handle: *mut c_void,
offset_low: u32,
offset_high: u32,
len_low: u32,
len_high: u32,
) -> i32;
fn GetFileAttributesW(name: *const u16) -> u32;
fn CreateDirectoryW(name: *const u16, security: *const c_void) -> i32;
fn RemoveDirectoryW(name: *const u16) -> i32;
fn DeleteFileW(name: *const u16) -> i32;
fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32;
fn CreateHardLinkW(link: *const u16, original: *const u16, security: *const c_void) -> i32;
fn CreateSymbolicLinkW(link: *const u16, target: *const u16, flags: u32) -> u8;
fn DeviceIoControl(
handle: *mut c_void,
code: u32,
input: *const c_void,
input_size: u32,
output: *mut c_void,
output_size: u32,
returned: *mut u32,
overlapped: *mut Overlapped,
) -> i32;
fn GetFinalPathNameByHandleW(handle: *mut c_void, path: *mut u16, len: u32, flags: u32)
-> u32;
fn GetCurrentDirectoryW(len: u32, path: *mut u16) -> u32;
fn CopyFileExW(
from: *const u16,
to: *const u16,
progress: Option<ProgressRoutine>,
data: *const c_void,
cancel: *mut i32,
flags: u32,
) -> i32;
fn GetFullPathNameW(path: *const u16, len: u32, buf: *mut u16, file_part: *mut *mut u16)
-> u32;
fn SetCurrentDirectoryW(path: *const u16) -> i32;
});
#[repr(C)]
struct UnicodeString {
len: u16,
capacity: u16,
buf: *const u16,
}
#[repr(C)]
struct ObjectAttributes {
len: u32,
root: *mut c_void,
name: *const UnicodeString,
attributes: u32,
security_descriptor: *const c_void,
security_qos: *const c_void,
}
dll!("ntdll.dll" {
fn NtCreateFile(
handle: *mut *mut c_void,
access: u32,
attributes: *const ObjectAttributes,
status: *mut IoStatusBlock,
allocation_size: *const i64,
file_attributes: u32,
share: u32,
disposition: u32,
options: u32,
ea: *const c_void,
ea_len: u32,
) -> i32;
fn NtQueryDirectoryFile(
handle: *mut c_void,
event: *mut c_void,
apc_routine: *const c_void,
apc_context: *const c_void,
status: *mut IoStatusBlock,
info: *mut c_void,
len: u32,
class: i32,
single_entry: u8,
name: *const UnicodeString,
restart: u8,
) -> i32;
fn NtSetInformationFile(
handle: *mut c_void,
status: *mut IoStatusBlock,
info: *const c_void,
len: u32,
class: i32,
) -> i32;
fn NtQueryVolumeInformationFile(
handle: *mut c_void,
status: *mut IoStatusBlock,
info: *mut c_void,
len: u32,
class: i32,
) -> i32;
});
type ProgressRoutine = unsafe extern "system" fn(
total_size: i64,
total_transferred: i64,
stream_size: i64,
stream_transferred: i64,
stream: u32,
reason: u32,
source: *mut c_void,
destination: *mut c_void,
data: *const c_void,
) -> u32;
#[derive(Default)]
#[repr(C)]
struct FileStandardInfo {
allocation_size: i64,
end_of_file: i64,
links: u32,
delete_pending: u8,
directory: u8,
}
#[derive(Default)]
#[repr(C)]
struct FileFsFullSizeInformation {
total_units: i64,
caller_available_units: i64,
actual_available_units: i64,
sectors_per_unit: u32,
bytes_per_sector: u32,
}
const FILE_FS_FULL_SIZE_INFORMATION: i32 = 7;
const GENERIC_READ: u32 = 0x8000_0000;
const GENERIC_WRITE: u32 = 0x4000_0000;
const FILE_WRITE_DATA: u32 = 0x2;
const FILE_READ_ATTRIBUTES: u32 = 0x80;
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
const FILE_GENERIC_WRITE: u32 = 0x12_0116;
const FILE_LIST_DIRECTORY: u32 = 0x1;
const DELETE: u32 = 0x1_0000;
const SYNCHRONIZE: u32 = 0x10_0000;
const FILE_SHARE_ALL: u32 = 0x1 | 0x2 | 0x4;
const FILE_OPEN: u32 = 1;
const FILE_CREATE: u32 = 2;
const FILE_OPEN_IF: u32 = 3;
const FILE_OVERWRITE: u32 = 4;
const FILE_OPENED: usize = 1;
const FILE_DIRECTORY_FILE: u32 = 0x1;
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x20;
const FILE_NON_DIRECTORY_FILE: u32 = 0x40;
const FILE_OPEN_FOR_BACKUP_INTENT: u32 = 0x4000;
const FILE_OPEN_REPARSE_POINT: u32 = 0x20_0000;
const OBJ_CASE_INSENSITIVE: u32 = 0x40;
const STATUS_FILE_IS_A_DIRECTORY: i32 = 0xc000_00ba_u32 as i32;
const FILE_RENAME_INFORMATION: i32 = 10;
const FILE_LINK_INFORMATION: i32 = 11;
const FILE_DISPOSITION_DELETE: u32 = 0x1;
const FILE_DISPOSITION_POSIX_SEMANTICS: u32 = 0x2;
const CREATE_NEW: u32 = 1;
const OPEN_EXISTING: u32 = 3;
const OPEN_ALWAYS: u32 = 4;
const TRUNCATE_EXISTING: u32 = 5;
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x20_0000;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x200_0000;
const FILE_ATTRIBUTE_READONLY: u32 = 0x1;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;
const FILE_BASIC_INFO: i32 = 0;
const FILE_STANDARD_INFO: i32 = 1;
const FILE_ALLOCATION_INFO: i32 = 5;
const FILE_DISPOSITION_INFO: i32 = 4;
const FILE_END_OF_FILE_INFO: i32 = 6;
const FILE_ATTRIBUTE_TAG_INFO: i32 = 9;
const FILE_ID_BOTH_DIRECTORY_INFORMATION: i32 = 37;
const FILE_DISPOSITION_INFO_EX: i32 = 21;
const FILE_TYPE_DISK: u32 = 1;
const FILE_TYPE_CHAR: u32 = 2;
const FILE_TYPE_PIPE: u32 = 3;
const LOCKFILE_FAIL_IMMEDIATELY: u32 = 1;
const LOCKFILE_EXCLUSIVE_LOCK: u32 = 2;
const MOVEFILE_REPLACE_EXISTING: u32 = 1;
const SYMBOLIC_LINK_FLAG_DIRECTORY: u32 = 1;
const SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: u32 = 2;
const FSCTL_SET_REPARSE_POINT: u32 = 0x9_00a4;
const FSCTL_GET_REPARSE_POINT: u32 = 0x9_00a8;
const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16384;
const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xa000_0003;
const IO_REPARSE_TAG_SYMLINK: u32 = 0xa000_000c;
const REPARSE_TAG_NAME_SURROGATE: u32 = 0x2000_0000;
const SYMLINK_FLAG_RELATIVE: u32 = 1;
const SYMLINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: u32 = 2;
const ERROR_INVALID_FUNCTION: i32 = 1;
const ERROR_ACCESS_DENIED: i32 = 5;
const ERROR_NOT_SUPPORTED: i32 = 50;
const ERROR_NO_MORE_FILES: i32 = 18;
const ERROR_SHARING_VIOLATION: i32 = 32;
const ERROR_LOCK_VIOLATION: i32 = 33;
const ERROR_INVALID_PARAMETER: i32 = 87;
const ERROR_NOT_LOCKED: i32 = 158;
const ERROR_ALREADY_EXISTS: i32 = 183;
const ERROR_DIRECTORY: i32 = 267;
const ERROR_DIRECTORY_NOT_SUPPORTED: i32 = 336;
const ERROR_IO_PENDING: i32 = 997;
const ERROR_CANT_RESOLVE_FILENAME: i32 = 1921;
const ERROR_NOT_A_REPARSE_POINT: i32 = 4390;
const EPOCH_DIFFERENCE: i64 = 11_644_473_600;
const INTERVALS_PER_SEC: u64 = 10_000_000;
const LEGACY_MAX_PATH: usize = 248;
fn with_path<R>(path: &[u8], f: impl FnOnce(&[u16]) -> Result<R>) -> Result<R> {
const SEP: u16 = b'\\' as u16;
const QUERY: u16 = b'?' as u16;
const COLON: u16 = b':' as u16;
const DOT: u16 = b'.' as u16;
const VERBATIM: [u16; 4] = [SEP, SEP, QUERY, SEP];
const VERBATIM_UNC: [u16; 8] = [
SEP,
SEP,
QUERY,
SEP,
b'U' as u16,
b'N' as u16,
b'C' as u16,
SEP,
];
const ROOM: usize = VERBATIM_UNC.len();
fn finish<R>(
buf: &mut [u16],
full: usize,
original: &[u16],
f: impl FnOnce(&[u16]) -> Result<R>,
) -> Result<R> {
if full + 1 < LEGACY_MAX_PATH {
return f(original);
}
let (skip, prefix): (usize, &[u16]) = match &buf[ROOM..ROOM + full] {
[_, COLON, SEP, ..] => (0, &VERBATIM),
[SEP, SEP, DOT, SEP, ..] => (4, &VERBATIM),
[SEP, SEP, QUERY, SEP, ..] | [SEP, QUERY, QUERY, SEP, ..] => (0, &[]),
[SEP, SEP, ..] => (2, &VERBATIM_UNC),
_ => (0, &[]),
};
let start = ROOM + skip - prefix.len();
buf[start..start + prefix.len()].copy_from_slice(prefix);
f(&buf[start..=ROOM + full])
}
with_wide(path, |wide| {
let is_separator = |c: u16| c == SEP || c == b'/' as u16;
let len = wide.len() - 1;
if len == 0 || wide.starts_with(&VERBATIM) || wide.starts_with(&[SEP, QUERY, QUERY, SEP]) {
return f(wide);
}
if len < LEGACY_MAX_PATH {
let drive =
wide[1] == COLON && !is_separator(wide[0]) && (len == 2 || is_separator(wide[2]));
let unc = len >= 2 && is_separator(wide[0]) && is_separator(wide[1]);
if drive || unc {
return f(wide);
}
}
let full_path = |buf: &mut [u16]| {
let room = &mut buf[ROOM..];
let full = unsafe {
GetFullPathNameW(
wide.as_ptr(),
room.len().min(u32::MAX as usize) as u32,
room.as_mut_ptr(),
ptr::null_mut(),
)
} as usize;
if full == 0 {
Err(last_error())
} else {
Ok(full)
}
};
let mut stack = [0u16; 1024];
let full = full_path(&mut stack)?;
if full < stack.len() - ROOM {
return finish(&mut stack, full, wide, f);
}
#[cfg(feature = "alloc")]
{
let mut heap = alloc::vec::Vec::new();
heap.try_reserve_exact(ROOM + full)
.map_err(|_| ErrorKind::OutOfMemory)?;
heap.resize(ROOM + full, 0u16);
let full = full_path(&mut heap)?;
if full < heap.len() - ROOM {
return finish(&mut heap, full, wide, f);
}
}
Err(ErrorKind::InvalidFilename.into())
})
}
pub(crate) fn create_file(
path: &[u16],
access: u32,
creation: u32,
flags: u32,
) -> Result<OwnedHandle> {
let handle = unsafe {
CreateFileW(
path.as_ptr(),
access,
FILE_SHARE_ALL,
ptr::null(),
creation,
flags,
ptr::null_mut(),
)
};
if handle as isize == -1 {
return Err(last_error());
}
Ok(unsafe { OwnedHandle::from_raw(handle) })
}
fn attributes_of(path: &[u16]) -> Option<u32> {
let attributes = unsafe { GetFileAttributesW(path.as_ptr()) };
(attributes != INVALID_FILE_ATTRIBUTES).then_some(attributes)
}
fn is_dir(path: &[u16]) -> bool {
attributes_of(path).is_some_and(|attributes| attributes & FILE_ATTRIBUTE_DIRECTORY != 0)
}
fn attribute_tag(handle: BorrowedHandle<'_>) -> Result<FileAttributeTagInfo> {
let mut info = FileAttributeTagInfo::default();
cvt(unsafe {
GetFileInformationByHandleEx(
handle.as_raw(),
FILE_ATTRIBUTE_TAG_INFO,
(&raw mut info).cast(),
size_of::<FileAttributeTagInfo>() as u32,
)
})?;
Ok(info)
}
fn is_link(attributes: u32, reparse_tag: u32) -> bool {
attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 && reparse_tag & REPARSE_TAG_NAME_SURROGATE != 0
}
pub(crate) fn open(path: &[u8], options: &OpenOptions) -> Result<OwnedHandle> {
open_with(path, options, 0)
}
pub(crate) const FILE_FLAG_OVERLAPPED: u32 = 0x4000_0000;
pub(crate) const FILE_FLAG_NO_BUFFERING: u32 = 0x2000_0000;
const FILE_EXECUTE: u32 = 0x20;
pub(crate) fn open_with(path: &[u8], options: &OpenOptions, extra: u32) -> Result<OwnedHandle> {
let mut access = 0;
if options.read {
access |= GENERIC_READ;
}
if options.append {
access |= FILE_GENERIC_WRITE & !FILE_WRITE_DATA;
} else if options.write {
access |= GENERIC_WRITE;
}
if options.execute {
access |= FILE_EXECUTE;
}
let truncate_existing = options.create && options.truncate && !options.create_new;
let creation = if options.create_new {
CREATE_NEW
} else {
match (options.create, options.truncate) {
(false, false) => OPEN_EXISTING,
(false, true) => TRUNCATE_EXISTING,
(true, _) => OPEN_ALWAYS,
}
};
let mut flags = extra;
if options.directory {
flags |= FILE_FLAG_BACKUP_SEMANTICS;
}
if options.no_follow || options.create_new {
flags |= FILE_FLAG_OPEN_REPARSE_POINT;
}
with_path(path, |path| {
let handle = match create_file(path, access, creation, flags) {
Ok(handle) => handle,
Err(error) => {
if error.raw_os_error() == ERROR_ACCESS_DENIED && !options.directory && is_dir(path)
{
return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
}
return Err(error);
}
};
if truncate_existing && last_error().raw_os_error() == ERROR_ALREADY_EXISTS {
set_len(handle.as_handle(), 0)?;
}
if options.no_follow || options.directory {
let info = attribute_tag(handle.as_handle())?;
if options.no_follow && is_link(info.attributes, info.reparse_tag) {
return Err(Error::from_raw_os_error(ERROR_CANT_RESOLVE_FILENAME));
}
if options.directory && info.attributes & FILE_ATTRIBUTE_DIRECTORY == 0 {
return Err(Error::from_raw_os_error(ERROR_DIRECTORY));
}
}
Ok(handle)
})
}
fn timestamp(time: FileTime) -> Timestamp {
let intervals = (time.high as u64) << 32 | time.low as u64;
Timestamp {
secs: (intervals / INTERVALS_PER_SEC) as i64 - EPOCH_DIFFERENCE,
nanos: (intervals % INTERVALS_PER_SEC) as u32 * 100,
}
}
fn file_time(time: Timestamp) -> Result<FileTime> {
time.secs
.checked_add(EPOCH_DIFFERENCE)
.and_then(|secs| u64::try_from(secs).ok())
.and_then(|secs| secs.checked_mul(INTERVALS_PER_SEC))
.and_then(|intervals| intervals.checked_add(time.nanos as u64 / 100))
.filter(|&intervals| intervals != 0 && intervals <= i64::MAX as u64)
.map(|intervals| FileTime {
low: intervals as u32,
high: (intervals >> 32) as u32,
})
.ok_or(ErrorKind::InvalidInput.into())
}
fn mode(attributes: u32) -> u32 {
let mut mode = if attributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
0o777
} else {
0o666
};
if attributes & FILE_ATTRIBUTE_READONLY != 0 {
mode &= !0o222;
}
mode
}
pub(crate) fn handle_metadata(handle: BorrowedHandle<'_>) -> Result<Metadata> {
let kind = unsafe {
SetLastError(0);
GetFileType(handle.as_raw())
};
let file_type = match kind {
FILE_TYPE_DISK => None,
FILE_TYPE_CHAR => Some(FileType::CharDevice),
FILE_TYPE_PIPE => Some(FileType::Fifo),
_ => {
let error = last_error();
if error.raw_os_error() != 0 {
return Err(error);
}
Some(FileType::Unknown)
}
};
if let Some(file_type) = file_type {
return Ok(Metadata {
file_type,
len: 0,
mode: 0o666,
modified: Timestamp::default(),
accessed: Timestamp::default(),
created: None,
links: 1,
device: 0,
inode: 0,
raw: 0,
unix: UnixMetadata::default(),
});
}
let mut info = ByHandleFileInformation::default();
cvt(unsafe { GetFileInformationByHandle(handle.as_raw(), &raw mut info) })?;
let mut file_type = if info.attributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
FileType::Directory
} else {
FileType::File
};
if info.attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
let tag = attribute_tag(handle)?;
if is_link(tag.attributes, tag.reparse_tag) {
file_type = FileType::Symlink;
}
}
Ok(Metadata {
file_type,
len: (info.file_size_high as u64) << 32 | info.file_size_low as u64,
mode: mode(info.attributes),
modified: timestamp(info.last_write_time),
accessed: timestamp(info.last_access_time),
created: Some(timestamp(info.creation_time)),
links: info.number_of_links as u64,
device: info.volume_serial_number as u64,
inode: (info.file_index_high as u64) << 32 | info.file_index_low as u64,
raw: info.attributes,
unix: UnixMetadata::default(),
})
}
fn open_for(path: &[u8], access: u32, follow: bool) -> Result<OwnedHandle> {
let mut flags = FILE_FLAG_BACKUP_SEMANTICS;
if !follow {
flags |= FILE_FLAG_OPEN_REPARSE_POINT;
}
with_path(path, |path| create_file(path, access, OPEN_EXISTING, flags))
}
pub(crate) fn metadata(path: &[u8], follow: bool) -> Result<Metadata> {
let handle = open_for(path, 0, follow)?;
handle_metadata(handle.as_handle())
}
pub(crate) fn set_len(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
let end = len as i64;
cvt(unsafe {
SetFileInformationByHandle(
handle.as_raw(),
FILE_END_OF_FILE_INFO,
(&raw const end).cast(),
size_of::<i64>() as u32,
)
})
}
pub(crate) fn allocate(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
let mut info = FileStandardInfo::default();
cvt(unsafe {
GetFileInformationByHandleEx(
handle.as_raw(),
FILE_STANDARD_INFO,
(&raw mut info).cast(),
size_of::<FileStandardInfo>() as u32,
)
})?;
let len = len as i64;
if len > info.allocation_size {
cvt(unsafe {
SetFileInformationByHandle(
handle.as_raw(),
FILE_ALLOCATION_INFO,
(&raw const len).cast(),
size_of::<i64>() as u32,
)
})?;
}
if len > info.end_of_file {
set_len(handle, len as u64)?;
}
Ok(())
}
pub(crate) fn sector_size(handle: BorrowedHandle<'_>) -> Result<u32> {
let mut info = FileFsFullSizeInformation::default();
let mut status_block = IoStatusBlock {
status: 0,
information: 0,
};
let status = unsafe {
NtQueryVolumeInformationFile(
handle.as_raw(),
&raw mut status_block,
(&raw mut info).cast(),
size_of::<FileFsFullSizeInformation>() as u32,
FILE_FS_FULL_SIZE_INFORMATION,
)
};
if status < 0 {
return Err(nt_error(status));
}
Ok(info.bytes_per_sector)
}
pub(crate) fn handle_space(handle: BorrowedHandle<'_>) -> Result<Space> {
let mut info = FileFsFullSizeInformation::default();
let mut status_block = IoStatusBlock {
status: 0,
information: 0,
};
let status = unsafe {
NtQueryVolumeInformationFile(
handle.as_raw(),
&raw mut status_block,
(&raw mut info).cast(),
size_of::<FileFsFullSizeInformation>() as u32,
FILE_FS_FULL_SIZE_INFORMATION,
)
};
if status < 0 {
return Err(nt_error(status));
}
let unit = (info.sectors_per_unit as u64).saturating_mul(info.bytes_per_sector as u64);
let bytes = |units: i64| (units.max(0) as u64).saturating_mul(unit);
Ok(Space {
total: bytes(info.total_units),
free: bytes(info.actual_available_units),
available: bytes(info.caller_available_units),
})
}
pub(crate) fn space(path: &[u8]) -> Result<Space> {
let handle = open_for(path, 0, true)?;
handle_space(handle.as_handle())
}
unsafe extern "system" fn copy_progress(
_total_size: i64,
_total_transferred: i64,
_stream_size: i64,
stream_transferred: i64,
stream: u32,
_reason: u32,
_source: *mut c_void,
_destination: *mut c_void,
data: *const c_void,
) -> u32 {
if stream == 1 {
unsafe { data.cast_mut().cast::<i64>().write(stream_transferred) };
}
0
}
pub(crate) fn copy(from: &[u8], to: &[u8]) -> Result<u64> {
let mut copied = 0i64;
let result = with_path(from, |from| {
with_path(to, |to| {
cvt(unsafe {
CopyFileExW(
from.as_ptr(),
to.as_ptr(),
Some(copy_progress),
(&raw mut copied).cast_const().cast(),
ptr::null_mut(),
0,
)
})
.map_err(|error| match error.raw_os_error() {
ERROR_ACCESS_DENIED if is_dir(from) => {
Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED)
}
error => Error::from_raw_os_error(error),
})
})
});
match result {
Ok(()) => Ok(copied.max(0) as u64),
Err(error) if error.raw_os_error() == ERROR_SHARING_VIOLATION && same_file(from, to) => {
Err(ErrorKind::InvalidInput.into())
}
Err(error) => Err(error),
}
}
fn same_file(a: &[u8], b: &[u8]) -> bool {
let id = |path: &[u8]| {
let meta = metadata(path, true).ok()?;
Some((meta.device, meta.inode))
};
id(a).is_some_and(|a| Some(a) == id(b))
}
pub(crate) fn sync(handle: BorrowedHandle<'_>, _data_only: bool) -> Result<()> {
cvt(unsafe { FlushFileBuffers(handle.as_raw()) })
}
pub(crate) fn set_handle_permissions(handle: BorrowedHandle<'_>, mode: u32) -> Result<()> {
let mut info = FileBasicInfo::default();
let size = size_of::<FileBasicInfo>() as u32;
cvt(unsafe {
GetFileInformationByHandleEx(
handle.as_raw(),
FILE_BASIC_INFO,
(&raw mut info).cast(),
size,
)
})?;
let mut attributes = info.attributes;
if mode & 0o222 == 0 {
attributes |= FILE_ATTRIBUTE_READONLY;
} else {
attributes &= !FILE_ATTRIBUTE_READONLY;
}
if attributes == 0 {
attributes = FILE_ATTRIBUTE_NORMAL;
}
let info = FileBasicInfo {
attributes,
..FileBasicInfo::default()
};
cvt(unsafe {
SetFileInformationByHandle(
handle.as_raw(),
FILE_BASIC_INFO,
(&raw const info).cast(),
size,
)
})
}
pub(crate) fn set_permissions(path: &[u8], mode: u32) -> Result<()> {
let handle = open_for(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, true)?;
set_handle_permissions(handle.as_handle(), mode)
}
pub(crate) fn set_handle_times(handle: BorrowedHandle<'_>, times: &FileTimes) -> Result<()> {
let accessed = times.accessed.map(file_time).transpose()?;
let modified = times.modified.map(file_time).transpose()?;
let pointer = |time: &Option<FileTime>| time.as_ref().map_or(ptr::null(), ptr::from_ref);
cvt(unsafe {
SetFileTime(
handle.as_raw(),
ptr::null(),
pointer(&accessed),
pointer(&modified),
)
})
}
pub(crate) fn set_times(path: &[u8], times: &FileTimes) -> Result<()> {
let handle = open_for(path, FILE_WRITE_ATTRIBUTES, true)?;
set_handle_times(handle.as_handle(), times)
}
pub(crate) fn lock(handle: BorrowedHandle<'_>, kind: LockKind, wait: bool) -> Result<bool> {
let mut flags = match kind {
LockKind::Shared => 0,
LockKind::Exclusive => LOCKFILE_EXCLUSIVE_LOCK,
};
if !wait {
flags |= LOCKFILE_FAIL_IMMEDIATELY;
}
let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) };
if event.is_null() {
return Err(last_error());
}
let event = unsafe { OwnedHandle::from_raw(event) };
let mut overlapped = Overlapped::at(0);
overlapped.internal = STATUS_PENDING as usize;
overlapped.event = event.as_raw().map_addr(|addr| addr | 1);
let locked = unsafe {
LockFileEx(
handle.as_raw(),
flags,
0,
u32::MAX,
u32::MAX,
&raw mut overlapped,
)
};
let result = if locked != 0 {
Ok(())
} else {
let error = last_error();
if error.raw_os_error() == ERROR_IO_PENDING {
let status =
unsafe { wait_completion(event.as_raw(), true, &raw const overlapped.internal) };
if status >= 0 {
Ok(())
} else {
Err(nt_error(status))
}
} else {
Err(error)
}
};
match result {
Ok(()) => Ok(true),
Err(error) if !wait && error.raw_os_error() == ERROR_LOCK_VIOLATION => Ok(false),
Err(error) => Err(error),
}
}
pub(crate) fn unlock(handle: BorrowedHandle<'_>) -> Result<()> {
for _ in 0..2 {
match cvt(unsafe { UnlockFile(handle.as_raw(), 0, 0, u32::MAX, u32::MAX) }) {
Ok(()) => {}
Err(error) if error.raw_os_error() == ERROR_NOT_LOCKED => break,
Err(error) => return Err(error),
}
}
Ok(())
}
pub(crate) fn create_dir(path: &[u8], _mode: u32) -> Result<()> {
with_path(path, |path| {
cvt(unsafe { CreateDirectoryW(path.as_ptr(), ptr::null()) })
})
}
pub(crate) fn remove_dir(path: &[u8]) -> Result<()> {
with_path(path, |path| {
cvt(unsafe { RemoveDirectoryW(path.as_ptr()) })
})
}
pub(crate) fn remove_file(path: &[u8]) -> Result<()> {
with_path(path, |path| {
let Err(error) = cvt(unsafe { DeleteFileW(path.as_ptr()) }) else {
return Ok(());
};
if error.raw_os_error() == ERROR_ACCESS_DENIED && is_dir(path) {
return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
}
Err(error)
})
}
pub(crate) fn rename(from: &[u8], to: &[u8]) -> Result<()> {
with_path(from, |from| {
with_path(to, |to| {
cvt(unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), MOVEFILE_REPLACE_EXISTING) })
})
})
}
pub(crate) fn hard_link(original: &[u8], link: &[u8]) -> Result<()> {
with_path(original, |original| {
with_path(link, |link| {
cvt(unsafe { CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null()) })
})
})
}
pub(crate) fn is_separator(c: u8) -> bool {
c == b'\\' || c == b'/'
}
fn target_is_dir(target: &[u8], link: &[u8]) -> bool {
let query = |path: &[u8]| with_path(path, |path| Ok(is_dir(path))).unwrap_or(false);
let absolute = target.first().is_some_and(|&c| is_separator(c)) || target.get(1) == Some(&b':');
if absolute {
return query(target);
}
let parent = match link.iter().rposition(|&c| is_separator(c)) {
Some(at) => &link[..=at],
None if link.get(1) == Some(&b':') => &link[..2],
None => &[],
};
let len = parent.len() + target.len();
let mut stack = [0u8; 1024];
if let Some(joined) = stack.get_mut(..len) {
joined[..parent.len()].copy_from_slice(parent);
joined[parent.len()..].copy_from_slice(target);
return query(joined);
}
#[cfg(feature = "alloc")]
{
let mut joined = alloc::vec::Vec::new();
if joined.try_reserve_exact(len).is_ok() {
joined.extend_from_slice(parent);
joined.extend_from_slice(target);
return query(&joined);
}
}
false
}
pub(crate) fn symlink(target: &[u8], link: &[u8]) -> Result<()> {
let mut flags = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
if target_is_dir(target, link) {
flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
}
with_wide(target, |target| {
with_path(link, |link| {
let create =
|flags| unsafe { CreateSymbolicLinkW(link.as_ptr(), target.as_ptr(), flags) };
if create(flags) != 0 {
return Ok(());
}
let error = last_error();
if error.raw_os_error() == ERROR_INVALID_PARAMETER
&& create(flags & !SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) != 0
{
return Ok(());
}
Err(error)
})
})
}
fn to_wtf8(wide: &[u16], buf: &mut [u8]) -> Result<usize> {
wide_to_wtf8(wide, buf).ok_or(ErrorKind::BufferTooSmall.into())
}
pub(crate) fn read_link(path: &[u8], buf: &mut [u8]) -> Result<usize> {
let handle = open_for(path, 0, false)?;
read_link_of(handle.as_handle(), buf)
}
fn read_link_of(handle: BorrowedHandle<'_>, buf: &mut [u8]) -> Result<usize> {
let mut data = [0u16; MAXIMUM_REPARSE_DATA_BUFFER_SIZE / 2];
let mut returned = 0;
let result = cvt(unsafe {
DeviceIoControl(
handle.as_raw(),
FSCTL_GET_REPARSE_POINT,
ptr::null(),
0,
data.as_mut_ptr().cast(),
MAXIMUM_REPARSE_DATA_BUFFER_SIZE as u32,
&raw mut returned,
ptr::null_mut(),
)
});
let not_a_link = || Error::from(ErrorKind::InvalidInput);
match result {
Ok(()) => {}
Err(error) if error.raw_os_error() == ERROR_NOT_A_REPARSE_POINT => {
return Err(not_a_link());
}
Err(error) => return Err(error),
}
let tag = data[0] as u32 | (data[1] as u32) << 16;
let (names, relative) = match tag {
IO_REPARSE_TAG_SYMLINK => {
let flags = data[8] as u32 | (data[9] as u32) << 16;
(10, flags & SYMLINK_FLAG_RELATIVE != 0)
}
IO_REPARSE_TAG_MOUNT_POINT => (8, false),
_ => return Err(not_a_link()),
};
let start = names + data[4] as usize / 2;
let end = start + data[5] as usize / 2;
let mut target = data.get(start..end).ok_or(Error::from(ErrorKind::Other))?;
const NT_PREFIX: [u16; 4] = [b'\\' as u16, b'?' as u16, b'?' as u16, b'\\' as u16];
if !relative && let Some(rest) = target.strip_prefix(&NT_PREFIX) {
target = rest;
}
to_wtf8(target, buf)
}
fn wide_path(buf: &mut [u8], mut call: impl FnMut(*mut u16, u32) -> u32) -> Result<usize> {
let mut stack = [0u16; 1024];
let len = call(stack.as_mut_ptr(), stack.len() as u32) as usize;
if len == 0 {
return Err(last_error());
}
if len < stack.len() {
return to_wtf8(&stack[..len], buf);
}
#[cfg(feature = "alloc")]
{
let mut needed = len;
for _ in 0..4 {
let mut heap = alloc::vec::Vec::new();
heap.try_reserve_exact(needed)
.map_err(|_| ErrorKind::OutOfMemory)?;
heap.resize(needed, 0u16);
let len = call(heap.as_mut_ptr(), heap.len().min(u32::MAX as usize) as u32) as usize;
if len == 0 {
return Err(last_error());
}
if len < heap.len() {
return to_wtf8(&heap[..len], buf);
}
needed = len + 1;
}
}
Err(ErrorKind::InvalidFilename.into())
}
pub(crate) fn canonicalize(path: &[u8], buf: &mut [u8]) -> Result<usize> {
let handle = open_for(path, 0, true)?;
wide_path(buf, |path, len| unsafe {
GetFinalPathNameByHandleW(handle.as_raw(), path, len, 0)
})
}
pub(crate) fn current_dir(buf: &mut [u8]) -> Result<usize> {
wide_path(buf, |path, len| unsafe { GetCurrentDirectoryW(len, path) })
}
pub(crate) fn set_current_dir(path: &[u8]) -> Result<()> {
with_wide(path, |path| {
cvt(unsafe { SetCurrentDirectoryW(path.as_ptr()) })
})
}
const DIR_BUF: usize = 4096;
const NAME_MAX: usize = 255;
const DIR_INFO_NAME: usize = 104;
#[repr(C, align(8))]
struct DirBuf([u8; DIR_BUF]);
pub(crate) struct Dir {
handle: OwnedHandle,
buf: DirBuf,
pos: Option<usize>,
name: [u8; NAME_MAX * 3],
}
impl Dir {
pub(crate) fn new(handle: OwnedHandle) -> Self {
Self {
handle,
buf: DirBuf([0; DIR_BUF]),
pos: None,
name: [0; NAME_MAX * 3],
}
}
pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
self.handle.as_handle()
}
pub(crate) fn name(&self, entry: &RawDirEntry) -> &[u8] {
&self.name[entry.name.0..entry.name.1]
}
pub(crate) fn next(&mut self) -> Result<Option<RawDirEntry>> {
let pos = match self.pos {
Some(pos) => pos,
None => {
let mut block = IoStatusBlock::PENDING;
let (status, _) = unsafe {
let status = NtQueryDirectoryFile(
self.handle.as_raw(),
ptr::null_mut(),
ptr::null(),
ptr::null(),
&raw mut block,
self.buf.0.as_mut_ptr().cast(),
DIR_BUF as u32,
FILE_ID_BOTH_DIRECTORY_INFORMATION,
0,
ptr::null(),
0,
);
completed(self.handle.as_handle(), status, &raw const block)
};
if status < 0 {
let error = nt_error(status);
if error.raw_os_error() == ERROR_NO_MORE_FILES {
return Ok(None);
}
return Err(error);
}
0
}
};
let malformed = || Error::from(ErrorKind::Other);
self.pos = None;
let entry = self.buf.0.get(pos..).ok_or_else(malformed)?;
let u32_at = |at: usize| {
entry
.get(at..at + 4)
.and_then(|bytes| bytes.try_into().ok())
.map(u32::from_le_bytes)
.ok_or_else(malformed)
};
let next = u32_at(0)? as usize;
let attributes = u32_at(56)?;
let name_len = u32_at(60)? as usize;
let reparse_tag = u32_at(64)?;
let inode = u32_at(96)? as u64 | (u32_at(100)? as u64) << 32;
let name = entry
.get(DIR_INFO_NAME..DIR_INFO_NAME + name_len)
.ok_or_else(malformed)?;
if next != 0 {
self.pos = Some(pos + next);
}
let mut wide = [0u16; NAME_MAX];
let units = name_len / 2;
let wide = wide.get_mut(..units).ok_or(ErrorKind::InvalidFilename)?;
for (unit, bytes) in wide.iter_mut().zip(name.as_chunks::<2>().0) {
*unit = u16::from_le_bytes(*bytes);
}
let len = wide_to_wtf8(wide, &mut self.name).ok_or(ErrorKind::InvalidFilename)?;
Ok(Some(RawDirEntry {
name: (0, len),
file_type: Some(if is_link(attributes, reparse_tag) {
FileType::Symlink
} else if attributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
FileType::Directory
} else {
FileType::File
}),
inode,
}))
}
}
fn nt_error(status: i32) -> Error {
if status == STATUS_FILE_IS_A_DIRECTORY {
return Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED);
}
crate::sys::nt_error(status)
}
fn with_nt_name<R>(
path: &[u8],
or_self: bool,
f: impl FnOnce(&[u16], bool) -> Result<R>,
) -> Result<R> {
const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
const MAX: usize = 0x7fff;
if path.get(1) == Some(&b':') {
return Err(ErrorKind::InvalidInput.into());
}
with_wide(path, |wide| {
let wide = &wide[..wide.len() - 1];
let mut stack = [0u16; 512];
#[cfg(feature = "alloc")]
let mut heap = alloc::vec::Vec::new();
let name = match stack.get_mut(..wide.len()) {
Some(name) => name,
#[cfg(feature = "alloc")]
None => {
heap.try_reserve_exact(wide.len())
.map_err(|_| ErrorKind::OutOfMemory)?;
heap.resize(wide.len(), 0u16);
&mut heap[..]
}
#[cfg(not(feature = "alloc"))]
None => return Err(ErrorKind::InvalidFilename.into()),
};
let mut len = 0;
let mut directory = false;
for component in wide.split(|c| SEPARATORS.contains(c)) {
directory = matches!(component, [] | [0x2e]);
if directory {
continue;
}
if len > 0 {
name[len] = SEPARATORS[0];
len += 1;
}
name[len..len + component.len()].copy_from_slice(component);
len += component.len();
}
if len == 0 && !or_self {
return Err(ErrorKind::InvalidInput.into());
}
if len > MAX {
return Err(ErrorKind::InvalidFilename.into());
}
f(&name[..len], directory)
})
}
fn nt_create(
root: BorrowedHandle<'_>,
name: &[u16],
access: u32,
disposition: u32,
options: u32,
) -> Result<(OwnedHandle, usize)> {
let name = UnicodeString {
len: (name.len() * 2) as u16,
capacity: (name.len() * 2) as u16,
buf: name.as_ptr(),
};
let attributes = ObjectAttributes {
len: size_of::<ObjectAttributes>() as u32,
root: root.as_raw(),
name: &raw const name,
attributes: OBJ_CASE_INSENSITIVE,
security_descriptor: ptr::null(),
security_qos: ptr::null(),
};
let mut handle = ptr::null_mut();
let mut status_block = IoStatusBlock {
status: 0,
information: 0,
};
let status = unsafe {
NtCreateFile(
&raw mut handle,
access,
&raw const attributes,
&raw mut status_block,
ptr::null(),
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_ALL,
disposition,
options | FILE_SYNCHRONOUS_IO_NONALERT,
ptr::null(),
0,
)
};
if status < 0 {
return Err(nt_error(status));
}
Ok((
unsafe { OwnedHandle::from_raw(handle) },
status_block.information,
))
}
#[derive(Clone, Copy, PartialEq)]
enum Want {
Anything,
NotADirectory,
Directory,
}
fn open_in(
dir: BorrowedHandle<'_>,
path: &[u8],
or_self: bool,
access: u32,
follow: bool,
want: Want,
) -> Result<OwnedHandle> {
with_nt_name(path, or_self, |name, directory| {
let mut options = FILE_OPEN_FOR_BACKUP_INTENT;
if !follow {
options |= FILE_OPEN_REPARSE_POINT;
}
match (want, directory) {
(Want::Directory, _) | (Want::Anything, true) => options |= FILE_DIRECTORY_FILE,
(Want::Anything, false) => {}
(Want::NotADirectory, false) => options |= FILE_NON_DIRECTORY_FILE,
(Want::NotADirectory, true) => {
let access = FILE_READ_ATTRIBUTES | SYNCHRONIZE;
nt_create(dir, name, access, FILE_OPEN, options | FILE_DIRECTORY_FILE)?;
return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
}
}
let (handle, _) = nt_create(dir, name, access | SYNCHRONIZE, FILE_OPEN, options)?;
Ok(handle)
})
}
pub(crate) fn open_at(
dir: BorrowedHandle<'_>,
path: &[u8],
options: &OpenOptions,
) -> Result<OwnedHandle> {
let mut access = SYNCHRONIZE | FILE_READ_ATTRIBUTES;
if options.read {
access |= GENERIC_READ;
}
if options.append {
access |= FILE_GENERIC_WRITE & !FILE_WRITE_DATA;
} else if options.write {
access |= GENERIC_WRITE;
}
if options.execute {
access |= FILE_EXECUTE;
}
let creates = options.create || options.create_new;
let truncate_existing = options.create && options.truncate && !options.create_new;
let disposition = if options.create_new {
FILE_CREATE
} else {
match (options.create, options.truncate) {
(false, false) => FILE_OPEN,
(false, true) => FILE_OVERWRITE,
(true, _) => FILE_OPEN_IF,
}
};
let mut flags = if options.directory {
FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT
} else {
FILE_NON_DIRECTORY_FILE
};
if options.no_follow || options.create_new {
flags |= FILE_OPEN_REPARSE_POINT;
}
with_nt_name(path, true, |name, directory| {
if directory && !options.directory {
if !creates {
let access = FILE_READ_ATTRIBUTES | SYNCHRONIZE;
let flags = FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT;
nt_create(dir, name, access, FILE_OPEN, flags)?;
}
return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
}
let (handle, done) = nt_create(dir, name, access, disposition, flags)?;
if truncate_existing && done == FILE_OPENED {
set_len(handle.as_handle(), 0)?;
}
if options.no_follow {
let info = attribute_tag(handle.as_handle())?;
if is_link(info.attributes, info.reparse_tag) {
return Err(Error::from_raw_os_error(ERROR_CANT_RESOLVE_FILENAME));
}
}
Ok(handle)
})
}
pub(crate) fn metadata_at(dir: BorrowedHandle<'_>, path: &[u8], follow: bool) -> Result<Metadata> {
let handle = open_in(
dir,
path,
true,
FILE_READ_ATTRIBUTES,
follow,
Want::Anything,
)?;
handle_metadata(handle.as_handle())
}
pub(crate) fn set_permissions_at(dir: BorrowedHandle<'_>, path: &[u8], mode: u32) -> Result<()> {
let access = FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES;
let handle = open_in(dir, path, true, access, true, Want::Anything)?;
set_handle_permissions(handle.as_handle(), mode)
}
pub(crate) fn set_times_at(dir: BorrowedHandle<'_>, path: &[u8], times: &FileTimes) -> Result<()> {
let handle = open_in(dir, path, true, FILE_WRITE_ATTRIBUTES, true, Want::Anything)?;
set_handle_times(handle.as_handle(), times)
}
pub(crate) fn create_dir_at(dir: BorrowedHandle<'_>, path: &[u8], _mode: u32) -> Result<()> {
with_nt_name(path, false, |name, _| {
let options = FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_OPEN_REPARSE_POINT;
let access = FILE_LIST_DIRECTORY | SYNCHRONIZE;
nt_create(dir, name, access, FILE_CREATE, options)?;
Ok(())
})
}
fn delete(handle: BorrowedHandle<'_>) -> Result<()> {
let flags = FILE_DISPOSITION_DELETE | FILE_DISPOSITION_POSIX_SEMANTICS;
let result = cvt(unsafe {
SetFileInformationByHandle(
handle.as_raw(),
FILE_DISPOSITION_INFO_EX,
(&raw const flags).cast(),
size_of::<u32>() as u32,
)
});
match result {
Err(error)
if matches!(
error.raw_os_error(),
ERROR_INVALID_PARAMETER | ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED
) => {}
result => return result,
}
let delete = 1u8;
cvt(unsafe {
SetFileInformationByHandle(
handle.as_raw(),
FILE_DISPOSITION_INFO,
(&raw const delete).cast(),
size_of::<u8>() as u32,
)
})
}
pub(crate) fn remove_dir_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
let handle = open_in(dir, path, false, DELETE, false, Want::Directory)?;
delete(handle.as_handle())
}
pub(crate) fn remove_file_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
let handle = open_in(dir, path, false, DELETE, false, Want::NotADirectory)?;
delete(handle.as_handle())
}
fn set_name(
handle: BorrowedHandle<'_>,
class: i32,
replace: bool,
root: BorrowedHandle<'_>,
name: &[u16],
) -> Result<()> {
const STACK: usize = 512;
#[repr(C)]
struct Info {
replace: u32,
root: *mut c_void,
len: u32,
name: [u16; STACK],
}
const HEADER: usize = core::mem::offset_of!(Info, name);
let call = |info: *const c_void, size: usize| {
let mut status_block = IoStatusBlock {
status: 0,
information: 0,
};
let status = unsafe {
NtSetInformationFile(
handle.as_raw(),
&raw mut status_block,
info,
size as u32,
class,
)
};
if status < 0 {
return Err(nt_error(status));
}
Ok(())
};
if name.len() <= STACK {
let mut info = Info {
replace: replace as u32,
root: root.as_raw(),
len: (name.len() * 2) as u32,
name: [0; STACK],
};
info.name[..name.len()].copy_from_slice(name);
let size = (HEADER + name.len() * 2).max(HEADER + 4);
return call((&raw const info).cast(), size);
}
#[cfg(feature = "alloc")]
{
let size = HEADER + name.len() * 2;
let mut buf = alloc::vec::Vec::<u64>::new();
buf.try_reserve_exact(size.div_ceil(8))
.map_err(|_| ErrorKind::OutOfMemory)?;
buf.resize(size.div_ceil(8), 0);
let info = buf.as_mut_ptr().cast::<Info>();
unsafe {
(&raw mut (*info).replace).write(replace as u32);
(&raw mut (*info).root).write(root.as_raw());
(&raw mut (*info).len).write((name.len() * 2) as u32);
(&raw mut (*info).name)
.cast::<u16>()
.copy_from_nonoverlapping(name.as_ptr(), name.len());
}
call(info.cast_const().cast(), size)
}
#[cfg(not(feature = "alloc"))]
Err(ErrorKind::InvalidFilename.into())
}
pub(crate) fn rename_at(
from_dir: BorrowedHandle<'_>,
from: &[u8],
to_dir: BorrowedHandle<'_>,
to: &[u8],
) -> Result<()> {
let handle = open_in(from_dir, from, false, DELETE, false, Want::Anything)?;
with_nt_name(to, false, |to, _| {
set_name(
handle.as_handle(),
FILE_RENAME_INFORMATION,
true,
to_dir,
to,
)
})
}
pub(crate) fn hard_link_at(
original_dir: BorrowedHandle<'_>,
original: &[u8],
link_dir: BorrowedHandle<'_>,
link: &[u8],
) -> Result<()> {
let access = FILE_WRITE_ATTRIBUTES;
let handle = open_in(original_dir, original, false, access, false, Want::Anything)?;
with_nt_name(link, false, |link, _| {
set_name(
handle.as_handle(),
FILE_LINK_INFORMATION,
false,
link_dir,
link,
)
})
}
pub(crate) fn read_link_at(dir: BorrowedHandle<'_>, path: &[u8], buf: &mut [u8]) -> Result<usize> {
let handle = open_in(dir, path, true, FILE_READ_ATTRIBUTES, false, Want::Anything)?;
read_link_of(handle.as_handle(), buf)
}
fn join_target(buf: &mut [u16], base: usize, link: &[u16], target: &[u16]) -> Option<usize> {
const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
const DOT: u16 = b'.' as u16;
let parent = match link.iter().rposition(|&c| c == SEPARATORS[0]) {
Some(at) => &link[..at],
None => &[],
};
let mut len = base;
for component in parent
.split(|&c| c == SEPARATORS[0])
.chain(target.split(|c| SEPARATORS.contains(c)))
{
match component {
[] | [DOT] => {}
[DOT, DOT] => {
if len == base && base == 0 {
return None;
}
len = buf[..len].iter().rposition(|&c| c == SEPARATORS[0])?;
}
_ => {
let room = buf.get_mut(len..len + 1 + component.len())?;
room[0] = SEPARATORS[0];
room[1..].copy_from_slice(component);
len += room.len();
}
}
}
Some(len)
}
fn relative_target_is_dir(dir: BorrowedHandle<'_>, link: &[u16], target: &[u16]) -> bool {
let mut joined = [0u16; 1024];
if let Some(len) = join_target(&mut joined, 0, link, target) {
let name = joined[..len].get(1..).unwrap_or(&[]);
let access = FILE_READ_ATTRIBUTES | SYNCHRONIZE;
let options = FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT;
return nt_create(dir, name, access, FILE_OPEN, options).is_ok();
}
let base = unsafe {
GetFinalPathNameByHandleW(dir.as_raw(), joined.as_mut_ptr(), joined.len() as u32, 0)
} as usize;
if base == 0 || base >= joined.len() {
return false;
}
match join_target(&mut joined, base, link, target) {
Some(len) if len < joined.len() => {
joined[len] = 0;
is_dir(&joined[..=len])
}
_ => false,
}
}
pub(crate) fn symlink_at(target: &[u8], dir: BorrowedHandle<'_>, link: &[u8]) -> Result<()> {
const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
const NT_PREFIX: [u16; 4] = [b'\\' as u16, b'?' as u16, b'?' as u16, b'\\' as u16];
const UNC: [u16; 4] = [b'U' as u16, b'N' as u16, b'C' as u16, b'\\' as u16];
const HEADER: usize = 4;
const NAMES: usize = 10;
let mut data = [0u16; MAXIMUM_REPARSE_DATA_BUFFER_SIZE / 2];
let too_long = || Error::from(ErrorKind::InvalidFilename);
with_nt_name(link, false, |link, _| {
let (len, directory) = with_wide(target, |wide| {
let target = &wide[..wide.len() - 1];
let is = |at: usize, c: u8| target.get(at) == Some(&(c as u16));
let separator = |at: usize| target.get(at).is_some_and(|c| SEPARATORS.contains(c));
let relative = !is(1, b':') && !(separator(0) && separator(1));
let names = &mut data[NAMES..];
let (substitute, print, directory);
if relative {
let len = target.len();
let both = names.get_mut(..2 * len).ok_or_else(too_long)?;
both[..len].copy_from_slice(target);
both[len..].copy_from_slice(target);
(substitute, print) = ((0, len), (len, len));
directory = if separator(0) {
is_dir(wide)
} else {
relative_target_is_dir(dir, link, target)
};
} else {
const ROOM: usize = 6;
let room = names.len() / 2;
let full = unsafe {
GetFullPathNameW(
wide.as_ptr(),
(room - ROOM) as u32,
names[ROOM..].as_mut_ptr(),
ptr::null_mut(),
)
} as usize;
if full == 0 {
return Err(last_error());
}
if full >= room - ROOM {
return Err(too_long());
}
let path = ROOM..ROOM + full;
let at = |i: usize, c: u8| names[ROOM + i] == c as u16;
let (skip, middle): (usize, &[u16]) =
if full >= 4 && at(0, b'\\') && at(1, b'\\') && at(3, b'\\') {
if at(2, b'?') || at(2, b'.') {
(4, &[])
} else {
(2, &UNC)
}
} else if full >= 2 && at(0, b'\\') && at(1, b'\\') {
(2, &UNC)
} else {
(0, &[])
};
let rest = full - skip;
let substitute_len = NT_PREFIX.len() + middle.len() + rest;
let start = path.end;
let end = start + substitute_len;
if end > names.len() {
return Err(too_long());
}
names[start..start + 4].copy_from_slice(&NT_PREFIX);
names[start + 4..start + 4 + middle.len()].copy_from_slice(middle);
names.copy_within(path.start + skip..path.end, start + 4 + middle.len());
(substitute, print) = ((start, substitute_len), (path.start, full));
directory = is_dir(wide);
}
let end = substitute.0 + substitute.1;
let end = end.max(print.0 + print.1);
let bytes = |units: usize| (units * 2) as u16;
let flags = if relative { SYMLINK_FLAG_RELATIVE } else { 0 }
| SYMLINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
data[0] = IO_REPARSE_TAG_SYMLINK as u16;
data[1] = (IO_REPARSE_TAG_SYMLINK >> 16) as u16;
data[2] = bytes(NAMES - HEADER + end);
data[3] = 0;
data[4] = bytes(substitute.0);
data[5] = bytes(substitute.1);
data[6] = bytes(print.0);
data[7] = bytes(print.1);
data[8] = flags as u16;
data[9] = (flags >> 16) as u16;
Ok((NAMES + end, directory))
})?;
let options = FILE_OPEN_REPARSE_POINT
| FILE_OPEN_FOR_BACKUP_INTENT
| if directory {
FILE_DIRECTORY_FILE
} else {
FILE_NON_DIRECTORY_FILE
};
let access = FILE_WRITE_ATTRIBUTES | DELETE | SYNCHRONIZE;
let (handle, _) = nt_create(dir, link, access, FILE_CREATE, options)?;
let set = |data: &[u16]| {
let mut returned = 0;
cvt(unsafe {
DeviceIoControl(
handle.as_raw(),
FSCTL_SET_REPARSE_POINT,
data.as_ptr().cast(),
(len * 2) as u32,
ptr::null_mut(),
0,
&raw mut returned,
ptr::null_mut(),
)
})
};
let mut result = set(&data);
if result.is_err_and(|error| error.raw_os_error() == ERROR_INVALID_PARAMETER) {
data[8] &= !(SYMLINK_FLAG_ALLOW_UNPRIVILEGED_CREATE as u16);
if set(&data).is_ok() {
result = Ok(());
}
}
if result.is_err() {
let _ = delete(handle.as_handle());
}
result
})
}