Skip to main content

webbluetooth_linux/dbus/
connection.rs

1//! A D-Bus connection: authenticate, dispatch, serve.
2//!
3//! # Authentication
4//!
5//! Before any message, the client sends a single NUL byte — a relic of the
6//! credential-passing handshake — then a line-based SASL exchange:
7//!
8//! ```text
9//!   AUTH EXTERNAL <uid, in ASCII, hex-encoded>
10//!   OK <server guid>
11//!   BEGIN
12//! ```
13//!
14//! `EXTERNAL` means "the kernel already told you who I am", which is true of a
15//! Unix socket. `ANONYMOUS` is tried as a fallback for buses configured to
16//! allow it, which is how some test harnesses are set up.
17//!
18//! # Dispatch
19//!
20//! One reader thread owns the read half and routes by message type: replies to
21//! the caller waiting on that serial, signals to match handlers, and inbound
22//! method calls to registered objects — the last being what the peripheral role
23//! needs, since BlueZ calls *back* into the application to read a
24//! characteristic.
25//!
26//! Calls are callback-based rather than blocking, so the async layer above can
27//! wrap them without a thread per request. [`Connection::call_blocking`] is
28//! provided for setup paths and tests.
29
30use super::codec::CodecError;
31use super::message::{Message, MessageType};
32use super::value::Value;
33use std::collections::HashMap;
34use std::io::{ErrorKind, Read, Write};
35use std::os::unix::net::UnixStream;
36use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
37use std::sync::{Arc, Condvar, Mutex};
38use std::time::Duration;
39
40unsafe extern "C" {
41    /// From libc, which is linked into every Unix process anyway — no crate.
42    fn getuid() -> u32;
43}
44
45/// Something went wrong on the bus.
46#[derive(Debug, Clone)]
47pub enum Error {
48    /// The socket could not be reached, or died.
49    Io(String),
50    /// SASL did not complete.
51    Auth(String),
52    /// A malformed message.
53    Codec(CodecError),
54    /// The peer replied with an error.
55    Call { name: String, message: String },
56    /// No reply within the deadline.
57    Timeout,
58    /// The connection is shutting down.
59    Disconnected,
60    /// `DBUS_SYSTEM_BUS_ADDRESS` was unparseable, or names no socket.
61    BadAddress(String),
62}
63
64impl std::fmt::Display for Error {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        match self {
67            Self::Io(m) => write!(f, "D-Bus I/O error: {m}"),
68            Self::Auth(m) => write!(f, "D-Bus authentication failed: {m}"),
69            Self::Codec(e) => write!(f, "D-Bus protocol error: {e}"),
70            Self::Call { name, message } => write!(f, "{name}: {message}"),
71            Self::Timeout => f.write_str("D-Bus call timed out"),
72            Self::Disconnected => f.write_str("D-Bus connection closed"),
73            Self::BadAddress(a) => write!(f, "unusable D-Bus address: {a}"),
74        }
75    }
76}
77
78impl std::error::Error for Error {}
79
80impl From<std::io::Error> for Error {
81    fn from(e: std::io::Error) -> Self {
82        Self::Io(e.to_string())
83    }
84}
85impl From<CodecError> for Error {
86    fn from(e: CodecError) -> Self {
87        Self::Codec(e)
88    }
89}
90
91/// A D-Bus result: this module's [`Error`], not the crate's.
92pub type Result<T> = std::result::Result<T, Error>;
93
94/// Handles inbound method calls on an exported object.
95///
96/// Returning `Err((name, text))` sends a D-Bus error reply.
97pub trait ObjectHandler: Send + Sync {
98    fn handle(&self, call: &Message) -> std::result::Result<Vec<Value>, (String, String)>;
99}
100
101impl<F> ObjectHandler for F
102where
103    F: Fn(&Message) -> std::result::Result<Vec<Value>, (String, String)> + Send + Sync,
104{
105    fn handle(&self, call: &Message) -> std::result::Result<Vec<Value>, (String, String)> {
106        self(call)
107    }
108}
109
110/// Called for every signal that arrives.
111pub type SignalHandler = Arc<dyn Fn(&Message) + Send + Sync>;
112
113type ReplyHandler = Box<dyn FnOnce(Result<Message>) + Send>;
114
115struct Shared {
116    write: Mutex<UnixStream>,
117    serial: AtomicU32,
118    pending: Mutex<HashMap<u32, ReplyHandler>>,
119    signals: Mutex<Vec<SignalHandler>>,
120    /// Exported objects, matched by exact path then by `path/` prefix.
121    objects: Mutex<Vec<(String, Arc<dyn ObjectHandler>)>>,
122    unique_name: Mutex<String>,
123    stopped: AtomicBool,
124    /// Descriptors that arrived with a reply, by the serial it answers.
125    ///
126    /// Claimed by [`Connection::take_fds`] after the call returns. Anything
127    /// nobody claims is closed when the connection is dropped — an unclaimed
128    /// descriptor is an open file the process cannot name.
129    received_fds: Mutex<HashMap<u32, Vec<std::os::fd::RawFd>>>,
130}
131
132impl Shared {
133    fn next_serial(&self) -> u32 {
134        // Serial 0 is reserved.
135        let mut s = self.serial.fetch_add(1, Ordering::Relaxed);
136        if s == 0 {
137            s = self.serial.fetch_add(1, Ordering::Relaxed);
138        }
139        s
140    }
141
142    fn send(&self, message: &Message, serial: u32) -> Result<()> {
143        if self.stopped.load(Ordering::Acquire) {
144            return Err(Error::Disconnected);
145        }
146        let bytes = message.serialize(serial);
147        let mut w = self.write.lock().map_err(|_| Error::Disconnected)?;
148        w.write_all(&bytes)?;
149        w.flush()?;
150        Ok(())
151    }
152
153    /// Fail every outstanding call — called when the reader thread exits, so a
154    /// dropped bus never leaves a caller waiting forever.
155    fn shutdown(&self) {
156        self.stopped.store(true, Ordering::Release);
157        let pending = std::mem::take(&mut *self.pending.lock().unwrap());
158        for (_, handler) in pending {
159            handler(Err(Error::Disconnected));
160        }
161    }
162}
163
164/// A connection to a message bus.
165pub struct Connection {
166    shared: Arc<Shared>,
167}
168
169impl Connection {
170    /// Connect to the system bus, where BlueZ lives.
171    ///
172    /// `WEBBLUETOOTH_DBUS_ADDRESS` overrides the address, which is how the test
173    /// harness points at a private bus carrying a mocked `org.bluez` instead of
174    /// the real one.
175    pub fn system() -> Result<Self> {
176        if let Ok(address) = std::env::var("WEBBLUETOOTH_DBUS_ADDRESS") {
177            return Self::connect(&address);
178        }
179        let address = std::env::var("DBUS_SYSTEM_BUS_ADDRESS")
180            .unwrap_or_else(|_| "unix:path=/var/run/dbus/system_bus_socket".into());
181        Self::connect(&address)
182    }
183
184    /// Connect to the session bus.
185    pub fn session() -> Result<Self> {
186        let address = std::env::var("DBUS_SESSION_BUS_ADDRESS")
187            .map_err(|_| Error::BadAddress("DBUS_SESSION_BUS_ADDRESS is unset".into()))?;
188        Self::connect(&address)
189    }
190
191    /// Connect to a bus at a D-Bus address.
192    ///
193    /// Only `unix:path=` and `unix:abstract=` transports are supported; TCP is
194    /// not, because BlueZ is never on one.
195    pub fn connect(address: &str) -> Result<Self> {
196        let socket = Self::open(address)?;
197        Self::authenticate(&socket)?;
198
199        let write = socket.try_clone()?;
200        let shared = Arc::new(Shared {
201            write: Mutex::new(write),
202            serial: AtomicU32::new(1),
203            pending: Mutex::new(HashMap::new()),
204            signals: Mutex::new(Vec::new()),
205            objects: Mutex::new(Vec::new()),
206            unique_name: Mutex::new(String::new()),
207            stopped: AtomicBool::new(false),
208            received_fds: Mutex::new(HashMap::new()),
209        });
210
211        spawn_reader(socket, shared.clone());
212
213        let connection = Self { shared };
214        // `Hello` is mandatory: the bus assigns a unique name and will reject
215        // everything else until it has been called.
216        let reply = connection.call_blocking(
217            Message::call(
218                "org.freedesktop.DBus",
219                "/org/freedesktop/DBus",
220                "org.freedesktop.DBus",
221                "Hello",
222            ),
223            Duration::from_secs(10),
224        )?;
225        if let Some(name) = reply.arg(0).and_then(Value::as_str) {
226            *connection.shared.unique_name.lock().unwrap() = name.to_owned();
227        }
228        Ok(connection)
229    }
230
231    fn open(address: &str) -> Result<UnixStream> {
232        // An address is a semicolon-separated list of transports to try.
233        for candidate in address.split(';') {
234            let Some(rest) = candidate.trim().strip_prefix("unix:") else {
235                continue;
236            };
237            for part in rest.split(',') {
238                if let Some(path) = part.strip_prefix("path=") {
239                    if let Ok(s) = UnixStream::connect(path) {
240                        return Ok(s);
241                    }
242                }
243                if let Some(name) = part.strip_prefix("abstract=") {
244                    // Linux abstract sockets are a NUL followed by the name.
245                    #[cfg(target_os = "linux")]
246                    {
247                        use std::os::linux::net::SocketAddrExt;
248                        let addr = std::os::unix::net::SocketAddr::from_abstract_name(name)?;
249                        if let Ok(s) = UnixStream::connect_addr(&addr) {
250                            return Ok(s);
251                        }
252                    }
253                    #[cfg(not(target_os = "linux"))]
254                    let _ = name;
255                }
256            }
257        }
258        Err(Error::BadAddress(address.to_owned()))
259    }
260
261    /// The SASL handshake.
262    fn authenticate(socket: &UnixStream) -> Result<()> {
263        let mut w = socket.try_clone()?;
264        let mut r = std::io::BufReader::new(socket.try_clone()?);
265
266        // The leading NUL must be its own write before any SASL line.
267        w.write_all(&[0])?;
268        w.flush()?;
269
270        let uid = unsafe { getuid() };
271        let hex_uid: String = uid
272            .to_string()
273            .bytes()
274            .map(|b| format!("{b:02x}"))
275            .collect();
276
277        for attempt in [
278            format!("AUTH EXTERNAL {hex_uid}\r\n"),
279            "AUTH ANONYMOUS\r\n".to_string(),
280        ] {
281            w.write_all(attempt.as_bytes())?;
282            w.flush()?;
283            let line = read_line(&mut r)?;
284            if line.starts_with("OK") {
285                w.write_all(b"BEGIN\r\n")?;
286                w.flush()?;
287                return Ok(());
288            }
289            if !line.starts_with("REJECTED") {
290                return Err(Error::Auth(line));
291            }
292        }
293        Err(Error::Auth(
294            "no supported authentication mechanism was accepted".into(),
295        ))
296    }
297
298    /// This connection's unique bus name, e.g. `:1.42`.
299    pub fn unique_name(&self) -> String {
300        self.shared.unique_name.lock().unwrap().clone()
301    }
302
303    /// Send a method call; `on_reply` runs on the reader thread when the answer
304    /// arrives. This is the primitive the async layer wraps.
305    pub fn call_async(&self, message: Message, on_reply: ReplyHandler) {
306        let serial = self.shared.next_serial();
307        self.shared.pending.lock().unwrap().insert(serial, on_reply);
308        if let Err(e) = self.shared.send(&message, serial) {
309            if let Some(handler) = self.shared.pending.lock().unwrap().remove(&serial) {
310                handler(Err(e));
311            }
312        }
313    }
314
315    /// Send a method call and wait for the reply, claiming any descriptors.
316    ///
317    /// For methods like `AcquireWrite` whose answer is a file descriptor: the
318    /// body carries only an index, and the descriptor itself arrived beside
319    /// the message. The caller owns what comes back and must close it.
320    pub fn call_blocking_with_fds(
321        &self,
322        message: Message,
323        timeout: Duration,
324    ) -> Result<(Message, Vec<std::os::fd::RawFd>)> {
325        let reply = self.call_blocking(message, timeout)?;
326        let fds = reply
327            .reply_serial
328            .map(|s| self.take_fds(s))
329            .unwrap_or_default();
330        Ok((reply, fds))
331    }
332
333    /// Send a method call and wait for the reply.
334    pub fn call_blocking(&self, message: Message, timeout: Duration) -> Result<Message> {
335        let slot: Arc<(Mutex<Option<Result<Message>>>, Condvar)> =
336            Arc::new((Mutex::new(None), Condvar::new()));
337        let writer = slot.clone();
338        self.call_async(
339            message,
340            Box::new(move |reply| {
341                *writer.0.lock().unwrap() = Some(reply);
342                writer.1.notify_all();
343            }),
344        );
345
346        let (lock, cv) = &*slot;
347        let mut guard = lock.lock().map_err(|_| Error::Disconnected)?;
348        let deadline = std::time::Instant::now() + timeout;
349        while guard.is_none() {
350            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
351            if remaining.is_zero() {
352                return Err(Error::Timeout);
353            }
354            let (g, _) = cv
355                .wait_timeout(guard, remaining)
356                .map_err(|_| Error::Disconnected)?;
357            guard = g;
358        }
359        guard.take().unwrap_or(Err(Error::Disconnected))
360    }
361
362    /// Send a signal or a reply, expecting nothing back.
363    pub fn send(&self, message: Message) -> Result<()> {
364        let serial = self.shared.next_serial();
365        self.shared.send(&message, serial)
366    }
367
368    /// Subscribe to signals. The rule is a D-Bus match expression, e.g.
369    /// `type='signal',interface='org.freedesktop.DBus.Properties'`.
370    ///
371    /// The handler sees *every* signal, because the bus may deliver more than
372    /// the rule asks for; filter inside it.
373    pub fn add_match(&self, rule: &str, handler: SignalHandler) -> Result<()> {
374        self.shared.signals.lock().unwrap().push(handler);
375        self.call_blocking(
376            Message::call(
377                "org.freedesktop.DBus",
378                "/org/freedesktop/DBus",
379                "org.freedesktop.DBus",
380                "AddMatch",
381            )
382            .with_body(vec![Value::Str(rule.into())]),
383            Duration::from_secs(10),
384        )?;
385        Ok(())
386    }
387
388    /// Export an object. `path` matches itself and everything beneath it, which
389    /// is how one handler can serve a whole GATT application tree.
390    pub fn export(&self, path: &str, handler: Arc<dyn ObjectHandler>) {
391        self.shared
392            .objects
393            .lock()
394            .unwrap()
395            .push((path.to_owned(), handler));
396    }
397
398    /// Claim a well-known bus name.
399    pub fn request_name(&self, name: &str) -> Result<()> {
400        self.call_blocking(
401            Message::call(
402                "org.freedesktop.DBus",
403                "/org/freedesktop/DBus",
404                "org.freedesktop.DBus",
405                "RequestName",
406            )
407            .with_body(vec![Value::Str(name.into()), Value::Uint32(0)]),
408            Duration::from_secs(10),
409        )?;
410        Ok(())
411    }
412
413    /// Whether the reader thread is still running.
414    pub fn is_connected(&self) -> bool {
415        !self.shared.stopped.load(Ordering::Acquire)
416    }
417}
418
419impl Drop for Connection {
420    fn drop(&mut self) {
421        self.shared.shutdown();
422        // Closing the socket wakes the reader out of its blocking read.
423        if let Ok(w) = self.shared.write.lock() {
424            let _ = w.shutdown(std::net::Shutdown::Both);
425        }
426    }
427}
428
429fn read_line(r: &mut impl Read) -> Result<String> {
430    // SASL is line-based and pre-dates the binary protocol, so read one byte at
431    // a time rather than buffering past the BEGIN.
432    let mut line = Vec::new();
433    let mut byte = [0u8; 1];
434    loop {
435        let n = r.read(&mut byte)?;
436        if n == 0 {
437            return Err(Error::Auth(
438                "connection closed during authentication".into(),
439            ));
440        }
441        if byte[0] == b'\n' {
442            break;
443        }
444        if byte[0] != b'\r' {
445            line.push(byte[0]);
446        }
447    }
448    Ok(String::from_utf8_lossy(&line).into_owned())
449}
450
451fn spawn_reader(socket: UnixStream, shared: Arc<Shared>) {
452    std::thread::Builder::new()
453        .name("webbluetooth-dbus".into())
454        .spawn(move || {
455            let reader = socket;
456            // Read with `recvmsg` from the first byte, not only once something
457            // expects a descriptor: a plain `read` does not ignore ancillary
458            // data, it makes the kernel discard it and close the descriptors
459            // it carried. By the time anything noticed, they would be gone.
460            let fd = std::os::fd::AsRawFd::as_raw_fd(&reader);
461            let mut pending = super::fds::Pending::default();
462            let mut buf: Vec<u8> = Vec::with_capacity(8192);
463            let mut chunk = [0u8; 4096];
464
465            loop {
466                // Drain every complete message already buffered before reading.
467                loop {
468                    let Some(len) = Message::framed_length(&buf) else {
469                        break;
470                    };
471                    if buf.len() < len {
472                        break;
473                    }
474                    let frame: Vec<u8> = buf.drain(..len).collect();
475                    match Message::parse(&frame) {
476                        Ok(mut message) => {
477                            // Each message claims exactly what its header
478                            // declared, so one that carries none cannot take
479                            // a descriptor meant for the message behind it.
480                            let claimed = pending.take(message.unix_fds as usize);
481                            attach(&shared, &mut message, claimed);
482                            dispatch(&shared, message)
483                        }
484                        // A message we cannot parse is skipped; the stream stays
485                        // framed because the length came from the fixed header.
486                        Err(_) => continue,
487                    }
488                }
489
490                match super::fds::recv_with_fds(fd, &mut chunk) {
491                    Ok(None) => continue, // Interrupted; try again.
492                    Ok(Some(received)) if received.bytes == 0 && received.fds.is_empty() => break,
493                    Ok(Some(received)) => {
494                        pending.push(received.fds);
495                        buf.extend_from_slice(&chunk[..received.bytes]);
496                    }
497                    Err(e) if e.kind() == ErrorKind::Interrupted => continue,
498                    Err(_) => break,
499                }
500            }
501            shared.shutdown();
502        })
503        .expect("could not start the D-Bus reader thread");
504}
505
506impl Connection {
507    /// Take the descriptors that came back with the reply to `serial`.
508    ///
509    /// Empty unless the method actually returned one. The caller owns them and
510    /// must close them; nothing else will.
511    pub fn take_fds(&self, serial: u32) -> Vec<std::os::fd::RawFd> {
512        self.shared
513            .received_fds
514            .lock()
515            .unwrap()
516            .remove(&serial)
517            .unwrap_or_default()
518    }
519}
520
521/// Record the descriptors that arrived with a reply.
522///
523/// They are keyed by the serial of the call they answer, because that is what
524/// the waiting side knows; a `h` in the body is an index into this list.
525fn attach(shared: &Arc<Shared>, message: &mut Message, fds: Vec<std::os::fd::RawFd>) {
526    if fds.is_empty() {
527        return;
528    }
529    if message.message_type == MessageType::MethodCall {
530        message.received_fds = fds;
531    } else if let Some(serial) = message.reply_serial {
532        shared.received_fds.lock().unwrap().insert(serial, fds);
533    } else {
534        // Nothing to hand them to. Closing beats leaking an open file that
535        // nothing in the process can name.
536        for fd in fds {
537            unsafe { super::fds::close_raw(fd) };
538        }
539    }
540}
541
542/// Run the handler for one inbound method call and send its reply.
543fn answer(shared: &Arc<Shared>, message: Message) {
544    let path = message.path.clone().unwrap_or_default();
545    let handler = {
546        let objects = shared.objects.lock().unwrap();
547        objects
548            .iter()
549            .find(|(p, _)| *p == path || path.starts_with(&format!("{p}/")))
550            .map(|(_, h)| h.clone())
551    };
552
553    let reply = match handler {
554        Some(h) => match h.handle(&message) {
555            Ok(body) => Message::reply_to(&message).with_body(body),
556            Err((name, text)) => Message::error_to(&message, &name, &text),
557        },
558        None => Message::error_to(
559            &message,
560            "org.freedesktop.DBus.Error.UnknownObject",
561            &format!("no object at {path}"),
562        ),
563    };
564    if message.flags & super::message::FLAG_NO_REPLY_EXPECTED == 0 {
565        let serial = shared.next_serial();
566        let _ = shared.send(&reply, serial);
567    }
568}
569
570fn dispatch(shared: &Arc<Shared>, message: Message) {
571    match message.message_type {
572        MessageType::MethodReturn | MessageType::Error => {
573            let Some(serial) = message.reply_serial else {
574                return;
575            };
576            let handler = shared.pending.lock().unwrap().remove(&serial);
577            if let Some(handler) = handler {
578                if message.message_type == MessageType::Error {
579                    handler(Err(Error::Call {
580                        name: message.error_name.clone().unwrap_or_default(),
581                        message: message.error_text().unwrap_or_default(),
582                    }));
583                } else {
584                    handler(Ok(message));
585                }
586            }
587        }
588
589        MessageType::Signal => {
590            let handlers = shared.signals.lock().unwrap().clone();
591            for h in handlers {
592                h(&message);
593            }
594        }
595
596        // Answered on its own thread, never on the reader's.
597        //
598        // A handler may take arbitrarily long — a GATT read is answered by
599        // application code, not from a table — and this is the only thread
600        // reading the socket. Running handlers here would stall every inbound
601        // message behind them, including the replies to our own outstanding
602        // calls, which deadlocks the obvious case: `RegisterApplication` does
603        // not return until BlueZ has walked our object tree, so we have to be
604        // able to answer `GetManagedObjects` while blocked waiting for it.
605        //
606        // One thread per call is more than a busy bus would want, but method
607        // calls arrive at the rate a GATT client generates them, and the peer
608        // here is `bluetoothd`.
609        MessageType::MethodCall => {
610            let shared = shared.clone();
611            let spawned = std::thread::Builder::new()
612                .name("webbluetooth-dbus-call".into())
613                .spawn(move || answer(&shared, message));
614            // If a thread cannot be spawned the call simply goes unanswered,
615            // which the caller sees as a timeout — the same as a handler that
616            // never returns, and better than killing the connection.
617            drop(spawned);
618        }
619    }
620}