Skip to main content

alpha2_os/
descriptor_passing.rs

1//! Descriptors carried with the bytes of a Unix stream socket (`SCM_RIGHTS`).
2
3use std::collections::VecDeque;
4use std::io::{self, Read, Write};
5use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};
6use std::os::unix::net::UnixStream;
7
8#[repr(C, align(8))]
9struct Control([u8; 64]);
10
11#[cfg(any(target_os = "linux", target_os = "android"))]
12const SEND_FLAGS: libc::c_int = libc::MSG_NOSIGNAL;
13#[cfg(not(any(target_os = "linux", target_os = "android")))]
14const SEND_FLAGS: libc::c_int = 0;
15
16#[cfg(any(target_os = "linux", target_os = "android"))]
17const RECEIVE_FLAGS: libc::c_int = libc::MSG_CMSG_CLOEXEC;
18#[cfg(not(any(target_os = "linux", target_os = "android")))]
19const RECEIVE_FLAGS: libc::c_int = 0;
20
21fn one_descriptor() -> (usize, usize) {
22    let size = libc::c_uint::try_from(size_of::<RawFd>()).unwrap_or(4);
23    // SAFETY: both are arithmetic on their argument.
24    let (space, length) = unsafe { (libc::CMSG_SPACE(size), libc::CMSG_LEN(size)) };
25    let space = usize::try_from(space).unwrap_or(usize::MAX);
26    assert!(space <= size_of::<Control>());
27    (space, usize::try_from(length).unwrap_or(usize::MAX))
28}
29
30/// Writes all of `bytes` to `socket`, with `descriptor` attached to the first of them, so that
31/// the reader receives a copy of it with those bytes ([`DescriptorReader`]).
32///
33/// # Errors
34/// When `bytes` is empty, or the socket refuses the write.
35pub fn write_with_descriptor(
36    socket: &UnixStream,
37    bytes: &[u8],
38    descriptor: BorrowedFd<'_>,
39) -> io::Result<()> {
40    if bytes.is_empty() {
41        return Err(io::Error::new(
42            io::ErrorKind::InvalidInput,
43            "a descriptor needs at least one byte to travel with",
44        ));
45    }
46    let (space, length) = one_descriptor();
47    let mut control = Control([0; 64]);
48    let mut part = libc::iovec {
49        iov_base: bytes.as_ptr().cast_mut().cast(),
50        iov_len: bytes.len(),
51    };
52    // SAFETY: an all-zero `msghdr` is valid; the fields the call reads are set below.
53    let mut message: libc::msghdr = unsafe { std::mem::zeroed() };
54    message.msg_iov = &raw mut part;
55    message.msg_iovlen = 1;
56    message.msg_control = control.0.as_mut_ptr().cast();
57    #[allow(
58        clippy::useless_conversion,
59        clippy::unnecessary_fallible_conversions,
60        reason = "the field's type differs between platforms"
61    )]
62    {
63        message.msg_controllen = space.try_into().map_err(io::Error::other)?;
64    }
65    // SAFETY: `message` names a control buffer of `space` bytes, room for one descriptor's
66    // header and data, which `CMSG_FIRSTHDR` and `CMSG_DATA` point into.
67    unsafe {
68        let header = libc::CMSG_FIRSTHDR(&raw const message);
69        (*header).cmsg_level = libc::SOL_SOCKET;
70        (*header).cmsg_type = libc::SCM_RIGHTS;
71        #[allow(
72            clippy::useless_conversion,
73            clippy::unnecessary_fallible_conversions,
74            reason = "the field's type differs between platforms"
75        )]
76        {
77            (*header).cmsg_len = length.try_into().map_err(io::Error::other)?;
78        }
79        libc::CMSG_DATA(header)
80            .cast::<RawFd>()
81            .write_unaligned(descriptor.as_raw_fd());
82    }
83    let sent = loop {
84        // SAFETY: `message` and the buffers it names live for the call.
85        let sent = unsafe { libc::sendmsg(socket.as_raw_fd(), &raw const message, SEND_FLAGS) };
86        if let Ok(sent) = usize::try_from(sent) {
87            break sent;
88        }
89        let error = io::Error::last_os_error();
90        if error.kind() != io::ErrorKind::Interrupted {
91            return Err(error);
92        }
93    };
94    let mut socket = socket;
95    socket.write_all(&bytes[sent..])
96}
97
98/// Reads a Unix stream socket and keeps, in arrival order, the descriptors that come with its
99/// bytes, each closed on `exec`. A read that receives more than one descriptor at once closes
100/// them and fails with `InvalidData`.
101#[derive(Debug)]
102pub struct DescriptorReader {
103    socket: OwnedFd,
104    received: VecDeque<OwnedFd>,
105}
106
107impl DescriptorReader {
108    /// A reader of `socket`.
109    pub fn new(socket: impl Into<OwnedFd>) -> Self {
110        Self {
111            socket: socket.into(),
112            received: VecDeque::new(),
113        }
114    }
115
116    /// The oldest received descriptor not yet taken.
117    pub fn take_descriptor(&mut self) -> Option<OwnedFd> {
118        self.received.pop_front()
119    }
120
121    /// How many received descriptors were not taken.
122    #[must_use]
123    pub fn pending(&self) -> usize {
124        self.received.len()
125    }
126}
127
128#[cfg(not(any(target_os = "linux", target_os = "android")))]
129fn close_on_exec(descriptor: &OwnedFd) -> io::Result<()> {
130    // SAFETY: `fcntl` reads no memory; `descriptor` is open.
131    if unsafe { libc::fcntl(descriptor.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
132        return Err(io::Error::last_os_error());
133    }
134    Ok(())
135}
136
137impl Read for DescriptorReader {
138    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
139        let (space, _) = one_descriptor();
140        let mut control = Control([0; 64]);
141        let mut part = libc::iovec {
142            iov_base: buf.as_mut_ptr().cast(),
143            iov_len: buf.len(),
144        };
145        // SAFETY: an all-zero `msghdr` is valid; the fields the call reads are set below.
146        let mut message: libc::msghdr = unsafe { std::mem::zeroed() };
147        message.msg_iov = &raw mut part;
148        message.msg_iovlen = 1;
149        message.msg_control = control.0.as_mut_ptr().cast();
150        #[allow(
151            clippy::useless_conversion,
152            clippy::unnecessary_fallible_conversions,
153            reason = "the field's type differs between platforms"
154        )]
155        {
156            message.msg_controllen = space.try_into().map_err(io::Error::other)?;
157        }
158        let read = loop {
159            // SAFETY: `message` and the buffers it names live for the call.
160            let read =
161                unsafe { libc::recvmsg(self.socket.as_raw_fd(), &raw mut message, RECEIVE_FLAGS) };
162            if let Ok(read) = usize::try_from(read) {
163                break read;
164            }
165            let error = io::Error::last_os_error();
166            if error.kind() != io::ErrorKind::Interrupted {
167                return Err(error);
168            }
169        };
170        let mut descriptors = Vec::new();
171        // SAFETY: `recvmsg` filled the control buffer and set its length; the macros walk it, and
172        // each descriptor it holds was installed in this process for this message alone.
173        unsafe {
174            let mut header = libc::CMSG_FIRSTHDR(&raw const message);
175            while !header.is_null() {
176                if (*header).cmsg_level == libc::SOL_SOCKET
177                    && (*header).cmsg_type == libc::SCM_RIGHTS
178                {
179                    let data = libc::CMSG_DATA(header);
180                    let start = data.offset_from(header.cast::<u8>()).cast_unsigned();
181                    #[allow(
182                        clippy::useless_conversion,
183                        clippy::unnecessary_fallible_conversions,
184                        reason = "the field's type differs between platforms"
185                    )]
186                    let length = usize::try_from((*header).cmsg_len).unwrap_or(0);
187                    let count = length.saturating_sub(start) / size_of::<RawFd>();
188                    for index in 0..count {
189                        let descriptor = data.cast::<RawFd>().add(index).read_unaligned();
190                        descriptors.push(OwnedFd::from_raw_fd(descriptor));
191                    }
192                }
193                header = libc::CMSG_NXTHDR(&raw const message, header);
194            }
195        }
196        if descriptors.len() > 1 || message.msg_flags & libc::MSG_CTRUNC != 0 {
197            return Err(io::Error::new(
198                io::ErrorKind::InvalidData,
199                "more than one descriptor came with one write",
200            ));
201        }
202        #[cfg(not(any(target_os = "linux", target_os = "android")))]
203        for descriptor in &descriptors {
204            close_on_exec(descriptor)?;
205        }
206        self.received.extend(descriptors);
207        Ok(read)
208    }
209}
210
211#[cfg(test)]
212#[path = "descriptor_passing_tests.rs"]
213mod tests;