use std::fs::{self, File};
use std::io;
use std::path::{Component, Path};
const FILE_SHARE_READ: u32 = 0x1;
const FILE_SHARE_DELETE: u32 = 0x4;
const ERROR_SHARING_VIOLATION: i32 = 32;
pub fn open_exclusive(path: &Path) -> io::Result<File> {
use std::os::windows::fs::OpenOptionsExt;
fs::OpenOptions::new()
.read(true)
.write(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_DELETE)
.open(path)
.map_err(|e| match e.raw_os_error() {
Some(ERROR_SHARING_VIOLATION) => io::ErrorKind::WouldBlock.into(),
_ => e,
})
}
pub fn create_new_no_follow(path: &Path) -> io::Result<File> {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
}
pub fn open_existing_no_follow(path: &Path) -> io::Result<File> {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
if !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"it is not a regular file",
));
}
Ok(file)
}
pub fn open_folder_no_follow(path: &Path) -> io::Result<File> {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::{
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES,
FILE_WRITE_ATTRIBUTES,
};
let dir = fs::OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
if !dir.metadata()?.is_dir() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"it is not a folder",
));
}
Ok(dir)
}
pub fn unlock_folder(_path: &Path) -> io::Result<()> {
Ok(())
}
pub fn name_problem(name: &str) -> Option<&'static str> {
const RESERVED: &[&str] = &[
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
"COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];
let stem = name.split('.').next().unwrap_or(name).trim_end();
if RESERVED.iter().any(|r| r.eq_ignore_ascii_case(stem)) {
return Some("it is a reserved device name on Windows");
}
if name.ends_with('.') || name.ends_with(' ') {
return Some("Windows removes a trailing dot or space from names");
}
if name
.chars()
.any(|c| matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*') || (c as u32) < 32)
{
return Some("it contains a character that Windows does not allow in names");
}
if name.encode_utf16().count() > 255 - ".hatchzip-part".len() {
return Some("the name is longer than Windows allows");
}
None
}
pub const MAX_PATH_LEN: usize = 32_000;
pub fn path_len(path: &Path) -> usize {
use std::os::windows::ffi::OsStrExt;
path.as_os_str().encode_wide().count()
}
pub const SYNC_EACH_FILE: bool = true;
pub fn sync_batch(_output: &Path) -> io::Result<()> {
Ok(())
}
pub fn sync_dir(_dir: &Path) -> io::Result<()> {
Ok(())
}
pub fn same_filesystem(a: &Path, b: &Path) -> bool {
let volume = |p: &Path| {
fs::canonicalize(p)
.ok()
.and_then(|p| match p.components().next() {
Some(Component::Prefix(prefix)) => {
Some(prefix.as_os_str().to_string_lossy().to_lowercase())
}
_ => None,
})
};
volume(a).is_some_and(|v| Some(v) == volume(b))
}
pub fn apply_mode(_file: &File, _mode: Option<u32>) -> io::Result<()> {
Ok(())
}
pub fn create_symlink(link: &Path, target: &Path) -> io::Result<()> {
fs::write(link, target.to_string_lossy().as_bytes())
}
const ERROR_INVALID_FUNCTION: i32 = 1;
const ERROR_NOT_SUPPORTED: i32 = 50;
const PUNCH_ALIGN: u64 = 64 << 10;
pub fn punch_hole(file: &File, offset: u64, len: u64) -> io::Result<bool> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::System::IO::DeviceIoControl;
use windows_sys::Win32::System::Ioctl::{
FILE_ZERO_DATA_INFORMATION, FSCTL_SET_SPARSE, FSCTL_SET_ZERO_DATA,
};
let start = offset.next_multiple_of(PUNCH_ALIGN);
let end = (offset + len) / PUNCH_ALIGN * PUNCH_ALIGN;
if start >= end {
return Ok(true);
}
let (Ok(start), Ok(end)) = (i64::try_from(start), i64::try_from(end)) else {
return Err(io::ErrorKind::InvalidInput.into());
};
let handle = file.as_raw_handle();
let mut returned = 0u32;
let failed = |e: io::Error| match e.raw_os_error() {
Some(ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED) => Ok(false),
_ => Err(e),
};
let ok = unsafe {
DeviceIoControl(
handle,
FSCTL_SET_SPARSE,
std::ptr::null(),
0,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
if ok == 0 {
return failed(io::Error::last_os_error());
}
let range = FILE_ZERO_DATA_INFORMATION {
FileOffset: start,
BeyondFinalZero: end,
};
let ok = unsafe {
DeviceIoControl(
handle,
FSCTL_SET_ZERO_DATA,
(&raw const range).cast(),
size_of::<FILE_ZERO_DATA_INFORMATION>() as u32,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
if ok == 0 {
return failed(io::Error::last_os_error());
}
Ok(true)
}
pub fn punch_granule(_dir: &Path) -> u64 {
1 << 20
}
pub fn allocated_bytes(path: &Path) -> io::Result<u64> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::GetCompressedFileSizeW;
const INVALID_FILE_SIZE: u32 = u32::MAX;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
let mut high = 0u32;
let low = unsafe { GetCompressedFileSizeW(wide.as_ptr(), &mut high) };
if low == INVALID_FILE_SIZE {
let e = io::Error::last_os_error();
if e.raw_os_error() != Some(0) {
return Err(e);
}
}
Ok((u64::from(high) << 32) | u64::from(low))
}
pub const NORMALIZES_NAMES: bool = false;
pub fn case_sensitive(_dir: &Path) -> bool {
false
}
pub fn local_time(
year: u16,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> Option<std::time::SystemTime> {
use windows_sys::Win32::Foundation::{FILETIME, SYSTEMTIME};
use windows_sys::Win32::System::Time::{
SystemTimeToFileTime, TzSpecificLocalTimeToSystemTimeEx,
};
let local = SYSTEMTIME {
wYear: year,
wMonth: month.into(),
wDayOfWeek: 0,
wDay: day.into(),
wHour: hour.into(),
wMinute: minute.into(),
wSecond: second.into(),
wMilliseconds: 0,
};
let mut utc = SYSTEMTIME::default();
if unsafe { TzSpecificLocalTimeToSystemTimeEx(std::ptr::null(), &local, &mut utc) } == 0 {
return None;
}
let mut ticks = FILETIME::default();
if unsafe { SystemTimeToFileTime(&utc, &mut ticks) } == 0 {
return None;
}
crate::fsutil::from_filetime(
(u64::from(ticks.dwHighDateTime) << 32) | u64::from(ticks.dwLowDateTime),
)
}
pub fn link_count(path: &Path) -> io::Result<u64> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
};
let file = File::open(path)?;
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(info.nNumberOfLinks.into())
}
#[cfg(feature = "rar")]
pub struct RarName(Vec<unrar_ng_sys::WCHAR>);
#[cfg(feature = "rar")]
impl RarName {
pub fn new(path: &Path) -> io::Result<Self> {
use std::os::windows::ffi::OsStrExt;
let mut wide: Vec<unrar_ng_sys::WCHAR> = path.as_os_str().encode_wide().collect();
if wide.contains(&0) {
return Err(io::ErrorKind::InvalidInput.into());
}
wide.push(0);
Ok(Self(wide))
}
pub fn open_data(&self, mode: std::ffi::c_uint) -> unrar_ng_sys::OpenArchiveDataEx {
unrar_ng_sys::OpenArchiveDataEx::new(self.0.as_ptr(), mode)
}
}
#[cfg(feature = "rar")]
#[link(name = "advapi32")]
unsafe extern "C" {}