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}
71
72/// Round up to the alignment `cmsghdr` uses, which is the platform word.
73const fn align(len: usize) -> usize {
74    let a = std::mem::align_of::<usize>();
75    (len + a - 1) & !(a - 1)
76}
77
78/// What one `recvmsg` produced.
79pub struct Received {
80    pub bytes: usize,
81    pub fds: Vec<RawFd>,
82}
83
84/// Read from `fd`, collecting any descriptors that arrive with the data.
85///
86/// Returns `Ok(None)` if the call was interrupted, which the caller should
87/// treat as "try again" rather than as an end of stream.
88pub fn recv_with_fds(fd: RawFd, buffer: &mut [u8]) -> std::io::Result<Option<Received>> {
89    let mut control = [0u8; CONTROL_CAPACITY];
90    let mut iov = IoVec {
91        base: buffer.as_mut_ptr() as *mut c_void,
92        len: buffer.len(),
93    };
94    let mut header = MsgHdr {
95        name: std::ptr::null_mut(),
96        namelen: 0,
97        iov: &mut iov,
98        iovlen: 1,
99        control: control.as_mut_ptr() as *mut c_void,
100        controllen: control.len(),
101        flags: 0,
102    };
103
104    let n = unsafe { recvmsg(fd, &mut header, 0) };
105    if n < 0 {
106        // `last_os_error` rather than a declared `__errno_location`: that
107        // symbol is glibc's, and this file is compiled on the development
108        // host too, where the equivalent is named something else.
109        let e = std::io::Error::last_os_error();
110        if e.kind() == std::io::ErrorKind::Interrupted {
111            return Ok(None);
112        }
113        return Err(e);
114    }
115
116    // Walk the control messages. There is usually none; when BlueZ answers an
117    // `AcquireWrite` there is exactly one, carrying one descriptor.
118    let mut fds = Vec::new();
119    let mut offset = 0usize;
120    while offset + std::mem::size_of::<CmsgHdr>() <= header.controllen {
121        // SAFETY: `offset` is within the control buffer, checked above.
122        let cmsg = unsafe { &*(control.as_ptr().add(offset) as *const CmsgHdr) };
123        if cmsg.len < std::mem::size_of::<CmsgHdr>() || offset + cmsg.len > header.controllen {
124            break; // Malformed; stop rather than read past the buffer.
125        }
126        if cmsg.level == SOL_SOCKET && cmsg.kind == SCM_RIGHTS {
127            let payload = cmsg.len - std::mem::size_of::<CmsgHdr>();
128            let count = payload / std::mem::size_of::<RawFd>();
129            let data = unsafe {
130                control
131                    .as_ptr()
132                    .add(offset + std::mem::size_of::<CmsgHdr>())
133            };
134            for i in 0..count {
135                // SAFETY: `count` was derived from the length the kernel set.
136                let raw = unsafe { std::ptr::read_unaligned(data.cast::<RawFd>().add(i)) };
137                fds.push(raw);
138            }
139        }
140        offset += align(cmsg.len);
141    }
142
143    Ok(Some(Received {
144        bytes: n as usize,
145        fds,
146    }))
147}
148
149/// Close a descriptor this module handed out.
150///
151/// # Safety
152/// `fd` must be one received here and not already closed.
153pub unsafe fn close_raw(fd: RawFd) {
154    unsafe { close(fd) };
155}
156
157/// Descriptors received but not yet claimed by a message.
158///
159/// Kept in arrival order. Anything still here when the connection closes is
160/// closed with it: a descriptor nobody claimed is a leaked open file, and the
161/// process has no other handle on it.
162#[derive(Default)]
163pub struct Pending {
164    queue: std::collections::VecDeque<RawFd>,
165}
166
167impl Pending {
168    pub fn push(&mut self, fds: impl IntoIterator<Item = RawFd>) {
169        self.queue.extend(fds);
170    }
171
172    /// Take `count` descriptors for a message that declared that many.
173    ///
174    /// Fewer than asked for means the peer's header disagreed with what it
175    /// sent, which is a protocol error on their side; whatever is available is
176    /// returned rather than blocking for something that is not coming.
177    pub fn take(&mut self, count: usize) -> Vec<RawFd> {
178        (0..count).filter_map(|_| self.queue.pop_front()).collect()
179    }
180
181    pub fn len(&self) -> usize {
182        self.queue.len()
183    }
184
185    pub fn is_empty(&self) -> bool {
186        self.queue.is_empty()
187    }
188}
189
190impl Drop for Pending {
191    fn drop(&mut self) {
192        for fd in self.queue.drain(..) {
193            // Nobody claimed it, and nothing else knows it exists.
194            unsafe { close(fd) };
195        }
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn control_messages_are_word_aligned() {
205        let word = std::mem::size_of::<usize>();
206        assert_eq!(align(1), word);
207        assert_eq!(align(word), word);
208        assert_eq!(align(word + 1), word * 2);
209    }
210
211    /// The layouts are the kernel's, not ours. Getting one wrong means reading
212    /// a descriptor out of the wrong offset — which yields a plausible-looking
213    /// small integer rather than an error.
214    #[test]
215    fn the_headers_match_the_kernel_abi() {
216        // `cmsghdr` is a length, then two ints.
217        assert_eq!(
218            std::mem::size_of::<CmsgHdr>(),
219            std::mem::size_of::<usize>() + 2 * std::mem::size_of::<i32>(),
220        );
221        assert_eq!(
222            std::mem::align_of::<CmsgHdr>(),
223            std::mem::align_of::<usize>()
224        );
225        // `iovec` is a pointer and a length.
226        assert_eq!(
227            std::mem::size_of::<IoVec>(),
228            std::mem::size_of::<*mut c_void>() + std::mem::size_of::<usize>(),
229        );
230    }
231
232    /// Dropping these is safe because the queue is empty, which both tests
233    /// here assert before they end.
234    ///
235    /// It matters: the descriptors are made up — 10, 11, 12 are somebody
236    /// else's open files in this process — so a `Drop` that reached one would
237    /// close it. An empty queue closes nothing.
238    ///
239    /// They used to end by forgetting the queue instead, which avoided the
240    /// same hazard by never running `Drop` at all, and leaked its buffer —
241    /// which is what `./scripts/check.sh miri` had been reporting.
242    ///
243    /// Nothing else catches this, so the assertions are the check. Miri is not
244    /// a second opinion here: it shims `close` rather than refusing it, so a
245    /// queue left full passes there and only bites on a real Linux run.
246    #[test]
247    fn a_message_takes_only_what_it_declared() {
248        let mut pending = Pending::default();
249        pending.push([10, 11, 12]);
250        assert_eq!(pending.len(), 3);
251
252        assert_eq!(pending.take(0), Vec::<RawFd>::new(), "a message with none");
253        assert_eq!(pending.take(1), vec![10], "takes from the front");
254        assert_eq!(pending.take(2), vec![11, 12]);
255        assert!(pending.is_empty());
256
257        // Asking for more than arrived yields what there is rather than
258        // hanging for something the peer is not going to send.
259        assert_eq!(pending.take(4), Vec::<RawFd>::new());
260        assert!(
261            pending.is_empty(),
262            "or dropping it would close 10, 11 and 12"
263        );
264    }
265
266    /// Order is the whole basis for matching descriptors to messages.
267    #[test]
268    fn descriptors_come_out_in_the_order_they_arrived() {
269        let mut pending = Pending::default();
270        pending.push([1, 2]);
271        pending.push([3]);
272        assert_eq!(pending.take(3), vec![1, 2, 3]);
273        assert!(pending.is_empty(), "or dropping it would close 1, 2 and 3");
274    }
275}