schedr_fd/lib.rs
1//! A task's inherited context channel, the one raw descriptor schedr adopts (decision 147).
2//!
3//! The agent starts a command task with one end of a datagram socket pair left open and its
4//! number in `SCHEDR_CTX_FD` (decision 143). Rust can only refer to a descriptor known by
5//! number through `unsafe` code, and the rest of the workspace forbids it; this crate holds the
6//! single block, and keeps it small: it **borrows** the number only to duplicate it, then
7//! checks the copy. The inherited descriptor is never owned (never closed here), so it can't be closed twice;
8//! the caller gets its own close-on-exec copy.
9
10use std::os::fd::{BorrowedFd, OwnedFd, RawFd};
11
12use rustix::io::Errno;
13use rustix::net::{AddressFamily, SocketType};
14
15#[cfg(test)]
16mod tests;
17
18/// Why an inherited descriptor isn't the task's context channel.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
20pub enum Inherited {
21 /// The number is one of stdin, stdout, stderr, or negative.
22 #[error("descriptor {0} can't be a context channel")]
23 Reserved(RawFd),
24 /// Nothing is open at that number (a parent process closed it).
25 #[error("descriptor {0} isn't open")]
26 Closed(RawFd),
27 /// Something else is open there: not a Unix datagram socket (the number was reused).
28 #[error("descriptor {0} isn't a Unix datagram socket")]
29 NotChannel(RawFd),
30 /// Duplicating it failed (e.g. the process is out of descriptors).
31 #[error("descriptor {fd} can't be duplicated: {errno}")]
32 Duplicate {
33 /// The descriptor.
34 fd: RawFd,
35 /// The error.
36 errno: Errno,
37 },
38}
39
40/// A close-on-exec copy of the inherited Unix datagram socket at `fd`.
41///
42/// Call it before starting threads that open or close descriptors: the number is borrowed
43/// while it is copied, and must not be closed or replaced meanwhile. What is checked and
44/// returned is the copy, so a later change of the number doesn't matter.
45///
46/// # Errors
47///
48/// [`Inherited`] when `fd` is stdin, stdout, stderr or negative, isn't open, isn't a Unix
49/// datagram socket, or can't be duplicated.
50pub fn inherited_datagram(fd: RawFd) -> Result<OwnedFd, Inherited> {
51 if fd <= 2 {
52 return Err(Inherited::Reserved(fd));
53 }
54 #[expect(
55 unsafe_code,
56 reason = "the only way to refer to an inherited descriptor by number (decision 147)"
57 )]
58 // SAFETY: the borrow lives only for the one `fcntl(F_DUPFD_CLOEXEC)` below, which either
59 // fails (`EBADF`: nothing open there) or makes this call's own copy; everything after it
60 // works on that copy, so the number being closed or replaced later can't change what is
61 // checked or returned. The borrow is never closed nor wrapped in an owning type, so no
62 // other owner can be closed twice (an inherited descriptor has none in this process: no
63 // Rust code opened it). The one precondition left: no other thread closes or replaces the
64 // number during that call. Callers adopt the channel before starting threads (the CLI does
65 // it first thing, before its runtime), which is documented on this function.
66 let borrowed = unsafe { BorrowedFd::borrow_raw(fd) };
67 let copy = match rustix::io::fcntl_dupfd_cloexec(borrowed, 3) {
68 Ok(copy) => copy,
69 Err(Errno::BADF) => return Err(Inherited::Closed(fd)),
70 Err(errno) => return Err(Inherited::Duplicate { fd, errno }),
71 };
72 let datagram = rustix::net::sockopt::socket_type(©) == Ok(SocketType::DGRAM);
73 let unix = rustix::net::getsockname(©)
74 .is_ok_and(|address| address.address_family() == AddressFamily::UNIX);
75 if !(datagram && unix) {
76 return Err(Inherited::NotChannel(fd));
77 }
78 Ok(copy)
79}