1use 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 fn getuid() -> u32;
43}
44
45#[derive(Debug, Clone)]
47pub enum Error {
48 Io(String),
50 Auth(String),
52 Codec(CodecError),
54 Call { name: String, message: String },
56 Timeout,
58 Disconnected,
60 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
91pub type Result<T> = std::result::Result<T, Error>;
93
94pub 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
110pub 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 objects: Mutex<Vec<(String, Arc<dyn ObjectHandler>)>>,
122 unique_name: Mutex<String>,
123 stopped: AtomicBool,
124 received_fds: Mutex<HashMap<u32, Vec<std::os::fd::RawFd>>>,
130}
131
132impl Shared {
133 fn next_serial(&self) -> u32 {
134 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 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
164pub struct Connection {
166 shared: Arc<Shared>,
167}
168
169impl Connection {
170 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 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 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 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 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 #[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 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 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 pub fn unique_name(&self) -> String {
300 self.shared.unique_name.lock().unwrap().clone()
301 }
302
303 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 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 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 pub fn send(&self, message: Message) -> Result<()> {
364 let serial = self.shared.next_serial();
365 self.shared.send(&message, serial)
366 }
367
368 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 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 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 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 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 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 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 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 let claimed = pending.take(message.unix_fds as usize);
481 attach(&shared, &mut message, claimed);
482 dispatch(&shared, message)
483 }
484 Err(_) => continue,
487 }
488 }
489
490 match super::fds::recv_with_fds(fd, &mut chunk) {
491 Ok(None) => continue, 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 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
521fn 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 for fd in fds {
537 unsafe { super::fds::close_raw(fd) };
538 }
539 }
540}
541
542fn 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 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 drop(spawned);
618 }
619 }
620}