use std::{io, os::fd::RawFd};
#[cfg(not(target_os = "macos"))]
const DESCRIPTOR_HEADROOM_FACTOR: usize = 2;
#[cfg(not(target_os = "macos"))]
const SPARE_DESCRIPTORS: usize = 64;
#[derive(Clone, Copy)]
struct PipeEnd {
fd: RawFd,
end: Key,
peer: Key,
#[cfg(target_os = "macos")]
stat: EndIdentity,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(not(target_os = "macos"))]
struct Key(u64, Direction);
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(target_os = "macos")]
struct Key(u64);
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(not(target_os = "macos"))]
enum Direction {
Read,
Write,
}
#[cfg(not(target_os = "macos"))]
impl Direction {
fn peer(self) -> Self {
match self {
Self::Read => Self::Write,
Self::Write => Self::Read,
}
}
}
pub(super) struct Inherited {
ends: Vec<PipeEnd>,
}
impl Inherited {
#[cfg(target_os = "macos")]
pub(super) fn reserve() -> Self {
Self {
ends: snapshot().unwrap_or_default(),
}
}
#[cfg(not(target_os = "macos"))]
pub(super) fn reserve() -> Self {
let capacity = open_descriptors()
.unwrap_or(0)
.saturating_mul(DESCRIPTOR_HEADROOM_FACTOR)
.saturating_add(SPARE_DESCRIPTORS);
Self {
ends: Vec::with_capacity(capacity),
}
}
pub(super) fn release(&mut self, keep: RawFd) {
#[cfg(not(target_os = "macos"))]
{
self.ends.clear();
self.collect(keep);
}
#[cfg(target_os = "macos")]
self.ends
.retain(|end| inherited(end.fd, keep) && EndIdentity::read(end.fd) == Some(end.stat));
self.ends.sort_unstable_by_key(|end| end.end);
for end in &self.ends {
if self
.ends
.binary_search_by_key(&end.peer, |other| other.end)
.is_ok()
{
unsafe { libc::close(end.fd) };
}
}
}
}
#[cfg(not(target_os = "macos"))]
fn push(ends: &mut Vec<PipeEnd>, end: PipeEnd) {
if ends.len() < ends.capacity() {
ends.push(end);
}
}
fn inherited(fd: RawFd, keep: RawFd) -> bool {
if fd <= libc::STDERR_FILENO || fd == keep {
return false;
}
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
flags >= 0 && flags & libc::FD_CLOEXEC != 0
}
#[cfg(not(target_os = "macos"))]
fn open_descriptors() -> io::Result<usize> {
Ok(std::fs::read_dir("/proc/self/fd")?.count())
}
#[cfg(not(target_os = "macos"))]
const DIRECTORY_BUFFER_BYTES: usize = 4096;
#[cfg(not(target_os = "macos"))]
impl Inherited {
fn collect(&mut self, keep: RawFd) {
use rustix::fs::{Mode, OFlags, RawDir, open};
use std::{mem::MaybeUninit, os::fd::AsRawFd};
let Ok(directory) = open(
c"/proc/self/fd",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) else {
return;
};
let directory_fd = directory.as_raw_fd();
let mut buffer = [MaybeUninit::uninit(); DIRECTORY_BUFFER_BYTES];
let mut entries = RawDir::new(directory, &mut buffer);
while let Some(Ok(entry)) = entries.next() {
if let Some(fd) = descriptor(entry.file_name().to_bytes())
&& fd != directory_fd
&& inherited(fd, keep)
&& let Some(end) = pipe_end(fd)
{
push(&mut self.ends, end);
}
}
}
}
#[cfg(target_os = "linux")]
pub(super) fn close_except(keep: RawFd) -> io::Result<()> {
use rustix::fs::{Mode, OFlags, RawDir, open};
use std::{mem::MaybeUninit, os::fd::AsRawFd};
unsafe {
let keep = keep as u32;
if (keep == 0 || libc::syscall(libc::SYS_close_range, 0_u32, keep - 1, 0_u32) == 0)
&& libc::syscall(libc::SYS_close_range, keep + 1, u32::MAX, 0_u32) == 0
{
return Ok(());
}
}
let directory = open(
c"/proc/self/fd",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?;
let directory_fd = directory.as_raw_fd();
let mut buffer = [MaybeUninit::uninit(); DIRECTORY_BUFFER_BYTES];
let mut entries = RawDir::new(directory, &mut buffer);
while let Some(entry) = entries.next() {
if let Some(fd) = descriptor(entry?.file_name().to_bytes())
&& fd != directory_fd
&& fd != keep
{
unsafe { libc::close(fd) };
}
}
Ok(())
}
#[cfg(not(target_os = "macos"))]
fn descriptor(name: &[u8]) -> Option<RawFd> {
if name.is_empty() {
return None;
}
name.iter().try_fold(0 as RawFd, |fd, &byte| {
let digit = RawFd::from(byte.checked_sub(b'0').filter(|digit| *digit <= 9)?);
fd.checked_mul(10)?.checked_add(digit)
})
}
#[cfg(not(target_os = "macos"))]
fn pipe_end(fd: RawFd) -> Option<PipeEnd> {
let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
let stat = unsafe {
if libc::fstat(fd, stat.as_mut_ptr()) != 0 {
return None;
}
stat.assume_init()
};
if stat.st_mode & libc::S_IFMT != libc::S_IFIFO {
return None;
}
let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
let direction = match mode {
..0 => return None,
mode if mode & libc::O_ACCMODE == libc::O_RDONLY => Direction::Read,
mode if mode & libc::O_ACCMODE == libc::O_WRONLY => Direction::Write,
_ => return None,
};
let inode = stat.st_ino;
Some(PipeEnd {
fd,
end: Key(inode, direction),
peer: Key(inode, direction.peer()),
})
}
#[cfg(target_os = "macos")]
#[repr(C)]
struct ProcFileInfo {
open_flags: u32,
status: u32,
offset: libc::off_t,
kind: i32,
guard_flags: u32,
}
#[cfg(target_os = "macos")]
#[repr(C)]
struct PipeInfo {
stat: libc::vinfo_stat,
handle: u64,
peer_handle: u64,
status: i32,
reserved: i32,
}
#[cfg(target_os = "macos")]
#[repr(C)]
struct PipeFdInfo {
file: ProcFileInfo,
pipe: PipeInfo,
}
#[cfg(target_os = "macos")]
const PROC_PIDFDPIPEINFO: libc::c_int = 6;
#[cfg(target_os = "macos")]
fn snapshot() -> io::Result<Vec<PipeEnd>> {
let pid = libc::pid_t::try_from(std::process::id()).map_err(io::Error::other)?;
let bytes =
unsafe { libc::proc_pidinfo(pid, libc::PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0) };
if bytes <= 0 {
return Err(io::Error::last_os_error());
}
let capacity = bytes as usize / std::mem::size_of::<libc::proc_fdinfo>();
let mut descriptors = vec![
libc::proc_fdinfo {
proc_fd: 0,
proc_fdtype: 0
};
capacity
];
let written = unsafe {
libc::proc_pidinfo(
pid,
libc::PROC_PIDLISTFDS,
0,
descriptors.as_mut_ptr().cast(),
std::mem::size_of_val(descriptors.as_slice()) as i32,
)
};
if written < 0 {
return Err(io::Error::last_os_error());
}
let count = written as usize / std::mem::size_of::<libc::proc_fdinfo>();
Ok(descriptors
.into_iter()
.take(count)
.filter(|entry| entry.proc_fdtype == libc::PROX_FDTYPE_PIPE as u32)
.filter_map(|entry| pipe_end(pid, entry.proc_fd))
.collect())
}
#[cfg(target_os = "macos")]
#[derive(Clone, Copy, PartialEq, Eq)]
struct EndIdentity {
inode: libc::ino_t,
birth: (libc::time_t, libc::c_long),
}
#[cfg(target_os = "macos")]
impl EndIdentity {
fn read(fd: RawFd) -> Option<Self> {
let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
let stat = unsafe {
if libc::fstat(fd, stat.as_mut_ptr()) != 0 {
return None;
}
stat.assume_init()
};
(stat.st_mode & libc::S_IFMT == libc::S_IFIFO).then_some(Self {
inode: stat.st_ino,
birth: (stat.st_birthtime, stat.st_birthtime_nsec),
})
}
}
#[cfg(target_os = "macos")]
fn pipe_end(pid: libc::pid_t, fd: RawFd) -> Option<PipeEnd> {
let stat = EndIdentity::read(fd)?;
let mut info = std::mem::MaybeUninit::<PipeFdInfo>::uninit();
let size = libc::c_int::try_from(std::mem::size_of::<PipeFdInfo>()).ok()?;
let info = unsafe {
if libc::proc_pidfdinfo(pid, fd, PROC_PIDFDPIPEINFO, info.as_mut_ptr().cast(), size) != size
{
return None;
}
info.assume_init()
};
if info.pipe.peer_handle == 0 || EndIdentity::read(fd) != Some(stat) {
return None;
}
Some(PipeEnd {
fd,
end: Key(info.pipe.handle),
peer: Key(info.pipe.peer_handle),
stat,
})
}