use std::{
ffi::{CString, OsStr, OsString},
fs::{self, File, OpenOptions},
io,
os::unix::{ffi::OsStrExt, fs::OpenOptionsExt},
path::{Path, PathBuf},
};
use rustix::{
fs::{AtFlags, Dir, FileType, Mode, OFlags, openat, statat},
io::Errno,
};
use super::FileKind;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
pub use macos::{case_sensitive, exact_name};
pub fn canonicalize(path: &Path) -> io::Result<PathBuf> {
fs::canonicalize(path)
}
pub fn open_no_follow(options: &mut OpenOptions, path: &Path) -> io::Result<File> {
let (path, directory) = terminal_component(path);
let mut flags = OFlags::NOFOLLOW | OFlags::NONBLOCK;
if directory {
flags |= OFlags::DIRECTORY;
}
options.custom_flags(flags.bits() as i32).open(path)
}
pub(in crate::platform) fn terminal_component(path: &Path) -> (&Path, bool) {
let original = path.as_os_str().as_bytes();
let mut bytes = original;
while bytes.len() > 1 {
if let Some(prefix) = bytes.strip_suffix(b"/") {
bytes = prefix;
} else if let Some(prefix) = bytes.strip_suffix(b"/.") {
bytes = if prefix.is_empty() { b"/" } else { prefix };
} else {
break;
}
}
(
Path::new(OsStr::from_bytes(bytes)),
bytes.len() != original.len(),
)
}
pub fn open_nonblocking(path: &Path) -> io::Result<File> {
OpenOptions::new()
.read(true)
.custom_flags(OFlags::NONBLOCK.bits() as i32)
.open(path)
}
pub fn open_directory(path: &Path) -> io::Result<File> {
OpenOptions::new()
.read(true)
.custom_flags(OFlags::DIRECTORY.bits() as i32)
.open(path)
}
pub struct EntryName(CString);
impl EntryName {
pub fn new(name: &OsStr) -> Option<Self> {
let bytes = name.as_bytes();
(!bytes.is_empty() && !matches!(bytes, b"." | b"..") && !bytes.contains(&b'/'))
.then(|| CString::new(bytes).ok().map(Self))
.flatten()
}
}
pub fn open_entry(directory: &File, name: &EntryName) -> io::Result<File> {
Ok(openat(
directory,
&name.0,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
)?
.into())
}
pub fn is_link_refusal(error: &io::Error) -> bool {
let link = if cfg!(any(target_os = "freebsd", target_os = "dragonfly")) {
Errno::MLINK
} else {
Errno::LOOP
};
error.raw_os_error() == Some(link.raw_os_error())
}
pub fn read_dir(directory: &File) -> io::Result<impl Iterator<Item = io::Result<DirEntry<'_>>>> {
Ok(ReadDir {
stream: open_scan(directory)?,
directory,
state: Scan::Reading,
})
}
fn open_scan(directory: &File) -> io::Result<Dir> {
let fd = openat(
directory,
c".",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?;
Ok(Dir::new(fd)?)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Scan {
Reading,
Done,
}
struct ReadDir<'a> {
stream: Dir,
directory: &'a File,
state: Scan,
}
impl<'a> Iterator for ReadDir<'a> {
type Item = io::Result<DirEntry<'a>>;
fn next(&mut self) -> Option<Self::Item> {
while self.state == Scan::Reading {
let entry = match self.stream.next() {
Some(Ok(entry)) => entry,
Some(Err(error)) => {
self.state = Scan::Done;
return Some(Err(error.into()));
}
None => {
self.state = Scan::Done;
return None;
}
};
let name = entry.file_name().to_bytes();
if name == b"." || name == b".." {
continue;
}
return Some(Ok(DirEntry {
directory: self.directory,
name: OsStr::from_bytes(name).to_owned(),
}));
}
None
}
}
pub struct DirEntry<'a> {
directory: &'a File,
name: OsString,
}
impl DirEntry<'_> {
pub fn file_name(&self) -> OsString {
self.name.clone()
}
pub fn file_type(&self) -> io::Result<FileKind> {
entry_kind(self.directory, &self.name)
}
}
pub fn entry_kind(directory: &File, name: &OsStr) -> io::Result<FileKind> {
let name = EntryName::new(name).ok_or(io::ErrorKind::InvalidInput)?;
let stat = statat(directory, &name.0, AtFlags::SYMLINK_NOFOLLOW)?;
Ok(match FileType::from_raw_mode(stat.st_mode) {
FileType::RegularFile => FileKind::File,
FileType::Directory => FileKind::Directory,
FileType::Symlink => FileKind::Symlink,
_ => FileKind::Other,
})
}
#[cfg(not(target_os = "macos"))]
pub fn exact_name(directory: &File, file: &File, name: &OsStr) -> io::Result<bool> {
let name = EntryName::new(name).ok_or(io::ErrorKind::InvalidInput)?;
let scan = open_scan(directory)?;
for entry in scan {
if entry?.file_name() == name.0.as_c_str() {
let opened = rustix::fs::fstat(file)?;
let listed = statat(directory, &name.0, AtFlags::SYMLINK_NOFOLLOW)?;
return Ok((listed.st_dev, listed.st_ino) == (opened.st_dev, opened.st_ino));
}
}
Ok(false)
}
pub fn verified_path(_file: &File, root: &Path, names: &[&OsStr]) -> io::Result<PathBuf> {
let mut path = root.to_owned();
path.extend(names);
Ok(path)
}
#[cfg(target_os = "linux")]
pub(in crate::platform) fn native_case_sensitive(
directory: &File,
filesystem: rustix::fs::FsWord,
) -> Option<bool> {
match filesystem as u64 {
kind if kind == libc::EXT4_SUPER_MAGIC as u64 || kind == libc::F2FS_SUPER_MAGIC as u64 => {
const CASEFOLD: u32 = 0x4000_0000;
rustix::fs::ioctl_getflags(directory)
.ok()
.map(|flags| flags.bits() & CASEFOLD == 0)
}
kind if kind == libc::TMPFS_MAGIC as u64 || kind == libc::BTRFS_SUPER_MAGIC as u64 => {
Some(true)
}
_ => None,
}
}
#[cfg(target_os = "linux")]
pub fn case_sensitive(directory: &File) -> io::Result<bool> {
let volume = rustix::fs::fstatfs(directory)?;
Ok(native_case_sensitive(directory, volume.f_type).unwrap_or(false))
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub fn case_sensitive(_directory: &File) -> io::Result<bool> {
Ok(false)
}