Skip to main content

webbluetooth_linux/dbus/
fds.rs

1//! Receiving file descriptors over D-Bus.
2//!
3//! A D-Bus value of type `h` is not a descriptor. It is an *index* into a list
4//! of descriptors that travelled beside the message, in the ancillary data of
5//! the `sendmsg` that carried it — `SCM_RIGHTS`, the Unix-socket mechanism for
6//! passing an open file from one process to another.
7//!
8//! That has a consequence worth stating plainly: a reader using `read()` does
9//! not merely ignore those descriptors, it *destroys* them. The kernel has
10//! nowhere to put ancillary data when no control buffer is supplied, so it
11//! discards it and closes the descriptors. There is no error and nothing in
12//! the message body to suggest anything went missing.
13//!
14//! So receiving a descriptor is not a decoding change, it is a transport
15//! change: the socket has to be read with `recvmsg` and a control buffer from
16//! the very first byte, whether or not anything is expecting a descriptor yet.
17//!
18//! # Matching descriptors to messages
19//!
20//! D-Bus runs over a stream socket, so a `recvmsg` boundary is not a message
21//! boundary — one read can span two messages, or half of one. Descriptors,
22//! however, arrive attached to the read that carried the bytes they belong to,
23//! and the specification requires a sender to attach them to the message whose
24//! header declares them.
25//!
26//! The rule that follows is simple and is what this implements: descriptors go
27//! into a queue in arrival order, and each parsed message takes the number its
28//! `UNIX_FDS` header field declares off the front. A message declaring none
29//! takes none, so an unrelated message in between cannot steal them.
30
31use std::ffi::c_void;
32use std::os::fd::RawFd;
33
34#[repr(C)]
35struct IoVec {
36    base: *mut c_void,
37    len: usize,
38}
39
40// `msghdr` and `cmsghdr` are libc's, laid out as the kernel expects. They are
41// written out here for the same reason everything else in this crate is: the
42// alternative is a dependency for two structs whose shape is fixed by the ABI.
43#[repr(C)]
44struct MsgHdr {
45    name: *mut c_void,
46    namelen: u32,
47    iov: *mut IoVec,
48    iovlen: usize,
49    control: *mut c_void,
50    controllen: usize,
51    flags: i32,
52}
53
54#[repr(C)]
55struct CmsgHdr {
56    len: usize,
57    level: i32,
58    kind: i32,
59}
60
61const SOL_SOCKET: i32 = 1;
62const SCM_RIGHTS: i32 = 1;
63/// Enough for 16 descriptors, which is far more than any one D-Bus message
64/// carries — BlueZ sends one.
65const CONTROL_CAPACITY: usize = 256;
66
67unsafe extern "C" {
68    fn recvmsg(fd: RawFd, msg: *mut MsgHdr, flags: i32) -> isize;
69    fn close(fd: RawFd) -> i32;
70    fn dup(fd: RawFd) -> RawFd;
71}
72
73/// Round up to the alignment `cmsghdr` uses, which is the platform word.
74const fn align(len: usize) -> usize {
75    let a = std::mem::align_of::<usize>();
76    (len + a - 1) & !(a - 1)
77}
78
79/// What one `recvmsg` produced.
80pub struct Received {
81    pub bytes: usize,
82    pub fds: Vec<RawFd>,
83}
84
85/// Read from `fd`, collecting any descriptors that arrive with the data.
86///
87/// Returns `Ok(None)` if the call was interrupted, which the caller should
88/// treat as "try again" rather than as an end of stream.
89pub fn recv_with_fds(fd: RawFd, buffer: &mut [u8]) -> std::io::Result<Option<Received>> {
90    let mut control = [0u8; CONTROL_CAPACITY];
91    let mut iov = IoVec {
92        base: buffer.as_mut_ptr() as *mut c_void,
93        len: buffer.len(),
94    };
95    let mut header = MsgHdr {
96        name: std::ptr::null_mut(),
97        namelen: 0,
98        iov: &mut iov,
99        iovlen: 1,
100        control: control.as_mut_ptr() as *mut c_void,
101        controllen: control.len(),
102        flags: 0,
103    };
104
105    let n = unsafe { recvmsg(fd, &mut header, 0) };
106    if n < 0 {
107        // `last_os_error` rather than a declared `__errno_location`: that
108        // symbol is glibc's, and this file is compiled on the development
109        // host too, where the equivalent is named something else.
110        let e = std::io::Error::last_os_error();
111        if e.kind() == std::io::ErrorKind::Interrupted {
112            return Ok(None);
113        }
114        return Err(e);
115    }
116
117    // Walk the control messages. There is usually none; when BlueZ answers an
118    // `AcquireWrite` there is exactly one, carrying one descriptor.
119    let mut fds = Vec::new();
120    let mut offset = 0usize;
121    while offset + std::mem::size_of::<CmsgHdr>() <= header.controllen {
122        // SAFETY: `offset` is within the control buffer, checked above.
123        let cmsg = unsafe { &*(control.as_ptr().add(offset) as *const CmsgHdr) };
124        if cmsg.len < std::mem::size_of::<CmsgHdr>() || offset + cmsg.len > header.controllen {
125            break; // Malformed; stop rather than read past the buffer.
126        }
127        if cmsg.level == SOL_SOCKET && cmsg.kind == SCM_RIGHTS {
128            let payload = cmsg.len - std::mem::size_of::<CmsgHdr>();
129            let count = payload / std::mem::size_of::<RawFd>();
130            let data = unsafe {
131                control
132                    .as_ptr()
133                    .add(offset + std::mem::size_of::<CmsgHdr>())
134            };
135            for i in 0..count {
136                // SAFETY: `count` was derived from the length the kernel set.
137                let raw = unsafe { std::ptr::read_unaligned(data.cast::<RawFd>().add(i)) };
138                fds.push(raw);
139            }
140        }
141        offset += align(cmsg.len);
142    }
143
144    Ok(Some(Received {
145        bytes: n as usize,
146        fds,
147    }))
148}
149
150/// Close a descriptor this module handed out.
151///
152/// # Safety
153/// `fd` must be one received here and not already closed.
154pub unsafe fn close_raw(fd: RawFd) {
155    unsafe { close(fd) };
156}
157
158/// Duplicate a received descriptor before handing it to a long-lived object.
159pub fn duplicate(fd: RawFd) -> std::io::Result<RawFd> {
160    let duplicate = unsafe { dup(fd) };
161    if duplicate < 0 {
162        Err(std::io::Error::last_os_error())
163    } else {
164        Ok(duplicate)
165    }
166}
167
168/// Descriptors received but not yet claimed by a message.
169///
170/// Kept in arrival order. Anything still here when the connection closes is
171/// closed with it: a descriptor nobody claimed is a leaked open file, and the
172/// process has no other handle on it.
173#[derive(Default)]
174pub struct Pending {
175    queue: std::collections::VecDeque<RawFd>,
176}
177
178impl Pending {
179    pub fn push(&mut self, fds: impl IntoIterator<Item = RawFd>) {
180        self.queue.extend(fds);
181    }
182
183    /// Take `count` descriptors for a message that declared that many.
184    ///
185    /// Fewer than asked for means the peer's header disagreed with what it
186    /// sent, which is a protocol error on their side; whatever is available is
187    /// returned rather than blocking for something that is not coming.
188    pub fn take(&mut self, count: usize) -> Vec<RawFd> {
189        (0..count).filter_map(|_| self.queue.pop_front()).collect()
190    }
191
192    pub fn len(&self) -> usize {
193        self.queue.len()
194    }
195
196    pub fn is_empty(&self) -> bool {
197        self.queue.is_empty()
198    }
199}
200
201impl Drop for Pending {
202    fn drop(&mut self) {
203        for fd in self.queue.drain(..) {
204            // Nobody claimed it, and nothing else knows it exists.
205            unsafe { close(fd) };
206        }
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn control_messages_are_word_aligned() {
216        let word = std::mem::size_of::<usize>();
217        assert_eq!(align(1), word);
218        assert_eq!(align(word), word);
219        assert_eq!(align(word + 1), word * 2);
220    }
221
222    /// The layouts are the kernel's, not ours. Getting one wrong means reading
223    /// a descriptor out of the wrong offset — which yields a plausible-looking
224    /// small integer rather than an error.
225    #[test]
226    fn the_headers_match_the_kernel_abi() {
227        // `cmsghdr` is a length, then two ints.
228        assert_eq!(
229            std::mem::size_of::<CmsgHdr>(),
230            std::mem::size_of::<usize>() + 2 * std::mem::size_of::<i32>(),
231        );
232        assert_eq!(
233            std::mem::align_of::<CmsgHdr>(),
234            std::mem::align_of::<usize>()
235        );
236        // `iovec` is a pointer and a length.
237        assert_eq!(
238            std::mem::size_of::<IoVec>(),
239            std::mem::size_of::<*mut c_void>() + std::mem::size_of::<usize>(),
240        );
241    }
242
243    /// Dropping these is safe because the queue is empty, which both tests
244    /// here assert before they end.
245    ///
246    /// It matters: the descriptors are made up — 10, 11, 12 are somebody
247    /// else's open files in this process — so a `Drop` that reached one would
248    /// close it. An empty queue closes nothing.
249    ///
250    /// They used to end by forgetting the queue instead, which avoided the
251    /// same hazard by never running `Drop` at all, and leaked its buffer —
252    /// which is what `./scripts/check.sh miri` had been reporting.
253    ///
254    /// Nothing else catches this, so the assertions are the check. Miri is not
255    /// a second opinion here: it shims `close` rather than refusing it, so a
256    /// queue left full passes there and only bites on a real Linux run.
257    #[test]
258    fn a_message_takes_only_what_it_declared() {
259        let mut pending = Pending::default();
260        pending.push([10, 11, 12]);
261        assert_eq!(pending.len(), 3);
262
263        assert_eq!(pending.take(0), Vec::<RawFd>::new(), "a message with none");
264        assert_eq!(pending.take(1), vec![10], "takes from the front");
265        assert_eq!(pending.take(2), vec![11, 12]);
266        assert!(pending.is_empty());
267
268        // Asking for more than arrived yields what there is rather than
269        // hanging for something the peer is not going to send.
270        assert_eq!(pending.take(4), Vec::<RawFd>::new());
271        assert!(
272            pending.is_empty(),
273            "or dropping it would close 10, 11 and 12"
274        );
275    }
276
277    /// Order is the whole basis for matching descriptors to messages.
278    #[test]
279    fn descriptors_come_out_in_the_order_they_arrived() {
280        let mut pending = Pending::default();
281        pending.push([1, 2]);
282        pending.push([3]);
283        assert_eq!(pending.take(3), vec![1, 2, 3]);
284        assert!(pending.is_empty(), "or dropping it would close 1, 2 and 3");
285    }
286
287    #[cfg(target_os = "linux")]
288    #[test]
289    fn duplicate_creates_an_independent_descriptor() {
290        use std::os::fd::{AsRawFd, FromRawFd};
291        let (left, _right) = std::os::unix::net::UnixStream::pair().unwrap();
292        let duplicate = duplicate(left.as_raw_fd()).unwrap();
293        let duplicate_file = unsafe { std::fs::File::from_raw_fd(duplicate) };
294        drop(duplicate_file);
295        assert!(left.peer_addr().is_ok());
296    }
297
298    #[test]
299    fn duplicate_rejects_invalid_descriptors() {
300        assert!(duplicate(-1).is_err());
301    }
302}