use std::fs::File;
#[cfg(not(target_os = "macos"))]
use std::fs::OpenOptions;
use std::io;
use std::path::Path;
pub(super) fn child(
directory: &File,
path: &Path,
name: &std::ffi::OsStr,
is_dir: bool,
) -> io::Result<File> {
#[cfg(unix)]
{
use rustix::fs::{Mode, OFlags};
let _ = path;
let flags = OFlags::RDONLY
| OFlags::NOFOLLOW
| OFlags::NONBLOCK
| OFlags::CLOEXEC
| if is_dir {
OFlags::DIRECTORY
} else {
OFlags::empty()
};
Ok(File::from(rustix::fs::openat(
directory,
name,
flags,
Mode::empty(),
)?))
}
#[cfg(not(unix))]
{
let _ = directory;
open_platform(&path.join(name), is_dir)
}
}
pub(super) fn entries(
directory: &File,
path: &Path,
) -> io::Result<Box<dyn Iterator<Item = io::Result<std::ffi::OsString>>>> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
let reader = child(directory, path, std::ffi::OsStr::new("."), true)?;
let entries = rustix::fs::Dir::read_from(&reader)?;
Ok(Box::new(entries.filter_map(|entry| match entry {
Ok(entry) if matches!(entry.file_name().to_bytes(), b"." | b"..") => None,
Ok(entry) => Some(Ok(
std::ffi::OsStr::from_bytes(entry.file_name().to_bytes()).to_owned(),
)),
Err(error) => Some(Err(error.into())),
})))
}
#[cfg(not(unix))]
{
let _ = directory;
Ok(Box::new(
std::fs::read_dir(path)?.map(|entry| entry.map(|entry| entry.file_name())),
))
}
}
pub(super) enum Kind {
Directory,
File,
Link,
Other,
}
pub(super) fn kind(directory: &File, path: &Path, name: &std::ffi::OsStr) -> io::Result<Kind> {
#[cfg(unix)]
{
use rustix::fs::{AtFlags, FileType, statat};
let _ = path;
Ok(
match FileType::from_raw_mode(
statat(directory, name, AtFlags::SYMLINK_NOFOLLOW)?.st_mode,
) {
FileType::Directory => Kind::Directory,
FileType::RegularFile => Kind::File,
FileType::Symlink => Kind::Link,
_ => Kind::Other,
},
)
}
#[cfg(not(unix))]
{
let _ = directory;
let metadata = std::fs::symlink_metadata(path.join(name))?;
Ok(if metadata.is_symlink() {
Kind::Link
} else if metadata.is_dir() {
Kind::Directory
} else if metadata.is_file() {
Kind::File
} else {
Kind::Other
})
}
}
pub(super) fn open(path: &Path) -> io::Result<File> {
let file = open_platform(path, false)?;
if !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"source must be a regular file",
));
}
Ok(file)
}
pub(super) fn open_directory(path: &Path) -> io::Result<File> {
let file = open_platform(path, true)?;
if !file.metadata()?.is_dir() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"source root is not a directory",
));
}
Ok(file)
}
#[cfg(target_os = "macos")]
fn open_platform(path: &Path, is_directory: bool) -> io::Result<File> {
open_macos(
path,
is_directory,
macos_has_nofollow_any(rustix::system::uname().release().to_bytes()),
)
}
#[cfg(target_os = "macos")]
fn macos_has_nofollow_any(release: &[u8]) -> bool {
std::str::from_utf8(release)
.ok()
.and_then(|s| s.split('.').next())
.and_then(|major| major.parse::<u32>().ok())
.is_some_and(|major| major >= 20)
}
#[cfg(target_os = "macos")]
fn open_macos(path: &Path, is_directory: bool, nofollow_any: bool) -> io::Result<File> {
use rustix::fs::{Mode, OFlags};
use std::path::Component;
let absolute = if path.is_absolute() {
path.to_owned()
} else {
std::env::current_dir()?.join(path)
};
if absolute
.components()
.any(|c| matches!(c, Component::ParentDir))
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"source path must not contain parent traversal",
));
}
if nofollow_any {
let flags = OFlags::from_bits_retain(0x20000000)
| OFlags::RDONLY
| OFlags::NONBLOCK
| OFlags::CLOEXEC;
let flags = if is_directory {
flags | OFlags::DIRECTORY
} else {
flags
};
return Ok(File::from(rustix::fs::open(
&absolute,
flags,
Mode::empty(),
)?));
}
let mut directory = File::from(rustix::fs::open(
"/",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?);
let mut components = absolute.components().peekable();
while let Some(component) = components.next() {
let name = match component {
Component::RootDir | Component::CurDir => continue,
Component::Normal(name) => name,
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"source path must not contain parent traversal",
));
}
};
let file = open_macos_child(
&directory,
name,
is_directory || components.peek().is_some(),
)?;
if components.peek().is_none() {
return Ok(file);
}
directory = file;
}
if is_directory {
return Ok(directory);
}
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"source path has no file name",
))
}
#[cfg(target_os = "macos")]
fn open_macos_child(
directory: &File,
name: &std::ffi::OsStr,
is_directory: bool,
) -> io::Result<File> {
use rustix::fs::{Mode, OFlags};
let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
let flags = if is_directory {
flags | OFlags::DIRECTORY
} else {
flags
};
Ok(File::from(rustix::fs::openat(
directory,
name,
flags,
Mode::empty(),
)?))
}
#[cfg(all(
target_os = "linux",
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "arm",
target_arch = "riscv64",
target_arch = "riscv32"
)
))]
fn open_platform(path: &Path, is_directory: bool) -> io::Result<File> {
open_linux(path, Path::new("/proc/self/fd"), is_directory)
}
#[cfg(all(
target_os = "linux",
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "arm",
target_arch = "riscv64",
target_arch = "riscv32"
)
))]
fn open_linux(path: &Path, procfs: &Path, is_directory: bool) -> io::Result<File> {
use std::os::unix::fs::OpenOptionsExt;
use std::path::Component;
const NOFOLLOW: i32 = 0o400000;
const DIRECTORY: i32 = 0o200000;
const NONBLOCK: i32 = 0o4000;
const PATH_ONLY: i32 = 0o10000000;
let absolute = if path.is_absolute() {
path.to_owned()
} else {
std::env::current_dir()?.join(path)
};
let mut directory = OpenOptions::new()
.read(true)
.custom_flags(DIRECTORY | PATH_ONLY)
.open("/")?;
procfs_directory(&directory, procfs)?;
let mut components = absolute.components().peekable();
while let Some(component) = components.next() {
let name = match component {
Component::RootDir | Component::CurDir => continue,
Component::Normal(name) => name,
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"source path must not contain parent traversal",
));
}
};
let child = procfs_directory(&directory, procfs)?.join(name);
let flags = NOFOLLOW
| NONBLOCK
| if is_directory || components.peek().is_some() {
DIRECTORY | PATH_ONLY
} else {
0
};
let file = OpenOptions::new()
.read(true)
.custom_flags(flags)
.open(child)?;
if components.peek().is_none() {
return Ok(file);
}
directory = file;
}
if is_directory {
return Ok(directory);
}
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"source path has no file name",
))
}
#[cfg(any(
all(test, unix),
all(
target_os = "linux",
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "arm",
target_arch = "riscv64",
target_arch = "riscv32"
)
)
))]
fn procfs_directory(directory: &File, procfs: &Path) -> io::Result<std::path::PathBuf> {
use std::os::fd::AsRawFd;
let path = procfs.join(directory.as_raw_fd().to_string());
let unavailable = |cause: String| {
io::Error::new(
io::ErrorKind::Unsupported,
format!(
"Linux source loading requires accessible procfs descriptors at {}: {cause}",
procfs.display()
),
)
};
let metadata = std::fs::metadata(&path).map_err(|e| unavailable(e.to_string()))?;
if !metadata.is_dir() {
return Err(unavailable(
"held directory descriptor is not accessible as a directory".into(),
));
}
Ok(path)
}
#[cfg(not(any(
target_os = "macos",
all(
target_os = "linux",
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "arm",
target_arch = "riscv64",
target_arch = "riscv32"
)
)
)))]
fn open_platform(path: &Path, is_directory: bool) -> io::Result<File> {
let mut options = OpenOptions::new();
options.read(true);
#[cfg(windows)]
if is_directory {
use std::os::windows::fs::OpenOptionsExt;
options.custom_flags(0x02000000); }
#[cfg(not(windows))]
let _ = is_directory;
options.open(path)
}
#[cfg(all(
test,
any(
target_os = "macos",
all(
target_os = "linux",
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "arm",
target_arch = "riscv64",
target_arch = "riscv32"
)
)
)
))]
mod tests {
use super::*;
use std::fs;
use std::os::unix::fs::symlink;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
#[cfg(target_os = "macos")]
struct MacosDirectory(std::path::PathBuf);
#[cfg(target_os = "macos")]
impl MacosDirectory {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"qleisli-macos-openat-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&path).unwrap();
Self(fs::canonicalize(path).unwrap())
}
}
#[cfg(target_os = "macos")]
impl Drop for MacosDirectory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_nofollow_any_is_gated_by_runtime_version() {
for release in [
b"19.6.0".as_slice(),
b"16.7.0",
b"",
b"unknown",
b"999999999999",
] {
assert!(!macos_has_nofollow_any(release));
}
for release in [b"20.0.0".as_slice(), b"21.6.0", b"25.0.0"] {
assert!(macos_has_nofollow_any(release));
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_legacy_walk_rejects_links_and_retains_read_requirement() {
use std::os::unix::fs::PermissionsExt;
let root = MacosDirectory::new();
fs::create_dir(root.0.join("nested")).unwrap();
let source = root.0.join("nested/main.qli");
fs::write(&source, "original").unwrap();
assert!(open_macos(&source, false, false).is_ok());
fs::set_permissions(&root.0, fs::Permissions::from_mode(0o100)).unwrap();
let denied = File::open(&root.0).is_err();
let result = open_macos(&source, false, false);
fs::set_permissions(&root.0, fs::Permissions::from_mode(0o700)).unwrap();
if denied {
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::PermissionDenied);
}
fs::rename(root.0.join("nested"), root.0.join("renamed")).unwrap();
symlink(root.0.join("renamed"), root.0.join("nested")).unwrap();
assert!(open_macos(&source, false, false).is_err());
let saved = root.0.join("renamed/main.qli");
fs::remove_file(&saved).unwrap();
symlink(root.0.join("missing"), &saved).unwrap();
assert!(open_macos(&saved, false, false).is_err());
fs::remove_file(&saved).unwrap();
assert!(
std::process::Command::new("mkfifo")
.arg(&saved)
.status()
.unwrap()
.success()
);
assert!(
!open_macos(&saved, false, false)
.unwrap()
.metadata()
.unwrap()
.is_file()
);
}
#[cfg(target_os = "macos")]
#[test]
fn macos_openat_retains_parent_identity_after_path_replacement() {
use std::io::Read;
let root = MacosDirectory::new();
fs::create_dir(root.0.join("nested")).unwrap();
fs::write(root.0.join("nested/main.qli"), "original").unwrap();
fs::create_dir(root.0.join("replacement")).unwrap();
fs::write(root.0.join("replacement/main.qli"), "replacement").unwrap();
let held =
open_macos_child(&File::open(&root.0).unwrap(), "nested".as_ref(), true).unwrap();
fs::rename(root.0.join("nested"), root.0.join("renamed")).unwrap();
symlink(root.0.join("replacement"), root.0.join("nested")).unwrap();
let mut original = open_macos_child(&held, "main.qli".as_ref(), false).unwrap();
let mut text = String::new();
original.read_to_string(&mut text).unwrap();
assert_eq!(text, "original");
assert!(open(&root.0.join("nested/main.qli")).is_err());
}
#[cfg(target_os = "macos")]
#[test]
fn macos_fifo_source_replacement_is_rejected_without_a_writer() {
let root = MacosDirectory::new();
let source = root.0.join("main.qli");
fs::write(&source, "original").unwrap();
let mut discovered = vec![];
fs::write(
root.0.join("Qargo.toml"),
"schema-version=2\n[qrate]\nedition=\"2026\"\n",
)
.unwrap();
assert!(
super::super::collect_qli_files(
&root.0,
&open_directory(&root.0).unwrap(),
&mut super::super::SourceBudget {
policy: super::super::SourcePolicy::Legacy,
used: 0
},
&mut discovered
)
.is_ok()
);
assert_eq!(discovered[0].0, source);
fs::remove_file(&source).unwrap();
assert!(
std::process::Command::new("mkfifo")
.arg(&source)
.status()
.unwrap()
.success()
);
assert_eq!(
open(&source).unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
}
#[test]
fn unavailable_linux_procfs_has_a_targeted_diagnostic() {
let root = std::env::temp_dir().join(format!(
"qleisli-procfs-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&root).unwrap();
struct Cleanup(std::path::PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
let _cleanup = Cleanup(root.clone());
fs::write(root.join("file"), "not a descriptor directory").unwrap();
for procfs in [root.join("absent"), root.join("file")] {
let directory = File::open("/").unwrap();
let error = procfs_directory(&directory, &procfs).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
assert!(
error
.to_string()
.contains("Linux source loading requires accessible procfs descriptors"),
"{error}"
);
assert!(error.to_string().contains(&procfs.display().to_string()));
}
}
#[cfg(target_os = "linux")]
#[test]
fn missing_linux_source_is_not_misreported_as_missing_procfs() {
let root = std::env::temp_dir().join(format!(
"qleisli-missing-source-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let error = open(&root.join("main.qli")).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::NotFound);
assert!(!error.to_string().contains("procfs"));
}
#[test]
fn source_replacement_between_discovery_and_open_cannot_follow_links() {
let path = std::env::temp_dir().join(format!(
"qleisli-source-open-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&path).unwrap();
struct Cleanup(std::path::PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
let _cleanup = Cleanup(path.clone());
let root = fs::canonicalize(path).unwrap();
fs::create_dir(root.join("nested")).unwrap();
fs::write(root.join("nested/main.qli"), "original").unwrap();
fs::write(root.join("outside"), "replacement").unwrap();
let mut discovered = vec![];
fs::write(
root.join("Qargo.toml"),
"schema-version=2\n[qrate]\nedition=\"2026\"\n",
)
.unwrap();
assert!(
super::super::collect_qli_files(
&root,
&open_directory(&root).unwrap(),
&mut super::super::SourceBudget {
policy: super::super::SourcePolicy::Legacy,
used: 0
},
&mut discovered
)
.is_ok()
);
assert_eq!(discovered[0].0, root.join("nested/main.qli"));
let source = &discovered[0].0;
let original = open(source).unwrap();
fs::rename(source, root.join("original")).unwrap();
symlink(root.join("outside"), source).unwrap();
assert!(open(source).is_err());
use std::io::Read;
let mut text = String::new();
(&original).read_to_string(&mut text).unwrap();
assert_eq!(text, "original");
fs::remove_file(source).unwrap();
fs::write(source, "original").unwrap();
fs::rename(root.join("nested"), root.join("renamed")).unwrap();
symlink(root.join("renamed"), root.join("nested")).unwrap();
assert!(
open(source).is_err(),
"an intermediate replacement must also be rejected"
);
assert!(
open(&root.join("renamed")).is_err(),
"directories are not sources"
);
assert!(open(&root.join("original")).is_ok());
}
}