use std::io;
use std::os::fd::RawFd;
use anyhow::{Context as _, Result};
const FIRST: RawFd = 3;
const LISTS: [&str; 2] = ["/proc/self/fd", "/dev/fd"];
pub fn close_on_exec() -> Result<()> {
if close_range() {
return Ok(());
}
let mut failed = Vec::new();
for list in LISTS {
match walk(list) {
Ok(()) => return Ok(()),
Err(error) => failed.push(format!("{list}: {error}")),
}
}
Err(io::Error::other(failed.join("; "))).context(
"cannot keep the files OpenMoat was started with from the agent (marking them \
close-on-exec); refusing to start it",
)
}
#[cfg(target_os = "linux")]
#[expect(
unsafe_code,
reason = "the C library has no safe wrapper, nor rustix: one raw system call"
)]
fn close_range() -> bool {
use libc::c_long;
let first = c_long::from(FIRST);
let last: c_long = -1;
let Ok(flags) = u16::try_from(libc::CLOSE_RANGE_CLOEXEC).map(c_long::from) else {
return false;
};
let done = unsafe { libc::syscall(libc::SYS_close_range, first, last, flags) };
done == 0
}
#[cfg(not(target_os = "linux"))]
fn close_range() -> bool {
false
}
fn walk(list: &str) -> io::Result<()> {
let mut found = Vec::new();
for entry in std::fs::read_dir(list)? {
let name = entry?.file_name();
let fd: RawFd = name.to_str().and_then(|n| n.parse().ok()).ok_or_else(|| {
io::Error::other(format!("{} is not a descriptor", name.to_string_lossy()))
})?;
if fd >= FIRST {
found.push(fd);
}
}
for fd in found {
match mark(fd) {
Err(error) if error.raw_os_error() == Some(libc::EBADF) => {}
other => other?,
}
}
Ok(())
}
#[expect(
unsafe_code,
reason = "`fcntl` on a descriptor number this process does not own as an `OwnedFd`"
)]
fn mark(fd: RawFd) -> io::Result<()> {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags < 0 {
return Err(io::Error::last_os_error());
}
if flags & libc::FD_CLOEXEC != 0 {
return Ok(());
}
if unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) } < 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::os::fd::{AsRawFd as _, RawFd};
use super::{FIRST, LISTS, close_on_exec, walk};
const MANIFEST: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
#[expect(unsafe_code, reason = "the test reads the flag itself")]
fn flags(fd: RawFd) -> i32 {
unsafe { libc::fcntl(fd, libc::F_GETFD) }
}
#[expect(unsafe_code, reason = "the test clears the flag itself")]
fn inheritable(file: &File) -> RawFd {
let fd = file.as_raw_fd();
assert_eq!(unsafe { libc::fcntl(fd, libc::F_SETFD, 0) }, 0);
assert_eq!(flags(fd) & libc::FD_CLOEXEC, 0);
fd
}
#[test]
fn the_sweep_marks_an_inherited_descriptor_close_on_exec() {
let file = File::open(MANIFEST).unwrap();
let fd = inheritable(&file);
close_on_exec().unwrap();
assert_ne!(flags(fd) & libc::FD_CLOEXEC, 0);
}
#[test]
fn the_walk_marks_it_too_where_close_range_is_missing() {
let file = File::open(MANIFEST).unwrap();
let fd = inheritable(&file);
let list = LISTS
.into_iter()
.find(|l| std::path::Path::new(l).is_dir())
.unwrap();
walk(list).unwrap();
assert_ne!(flags(fd) & libc::FD_CLOEXEC, 0);
}
#[test]
fn standard_streams_are_left_alone() {
let before: Vec<i32> = (0..FIRST).map(flags).collect();
close_on_exec().unwrap();
let after: Vec<i32> = (0..FIRST).map(flags).collect();
assert_eq!(before, after);
}
#[test]
fn a_missing_listing_is_an_error() {
assert!(walk("/nonexistent/fd-list").is_err());
}
}