use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Found {
File,
Folder,
Link,
Other,
}
#[derive(Debug)]
pub(crate) enum Refused {
Link,
Other,
Io(io::Error),
}
impl From<io::Error> for Refused {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
pub(crate) struct Held {
path: PathBuf,
inner: imp::Inner,
}
impl Held {
pub(crate) fn open(path: &Path) -> io::Result<Arc<Self>> {
Ok(Arc::new(Self {
path: path.to_path_buf(),
inner: imp::Inner::open(path)?,
}))
}
pub(crate) fn create(path: &Path) -> io::Result<Arc<Self>> {
Ok(Arc::new(Self {
path: path.to_path_buf(),
inner: imp::Inner::create(path)?,
}))
}
pub(crate) fn path(&self) -> &Path {
&self.path
}
pub(crate) fn list(&self) -> io::Result<Vec<(OsString, Found)>> {
self.inner.list(&self.path)
}
pub(crate) fn open_folder(self: &Arc<Self>, name: &str) -> Result<Arc<Self>, Refused> {
let path = self.path.join(name);
let inner = imp::Inner::open_folder(self, one_name(name)?, &path)?;
Ok(Arc::new(Self { path, inner }))
}
pub(crate) fn open_file(&self, name: &str) -> Result<File, Refused> {
self.inner.open_file(one_name(name)?, &self.path.join(name))
}
pub(crate) fn create_folder(self: &Arc<Self>, name: &str) -> io::Result<Arc<Self>> {
let path = self.path.join(name);
let inner = imp::Inner::create_folder(self, one_name(name)?, &path)?;
Ok(Arc::new(Self { path, inner }))
}
pub(crate) fn create_file(&self, name: &str) -> io::Result<File> {
self.inner
.create_file(one_name(name)?, &self.path.join(name))
}
}
fn one_name(name: &str) -> io::Result<&OsStr> {
let more_than_a_name = name.is_empty()
|| name == "."
|| name == ".."
|| name.contains(['/', '\0'])
|| (cfg!(windows) && name.contains(['\\', ':']));
if more_than_a_name {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"what is opened or made in a folder is named by one name",
));
}
Ok(OsStr::new(name))
}
#[cfg(not(unix))]
fn list_by_path(path: &Path) -> io::Result<Vec<(OsString, Found)>> {
let mut listed = Vec::new();
for entry in std::fs::read_dir(path)? {
let entry = entry?;
let kind = entry.file_type()?;
let found = if kind.is_symlink() {
Found::Link
} else if kind.is_dir() {
Found::Folder
} else if kind.is_file() {
Found::File
} else {
Found::Other
};
listed.push((entry.file_name(), found));
}
Ok(listed)
}
#[cfg(not(unix))]
fn refused_by_path(path: &Path, error: io::Error, wanted: Found) -> Refused {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_symlink() => Refused::Link,
Ok(metadata) if metadata.is_dir() != (wanted == Found::Folder) => Refused::Other,
_ => Refused::Io(error),
}
}
#[cfg(unix)]
mod imp {
use super::{Found, Held, Refused};
use rustix::fs::{fstat, mkdirat, openat, statat, AtFlags, Dir, FileType, Mode, OFlags, CWD};
use rustix::io::Errno;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io;
use std::os::fd::OwnedFd;
use std::os::unix::ffi::OsStringExt;
use std::path::Path;
use std::sync::Arc;
pub(super) struct Inner {
fd: OwnedFd,
}
fn found(kind: FileType) -> Found {
match kind {
FileType::RegularFile => Found::File,
FileType::Directory => Found::Folder,
FileType::Symlink => Found::Link,
_ => Found::Other,
}
}
fn look(fd: &OwnedFd, name: &OsStr) -> io::Result<Found> {
let stat = statat(fd, name, AtFlags::SYMLINK_NOFOLLOW)?;
Ok(found(FileType::from_raw_mode(stat.st_mode)))
}
fn refused(fd: &OwnedFd, name: &OsStr, error: Errno, wanted: Found) -> Refused {
match look(fd, name) {
Ok(Found::Link) => Refused::Link,
Ok(found) if found != wanted => Refused::Other,
_ => Refused::Io(error.into()),
}
}
fn folder_flags() -> OFlags {
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
}
fn all_may() -> Mode {
Mode::RWXU | Mode::RWXG | Mode::RWXO
}
impl Inner {
pub(super) fn open(path: &Path) -> io::Result<Self> {
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
Ok(Self {
fd: openat(CWD, path, flags, Mode::empty())?,
})
}
pub(super) fn create(path: &Path) -> io::Result<Self> {
mkdirat(CWD, path, all_may())?;
Ok(Self {
fd: openat(CWD, path, folder_flags(), Mode::empty())?,
})
}
pub(super) fn list(&self, _path: &Path) -> io::Result<Vec<(OsString, Found)>> {
let mut listed = Vec::new();
for entry in Dir::read_from(&self.fd)? {
let entry = entry?;
let name = entry.file_name().to_bytes();
if name == b"." || name == b".." {
continue;
}
let name = OsString::from_vec(name.to_vec());
let kind = match entry.file_type() {
FileType::Unknown => look(&self.fd, &name)?,
kind => found(kind),
};
listed.push((name, kind));
}
Ok(listed)
}
pub(super) fn open_folder(
above: &Arc<Held>,
name: &OsStr,
_path: &Path,
) -> Result<Self, Refused> {
let fd = &above.inner.fd;
match openat(fd, name, folder_flags(), Mode::empty()) {
Ok(fd) => Ok(Self { fd }),
Err(error) => Err(refused(fd, name, error, Found::Folder)),
}
}
pub(super) fn open_file(&self, name: &OsStr, _path: &Path) -> Result<File, Refused> {
let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
let fd = match openat(&self.fd, name, flags, Mode::empty()) {
Ok(fd) => fd,
Err(error) => return Err(refused(&self.fd, name, error, Found::File)),
};
let stat = fstat(&fd).map_err(io::Error::from)?;
if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
return Err(Refused::Other);
}
Ok(File::from(fd))
}
pub(super) fn create_folder(
above: &Arc<Held>,
name: &OsStr,
_path: &Path,
) -> io::Result<Self> {
let fd = &above.inner.fd;
mkdirat(fd, name, all_may())?;
Ok(Self {
fd: openat(fd, name, folder_flags(), Mode::empty())?,
})
}
pub(super) fn create_file(&self, name: &OsStr, _path: &Path) -> io::Result<File> {
let flags =
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
let mode = Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH;
Ok(File::from(openat(&self.fd, name, flags, mode)?))
}
}
}
#[cfg(windows)]
mod imp {
use super::{list_by_path, refused_by_path, Found, Held, Refused};
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
use std::path::{Component, Path, PathBuf, Prefix};
use std::sync::Arc;
const FILE_SHARE_READ: u32 = 0x1;
const FILE_SHARE_WRITE: u32 = 0x2;
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
pub(super) struct Inner {
exact: PathBuf,
_pin: File,
_above: Option<Arc<Held>>,
}
fn exact(path: &Path) -> io::Result<PathBuf> {
let whole = std::path::absolute(path)?;
let mut parts = whole.components();
let mut exact = OsString::from(r"\\?\");
match parts.next() {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::Disk(_) => exact.push(prefix.as_os_str()),
Prefix::UNC(server, share) => {
exact.push("UNC\\");
exact.push(server);
exact.push("\\");
exact.push(share);
}
Prefix::DeviceNS(device) => exact.push(device),
Prefix::Verbatim(_) | Prefix::VerbatimUNC(..) | Prefix::VerbatimDisk(_) => {
return Ok(whole);
}
},
_ => return Ok(whole),
}
exact.push(parts.as_path());
Ok(PathBuf::from(exact))
}
fn pin(path: &Path, follow: bool) -> Result<File, Refused> {
let mut flags = FILE_FLAG_BACKUP_SEMANTICS;
if !follow {
flags |= FILE_FLAG_OPEN_REPARSE_POINT;
}
let pin = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(flags)
.open(path)
.map_err(|error| refused_by_path(path, error, Found::Folder))?;
let metadata = pin.metadata()?;
if metadata.file_type().is_symlink() {
return Err(Refused::Link);
}
if !metadata.is_dir() {
return Err(Refused::Other);
}
Ok(pin)
}
fn as_io(refused: Refused) -> io::Error {
match refused {
Refused::Io(error) => error,
Refused::Link => io::Error::new(
io::ErrorKind::InvalidInput,
"a link is there, where a folder has to be",
),
Refused::Other => io::Error::new(
io::ErrorKind::InvalidInput,
"something that is no folder is there, where a folder has to be",
),
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Identity {
volume: u64,
number: [u8; 16],
}
#[allow(unsafe_code)]
pub(super) fn identity(file: &File, long: bool) -> io::Result<Identity> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
FileIdInfo, GetFileInformationByHandle, GetFileInformationByHandleEx,
BY_HANDLE_FILE_INFORMATION, FILE_ID_INFO,
};
let handle = file.as_raw_handle();
if long {
let mut info = FILE_ID_INFO::default();
let done = unsafe {
GetFileInformationByHandleEx(
handle,
FileIdInfo,
(&raw mut info).cast(),
size_of::<FILE_ID_INFO>() as u32,
)
};
if done == 0 {
return Err(io::Error::last_os_error());
}
return Ok(Identity {
volume: info.VolumeSerialNumber,
number: info.FileId.Identifier,
});
}
let mut info = BY_HANDLE_FILE_INFORMATION::default();
let done = unsafe { GetFileInformationByHandle(handle, &mut info) };
if done == 0 {
return Err(io::Error::last_os_error());
}
let mut number = [0; 16];
number[..4].copy_from_slice(&info.nFileIndexLow.to_le_bytes());
number[4..8].copy_from_slice(&info.nFileIndexHigh.to_le_bytes());
Ok(Identity {
volume: u64::from(info.dwVolumeSerialNumber),
number,
})
}
pub(super) fn one_file(left: &File, right: &File) -> io::Result<bool> {
if let (Ok(left), Ok(right)) = (identity(left, true), identity(right, true)) {
return Ok(left == right);
}
Ok(identity(left, false)? == identity(right, false)?)
}
fn open_as_itself(path: &Path, held: bool) -> Result<(File, bool), Refused> {
let mut options = OpenOptions::new();
options
.read(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
if held {
options.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
}
let file = options
.open(path)
.map_err(|error| refused_by_path(path, error, Found::File))?;
let metadata = file.metadata()?;
if metadata.file_type().is_symlink() {
return Err(Refused::Link);
}
if metadata.is_dir() {
return Err(Refused::Other);
}
let plain = metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0;
Ok((file, plain))
}
impl Inner {
fn within(&self, name: &OsStr) -> PathBuf {
let mut path = self.exact.clone().into_os_string();
if !path.as_encoded_bytes().ends_with(b"\\") {
path.push("\\");
}
path.push(name);
PathBuf::from(path)
}
pub(super) fn open(path: &Path) -> io::Result<Self> {
let exact = exact(path)?;
Ok(Self {
_pin: pin(&exact, true).map_err(as_io)?,
exact,
_above: None,
})
}
pub(super) fn create(path: &Path) -> io::Result<Self> {
let exact = exact(path)?;
fs::create_dir(&exact)?;
Ok(Self {
_pin: pin(&exact, false).map_err(as_io)?,
exact,
_above: None,
})
}
pub(super) fn list(&self, _path: &Path) -> io::Result<Vec<(OsString, Found)>> {
list_by_path(&self.exact)
}
pub(super) fn open_folder(
above: &Arc<Held>,
name: &OsStr,
_path: &Path,
) -> Result<Self, Refused> {
let exact = above.inner.within(name);
Ok(Self {
_pin: pin(&exact, false)?,
exact,
_above: Some(Arc::clone(above)),
})
}
pub(super) fn open_file(&self, name: &OsStr, _path: &Path) -> Result<File, Refused> {
let exact = self.within(name);
let (file, plain) = open_as_itself(&exact, false)?;
if plain {
return Ok(file);
}
drop(file);
let (held, _) = open_as_itself(&exact, true)?;
let file = File::open(&exact)?;
if !one_file(&held, &file)? {
return Err(Refused::Link);
}
drop(held);
Ok(file)
}
pub(super) fn create_folder(
above: &Arc<Held>,
name: &OsStr,
_path: &Path,
) -> io::Result<Self> {
let exact = above.inner.within(name);
fs::create_dir(&exact)?;
Ok(Self {
_pin: pin(&exact, false).map_err(as_io)?,
exact,
_above: Some(Arc::clone(above)),
})
}
pub(super) fn create_file(&self, name: &OsStr, _path: &Path) -> io::Result<File> {
OpenOptions::new()
.write(true)
.create_new(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(self.within(name))
}
}
}
#[cfg(not(any(unix, windows)))]
mod imp {
use super::{list_by_path, refused_by_path, Found, Held, Refused};
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::path::Path;
use std::sync::Arc;
pub(super) struct Inner;
fn check(path: &Path, wanted: Found) -> Result<(), Refused> {
let metadata = fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() {
return Err(Refused::Link);
}
let is = if metadata.is_dir() {
Found::Folder
} else if metadata.is_file() {
Found::File
} else {
Found::Other
};
if is == wanted {
Ok(())
} else {
Err(Refused::Other)
}
}
impl Inner {
pub(super) fn open(path: &Path) -> io::Result<Self> {
fs::read_dir(path).map(|_| Self)
}
pub(super) fn create(path: &Path) -> io::Result<Self> {
fs::create_dir(path).map(|()| Self)
}
pub(super) fn list(&self, path: &Path) -> io::Result<Vec<(OsString, Found)>> {
list_by_path(path)
}
pub(super) fn open_folder(
_above: &Arc<Held>,
_name: &OsStr,
path: &Path,
) -> Result<Self, Refused> {
check(path, Found::Folder).map(|()| Self)
}
pub(super) fn open_file(&self, _name: &OsStr, path: &Path) -> Result<File, Refused> {
check(path, Found::File)?;
File::open(path).map_err(|error| refused_by_path(path, error, Found::File))
}
pub(super) fn create_folder(
_above: &Arc<Held>,
_name: &OsStr,
path: &Path,
) -> io::Result<Self> {
fs::create_dir(path).map(|()| Self)
}
pub(super) fn create_file(&self, _name: &OsStr, path: &Path) -> io::Result<File> {
OpenOptions::new().write(true).create_new(true).open(path)
}
}
}
#[cfg(test)]
mod tests;