crates/edge/proto/src/fd.rs 5.9 KiB 171 lines Raw
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.14 15 use std::io::{self, Read};16 use std::mem::MaybeUninit;17 use std::os::fd::{BorrowedFd, OwnedFd};18 use std::os::unix::net::UnixStream;19 20 use rustix::io::Errno;21 use rustix::net::{22     RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer,23     SendAncillaryMessage, SendFlags, recvmsg, sendmsg,24 };25 26 use crate::frame::{Error, Frame, Header, MAX_PAYLOAD, read_frame};27 28 /// The kernel's limit on descriptors in one message (`SCM_MAX_FD` on Linux).29 /// It is a physical limit, not a setting.30 pub const MAX_FDS: usize = 253;31 32 /// 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.37 pub fn send_frame(38     socket: &UnixStream,39     header: Header,40     payload: &[u8],41     fds: &[BorrowedFd<'_>],42 ) -> Result<(), Error> {43     if fds.len() > MAX_FDS {44         return Err(Error::TooManyDescriptors(fds.len()));45     }46     if payload.len() > MAX_PAYLOAD {47         return Err(Error::TooLarge(payload.len()));48     }49     if header.length as usize != payload.len() {50         return Err(Error::Frame(crate::frame::FrameError::Mismatch {51             header: header.length,52             payload: payload.len(),53         }));54     }55 56     let head = header.encode();57     let mut space = vec![MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(fds.len()))];58     let mut control = SendAncillaryBuffer::new(&mut space);59     if !fds.is_empty() {60         let pushed = control.push(SendAncillaryMessage::ScmRights(fds));61         debug_assert!(pushed, "the buffer was sized for every descriptor");62         if !pushed {63             return Err(Error::TooManyDescriptors(fds.len()));64         }65     }66 67     let iov = [io::IoSlice::new(&head), io::IoSlice::new(payload)];68     let flags = SendFlags::NOSIGNAL;69     let total = head.len() + payload.len();70     let mut written = retry(|| sendmsg(socket, &iov, &mut control, flags)).map_err(errno)?;71     if written == 0 {72         return Err(Error::Io(io::ErrorKind::WriteZero.into()));73     }74 75     // 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.78     let mut empty = [];79     let mut no_control = SendAncillaryBuffer::new(&mut empty);80     while written < total {81         let (first, second) = split(&head, payload, written);82         let rest = [io::IoSlice::new(first), io::IoSlice::new(second)];83         let n = retry(|| sendmsg(socket, &rest, &mut no_control, flags)).map_err(errno)?;84         if n == 0 {85             return Err(Error::Io(io::ErrorKind::WriteZero.into()));86         }87         written += n;88     }89     Ok(())90 }91 92 /// 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.97 pub fn recv_frame(socket: &UnixStream) -> Result<Option<(Frame, Vec<OwnedFd>)>, Error> {98     let mut first = [0u8; 1];99     let mut space = vec![MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(MAX_FDS))];100     let mut control = RecvAncillaryBuffer::new(&mut space);101     let mut iov = [io::IoSliceMut::new(&mut first)];102     let msg = retry(|| recvmsg(socket, &mut iov, &mut control, RecvFlags::CMSG_CLOEXEC))103         .map_err(errno)?;104 105     if msg.bytes == 0 {106         return Ok(None);107     }108     if 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.111         return Err(Error::TruncatedDescriptors);112     }113 114     let mut fds = Vec::new();115     for message in control.drain() {116         if let RecvAncillaryMessage::ScmRights(received) = message {117             fds.extend(received);118         }119     }120 121     let mut reader = Prefixed {122         first: Some(first[0]),123         socket,124     };125     let frame =126         read_frame(&mut reader)?.ok_or_else(|| Error::Io(io::ErrorKind::UnexpectedEof.into()))?;127     Ok(Some((frame, fds)))128 }129 130 /// The one byte that came with the descriptors, then the socket.131 struct Prefixed<'a> {132     first: Option<u8>,133     socket: &'a UnixStream,134 }135 136 impl Read for Prefixed<'_> {137     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {138         if buf.is_empty() {139             return Ok(0);140         }141         if let Some(byte) = self.first.take() {142             buf[0] = byte;143             return Ok(1);144         }145         self.socket.read(buf)146     }147 }148 149 /// Calls one socket operation again when a signal interrupts it.150 fn retry<T>(mut call: impl FnMut() -> Result<T, Errno>) -> Result<T, Errno> {151     loop {152         match call() {153             Err(Errno::INTR) => continue,154             other => return other,155         }156     }157 }158 159 /// The part of the header and payload that is still to write.160 fn split<'a>(head: &'a [u8], payload: &'a [u8], written: usize) -> (&'a [u8], &'a [u8]) {161     if written < head.len() {162         (&head[written..], payload)163     } else {164         let at = (written - head.len()).min(payload.len());165         (&[], &payload[at..])166     }167 }168 169 fn errno(e: Errno) -> Error {170     Error::Io(e.into())171 }