1//! Descriptors on a socket.2//!3//! A descriptor travels with the **first byte of its frame**. The receiver4//! takes that byte with `recvmsg`, so the ancillary data cannot be separated5//! from the frame that owns it. The rest of the frame is an ordinary read.6//!7//! This crate contains no `unsafe`. The ancillary buffers are `rustix` types,8//! and the descriptors it hands back are `OwnedFd`, so a received descriptor is9//! closed by the drop that ends its lifetime. Nothing here can leak one.10//!11//! The sender states the descriptors it wants to send; the receiver gets what12//! arrived. There is no descriptor number on the wire after the `grant` frame,13//! because the kernel assigns the receiving side its own numbers.1415use std::io::{self, Read};16use std::mem::MaybeUninit;17use std::os::fd::{BorrowedFd, OwnedFd};18use std::os::unix::net::UnixStream;1920use rustix::io::Errno;21use rustix::net::{22RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer,23SendAncillaryMessage, SendFlags, recvmsg, sendmsg,24 };2526usecrate::frame::{Error, Frame, Header, MAX_PAYLOAD, read_frame};2728/// The kernel's limit on descriptors in one message (`SCM_MAX_FD` on Linux).29/// It is a physical limit, not a setting.30pubconstMAX_FDS: usize = 253;3132/// Writes one frame and the descriptors that belong to it.33///34/// The descriptors ride with the first byte. A partial write is finished with35/// ordinary writes; the kernel delivers the ancillary data once, with the byte36/// it was attached to.37pubfnsend_frame(38 socket: &UnixStream,39 header: Header,40 payload: &[u8],41 fds: &[BorrowedFd<'_>],42 ) -> Result<(), Error> {43if fds.len() > MAX_FDS {44returnErr(Error::TooManyDescriptors(fds.len()));45 }46if payload.len() > MAX_PAYLOAD {47returnErr(Error::TooLarge(payload.len()));48 }49if header.length as usize != payload.len() {50returnErr(Error::Frame(crate::frame::FrameError::Mismatch {51 header: header.length,52 payload: payload.len(),53 }));54 }5556let head = header.encode();57letmut space = vec![MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(fds.len()))];58letmut control = SendAncillaryBuffer::new(&mut space);59if !fds.is_empty() {60let pushed = control.push(SendAncillaryMessage::ScmRights(fds));61 debug_assert!(pushed, "the buffer was sized for every descriptor");62if !pushed {63returnErr(Error::TooManyDescriptors(fds.len()));64 }65 }6667let iov = [io::IoSlice::new(&head), io::IoSlice::new(payload)];68let flags = SendFlags::NOSIGNAL;69let total = head.len() + payload.len();70letmut written = retry(|| sendmsg(socket, &iov, &mut control, flags)).map_err(errno)?;71if written == 0 {72returnErr(Error::Io(io::ErrorKind::WriteZero.into()));73 }7475// Finish from the two slices, not from a flattened copy. A frame that the76// first sendmsg wrote whole never allocates anything. The rest carries no77// descriptors, so it has its own empty control buffer.78letmut empty = [];79letmut no_control = SendAncillaryBuffer::new(&mut empty);80while written < total {81let (first, second) = split(&head, payload, written);82let rest = [io::IoSlice::new(first), io::IoSlice::new(second)];83let n = retry(|| sendmsg(socket, &rest, &mut no_control, flags)).map_err(errno)?;84if n == 0 {85returnErr(Error::Io(io::ErrorKind::WriteZero.into()));86 }87 written += n;88 }89Ok(())90 }9192/// Reads one frame and the descriptors that belong to it.93///94/// `Ok(None)` means the peer closed the socket at a frame boundary. A frame95/// that arrives with more descriptors than [`MAX_FDS`] is refused, and the96/// descriptors that did arrive are dropped, so none leak.97pubfnrecv_frame(socket: &UnixStream) -> Result<Option<(Frame, Vec<OwnedFd>)>, Error> {98letmut first = [0u8; 1];99letmut space = vec![MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(MAX_FDS))];100letmut control = RecvAncillaryBuffer::new(&mut space);101letmut iov = [io::IoSliceMut::new(&mut first)];102let msg = retry(|| recvmsg(socket, &mut iov, &mut control, RecvFlags::CMSG_CLOEXEC))103 .map_err(errno)?;104105if msg.bytes == 0 {106returnOk(None);107 }108if msg.flags.contains(ReturnFlags::CTRUNC) {109// The buffer sized for MAX_FDS could not hold what arrived. Dropping110// the buffer closes every descriptor that did fit.111returnErr(Error::TruncatedDescriptors);112 }113114letmut fds = Vec::new();115for message in control.drain() {116ifletRecvAncillaryMessage::ScmRights(received) = message {117 fds.extend(received);118 }119 }120121letmut reader = Prefixed {122 first: Some(first[0]),123 socket,124 };125let frame =126read_frame(&mut reader)?.ok_or_else(|| Error::Io(io::ErrorKind::UnexpectedEof.into()))?;127Ok(Some((frame, fds)))128 }129130/// The one byte that came with the descriptors, then the socket.131structPrefixed<'a> {132 first: Option<u8>,133 socket: &'a UnixStream,134 }135136implReadforPrefixed<'_> {137fnread(&mutself, buf: &mut [u8]) -> io::Result<usize> {138if buf.is_empty() {139returnOk(0);140 }141ifletSome(byte) = self.first.take() {142 buf[0] = byte;143returnOk(1);144 }145self.socket.read(buf)146 }147 }148149/// Calls one socket operation again when a signal interrupts it.150fn retry<T>(mut call: implFnMut() -> Result<T, Errno>) -> Result<T, Errno> {151loop {152matchcall() {153Err(Errno::INTR) => continue,154 other => return other,155 }156 }157 }158159/// The part of the header and payload that is still to write.160fn split<'a>(head: &'a [u8], payload: &'a [u8], written: usize) -> (&'a [u8], &'a [u8]) {161if written < head.len() {162 (&head[written..], payload)163 } else {164let at = (written - head.len()).min(payload.len());165 (&[], &payload[at..])166 }167 }168169fnerrno(e: Errno) -> Error {170Error::Io(e.into())171 }