#![allow(unsafe_code)]
use core::fmt;
use std::fs::File;
use std::io;
use std::os::fd::{AsFd, BorrowedFd, IntoRawFd};
use std::os::unix::io::{FromRawFd, RawFd};
pub(crate) const RESERVED_FD_FLOOR: RawFd = 3;
pub fn adoptable_fd(fd: RawFd) -> Result<(), SysError> {
if fd < RESERVED_FD_FLOOR {
return Err(SysError::ReservedFd(fd));
}
nix::fcntl::fcntl(fd, nix::fcntl::FcntlArg::F_GETFD).map_err(|errno| SysError::BadFd {
fd,
errno: errno.to_string(),
})?;
Ok(())
}
pub unsafe fn adopt_fd(fd: RawFd) -> Result<File, SysError> {
adoptable_fd(fd)?;
Ok(unsafe { File::from_raw_fd(fd) })
}
pub fn adopt_handover_fd(fd: RawFd) -> Result<File, SysError> {
unsafe { adopt_fd(fd) }
}
#[derive(Debug)]
pub(crate) struct OpenFd(RawFd);
impl OpenFd {
pub(crate) fn new(fd: RawFd) -> Result<Self, SysError> {
adoptable_fd(fd)?;
Ok(Self(fd))
}
}
impl AsFd for OpenFd {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.0) }
}
}
pub(crate) fn duplicate_fd(fd: RawFd) -> io::Result<RawFd> {
nix::fcntl::fcntl(fd, nix::fcntl::FcntlArg::F_GETFD)?;
let borrowed = unsafe { BorrowedFd::borrow_raw(fd) };
Ok(borrowed.try_clone_to_owned()?.into_raw_fd())
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SysError {
ReservedFd(RawFd),
BadFd {
fd: RawFd,
errno: String,
},
}
impl fmt::Display for SysError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ReservedFd(fd) if *fd < 0 => {
write!(f, "fd {fd} is negative and cannot name a descriptor")
}
Self::ReservedFd(fd) => {
write!(f, "fd {fd} is reserved for stdio and cannot be adopted")
}
Self::BadFd { fd, errno } => {
write!(
f,
"fd {fd} is not an open descriptor in this process: {errno}"
)
}
}
}
}
impl core::error::Error for SysError {}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
use std::os::unix::io::{AsRawFd, IntoRawFd};
#[test]
fn a_real_inherited_descriptor_is_adopted_and_owned() {
let (parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
let fd = child.into_raw_fd();
{
let mut adopted = unsafe { adopt_fd(fd) }.unwrap();
std::io::Write::write_all(&mut adopted, b"hello\n").unwrap();
} let mut read = String::new();
let mut parent = parent;
parent.read_to_string(&mut read).unwrap();
assert_eq!(
read, "hello\n",
"EOF proves the adopted descriptor was closed on drop"
);
}
#[test]
fn stdio_numbers_are_refused() {
for fd in 0..3 {
let result = unsafe { adopt_fd(fd) };
assert_eq!(result.unwrap_err(), SysError::ReservedFd(fd));
}
}
#[test]
fn a_negative_fd_is_refused_with_an_accurate_message() {
let err = unsafe { adopt_fd(-1) }.unwrap_err();
assert_eq!(err, SysError::ReservedFd(-1));
assert!(
err.to_string().contains("negative"),
"a negative fd is not \"reserved for stdio\": {err}"
);
}
#[test]
fn a_closed_descriptor_is_refused_instead_of_adopted() {
const PROBE_FD: RawFd = 2048;
let (a, _b) = std::os::unix::net::UnixStream::pair().unwrap();
let parked = nix::fcntl::fcntl(a.as_raw_fd(), nix::fcntl::FcntlArg::F_DUPFD(PROBE_FD))
.expect("duplicating onto a high fd number must succeed");
assert!(
parked >= PROBE_FD,
"F_DUPFD must return a number at or above its floor, got {parked}"
);
drop(unsafe { adopt_fd(parked) }.unwrap()); let second = unsafe { adopt_fd(parked) };
assert!(matches!(second, Err(SysError::BadFd { .. })));
}
#[test]
fn a_fd_this_process_never_owned_is_refused() {
let err = unsafe { adopt_fd(4096) }.unwrap_err();
assert!(
matches!(err, SysError::BadFd { fd: 4096, .. }),
"a fd this process never owned must be refused as BadFd: {err:?}"
);
}
}