use std::{fs::File, io};
#[derive(Debug)]
pub enum OpenRegularError {
Io(io::Error),
Symlink,
NotRegularFile,
}
impl std::fmt::Display for OpenRegularError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(error) => write!(f, "input open failed: {error}"),
Self::Symlink => f.write_str("input leaf is a symlink or reparse point"),
Self::NotRegularFile => f.write_str("input handle is not a regular file"),
}
}
}
impl std::error::Error for OpenRegularError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => Some(error),
_ => None,
}
}
}
impl From<io::Error> for OpenRegularError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
#[cfg(unix)]
pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
use std::os::unix::fs::OpenOptionsExt;
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)
.map_err(|error| {
if error.raw_os_error() == Some(libc::ELOOP) {
OpenRegularError::Symlink
} else {
OpenRegularError::Io(error)
}
})?;
if !file.metadata()?.is_file() {
return Err(OpenRegularError::NotRegularFile);
}
Ok(file)
}
#[cfg(unix)]
pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
open_nofollow_all(path, false)
}
pub fn open_directory_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
open_nofollow_all(path, true)
}
#[cfg(unix)]
fn open_nofollow_all(
path: &std::path::Path,
want_directory: bool,
) -> Result<File, OpenRegularError> {
use rustix::fs::{open, openat, statat, AtFlags, FileType, Mode, OFlags};
use std::path::Component;
if !path.is_absolute() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
}
let mut directory = open(
"/",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(io::Error::from)?;
let parts = path
.components()
.filter(|part| !matches!(part, Component::RootDir | Component::CurDir))
.collect::<Vec<_>>();
for (index, part) in parts.iter().enumerate() {
let name = part.as_os_str();
let leaf = index + 1 == parts.len();
let flags = OFlags::RDONLY
| OFlags::CLOEXEC
| OFlags::NOFOLLOW
| OFlags::NONBLOCK
| if leaf && !want_directory {
OFlags::empty()
} else {
OFlags::DIRECTORY
};
directory = openat(&directory, name, flags, Mode::empty()).map_err(|error| {
if error == rustix::io::Errno::LOOP
|| (error == rustix::io::Errno::NOTDIR
&& statat(&directory, name, AtFlags::SYMLINK_NOFOLLOW).is_ok_and(|stat| {
FileType::from_raw_mode(stat.st_mode) == FileType::Symlink
}))
{
OpenRegularError::Symlink
} else if error == rustix::io::Errno::NOTDIR {
OpenRegularError::NotRegularFile
} else {
OpenRegularError::Io(error.into())
}
})?;
}
let file = File::from(directory);
if if want_directory {
!file.metadata()?.is_dir()
} else {
!file.metadata()?.is_file()
} {
return Err(OpenRegularError::NotRegularFile);
}
Ok(file)
}
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
open_nofollow_all(path, false)
}
#[cfg(windows)]
#[allow(unsafe_code)]
fn open_nofollow_all(
path: &std::path::Path,
want_directory: bool,
) -> Result<File, OpenRegularError> {
use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT,
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES,
FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE,
};
if !path.is_absolute() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
}
let mut ancestors = Vec::new();
let prefixes: Vec<_> = path
.ancestors()
.take_while(|prefix| prefix.is_absolute())
.collect();
for prefix in prefixes.into_iter().rev() {
let mut options = std::fs::OpenOptions::new();
if want_directory || prefix != path {
options
.access_mode(FILE_READ_ATTRIBUTES | FILE_TRAVERSE)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
} else {
options.read(true).share_mode(FILE_SHARE_READ);
}
let file = options
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(prefix)?;
let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
return Err(io::Error::last_os_error().into());
}
if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
return Err(OpenRegularError::Symlink);
}
ancestors.push(file);
}
let file = ancestors.pop().ok_or(OpenRegularError::NotRegularFile)?;
if if want_directory {
!file.metadata()?.is_dir()
} else {
!file.metadata()?.is_file()
} {
return Err(OpenRegularError::NotRegularFile);
}
Ok(file)
}
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, GetFileType, BY_HANDLE_FILE_INFORMATION,
FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_TYPE_DISK,
};
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
.open(path)?;
if unsafe { GetFileType(file.as_raw_handle()) } != FILE_TYPE_DISK {
return Err(OpenRegularError::NotRegularFile);
}
let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
return Err(io::Error::last_os_error().into());
}
if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
return Err(OpenRegularError::Symlink);
}
if information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
return Err(OpenRegularError::NotRegularFile);
}
Ok(file)
}
#[cfg(test)]
#[path = "regular_open_tests.rs"]
mod open_tests;
#[cfg(unix)]
pub type RetainedFileIdentity = crate::FileIdentity;
#[cfg(windows)]
pub type RetainedFileIdentity = crate::WindowsFileIdentity;
#[cfg(unix)]
pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
use std::os::unix::fs::MetadataExt;
let metadata = file.metadata()?;
Ok(RetainedFileIdentity {
device: metadata.dev(),
inode: metadata.ino(),
})
}
#[cfg(windows)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindowsFileIndexIdentity {
pub volume_serial: u32,
pub file_index: u64,
}
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn retained_file_index(file: &File) -> io::Result<WindowsFileIndexIdentity> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
};
let mut info: BY_HANDLE_FILE_INFORMATION = Default::default();
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(WindowsFileIndexIdentity {
volume_serial: info.dwVolumeSerialNumber,
file_index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
})
}
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
use std::{mem::size_of, os::windows::io::AsRawHandle};
use windows_sys::Win32::Storage::FileSystem::{
FileIdInfo, GetFileInformationByHandleEx, FILE_ID_INFO,
};
let mut info: FILE_ID_INFO = Default::default();
if unsafe {
GetFileInformationByHandleEx(
file.as_raw_handle(),
FileIdInfo,
(&mut info as *mut FILE_ID_INFO).cast(),
size_of::<FILE_ID_INFO>() as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(RetainedFileIdentity {
volume_serial_number: info.VolumeSerialNumber,
file_id: info.FileId.Identifier,
})
}
#[cfg(all(test, any(unix, windows)))]
mod tests {
use super::*;
#[test]
fn retained_directory_open_checks_type_and_identity() {
let dir = cortexkit_test_support::ScratchDir::new("retained-directory");
let opened = open_directory_nofollow_all(&dir).unwrap();
assert!(opened.metadata().unwrap().is_dir());
assert_eq!(
retained_file_identity(&opened).unwrap(),
retained_file_identity(&open_directory_nofollow_all(&dir).unwrap()).unwrap()
);
let path = dir.join("file");
std::fs::write(&path, b"file").unwrap();
assert!(open_directory_nofollow_all(&path).is_err());
assert!(open_directory_nofollow_all(std::path::Path::new("relative")).is_err());
}
#[cfg(unix)]
#[test]
fn retained_directory_open_refuses_symlink_ancestors_and_leaf() {
let dir = cortexkit_test_support::ScratchDir::new("retained-directory-symlink");
std::fs::create_dir_all(dir.join("real/child")).unwrap();
std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap();
assert!(open_directory_nofollow_all(&dir.join("link")).is_err());
assert!(open_directory_nofollow_all(&dir.join("link/child")).is_err());
}
#[cfg(windows)]
#[test]
fn retained_directory_open_can_publish_under_a_canonical_windows_path() {
use std::{ffi::OsStr, io::Write};
let root = cortexkit_test_support::ScratchDir::new("retained-canonical-directory");
let canonical = std::fs::canonicalize(root.path()).unwrap();
let parent = open_directory_nofollow_all(&canonical).unwrap();
let mut file = crate::RetainedTempFile::create_for_publish(&parent).unwrap();
file.file_mut().write_all(b"published").unwrap();
file.publish(OsStr::new("published")).unwrap();
assert_eq!(std::fs::read(root.join("published")).unwrap(), b"published");
}
#[cfg(windows)]
#[test]
fn retained_directory_open_coexists_with_an_existing_directory_writer() {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::{FILE_ADD_FILE, FILE_FLAG_BACKUP_SEMANTICS};
let dir = cortexkit_test_support::ScratchDir::new("retained-directory-writer");
let child = dir.join("child");
std::fs::create_dir(&child).unwrap();
let writer = std::fs::OpenOptions::new()
.access_mode(FILE_ADD_FILE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(&dir)
.unwrap();
let parent = open_directory_nofollow_all(&dir).unwrap();
let reopened = open_directory_nofollow_all(&dir).unwrap();
assert_eq!(
retained_file_identity(&parent).unwrap(),
retained_file_identity(&reopened).unwrap()
);
assert!(open_directory_nofollow_all(&child)
.unwrap()
.metadata()
.unwrap()
.is_dir());
drop(writer);
}
#[cfg(windows)]
#[test]
fn retained_directory_open_still_blocks_rename_until_handle_closes() {
let dir = cortexkit_test_support::ScratchDir::new("retained-directory-rename");
let child = dir.join("child");
let renamed = dir.join("renamed");
std::fs::create_dir(&child).unwrap();
let handle = open_directory_nofollow_all(&child).unwrap();
assert!(std::fs::rename(&child, &renamed).is_err());
assert!(!renamed.exists());
drop(handle);
std::fs::rename(&child, &renamed).unwrap();
assert!(renamed.is_dir());
}
#[test]
fn retained_file_identity_hard_links_share_identity_but_copies_do_not() {
let root = cortexkit_test_support::ScratchDir::new("subc-retained-file");
let first = root.join("first");
let link = root.join("link");
let copy = root.join("copy");
std::fs::write(&first, b"same bytes").unwrap();
std::fs::hard_link(&first, &link).unwrap();
std::fs::copy(&first, ©).unwrap();
let id = |path| retained_file_identity(&File::open(path).unwrap()).unwrap();
assert_eq!(id(&first), id(&link));
assert_ne!(id(&first), id(©));
}
}