Skip to main content

crabshell_services/bluetooth/
agent.rs

1//! The shell's own Bluetooth pairing agent: BlueZ's `org.bluez.Agent1`,
2//! so a device that asks for a PIN, a passkey or a confirmation can pair
3//! from the shell. zbus has no object server here, so BlueZ's calls are
4//! answered by hand on the main thread, as the polkit agent's are.
5
6#[cfg(test)]
7mod tests;
8
9use std::cell::{Cell, RefCell};
10use std::future::poll_fn;
11use std::pin::Pin;
12use std::rc::Rc;
13use std::sync::Once;
14
15use crabshell_reactive::{ReadSignal, Signal};
16use crabshell_ui::Cx;
17use zbus::export::futures_core::Stream;
18use zbus::message::{Flags, Type as Kind};
19use zbus::{Connection, Message, MessageStream, ObjectPath};
20
21use crate::Shared;
22use crate::dbus::{CALL_TIMEOUT, bus_call, owner_changed, owner_rule, set_changed};
23
24const BLUEZ: &str = "org.bluez";
25const MANAGER_PATH: &str = "/org/bluez";
26const MANAGER: &str = "org.bluez.AgentManager1";
27const AGENT: &str = "org.bluez.Agent1";
28/// Where the agent answers BlueZ: any path of the shell's own.
29pub(crate) const AGENT_PATH: &str = "/org/crabshell/BluetoothAgent";
30/// What a shell can do: show a code and take one typed.
31const CAPABILITY: &str = "KeyboardDisplay";
32
33const REJECTED: &str = "org.bluez.Error.Rejected";
34const CANCELED: &str = "org.bluez.Error.Canceled";
35const ACCESS_DENIED: &str = "org.freedesktop.DBus.Error.AccessDenied";
36const INVALID_ARGS: &str = "org.freedesktop.DBus.Error.InvalidArgs";
37const UNKNOWN_METHOD: &str = "org.freedesktop.DBus.Error.UnknownMethod";
38
39/// The longest PIN code, as Bluetooth allows.
40const MAX_PIN: usize = 16;
41/// The longest service UUID kept.
42const MAX_UUID: usize = 64;
43/// The largest passkey: six digits.
44const MAX_PASSKEY: u32 = 999_999;
45
46/// What BlueZ asks the shell during a pairing, from
47/// [`BluetoothAgent::request`].
48#[derive(Clone, Debug, PartialEq)]
49pub struct PairingRequest {
50  /// Which request this is, so two alike still differ.
51  id: u64,
52  /// The device's path, as in [`BluetoothDevice::path`], for its name.
53  ///
54  /// [`BluetoothDevice::path`]: crate::BluetoothDevice::path
55  pub device: String,
56  /// What BlueZ wants.
57  pub kind: PairingKind,
58}
59
60/// What a [`PairingRequest`] wants, and the answer it takes.
61#[derive(Clone, Debug, PartialEq)]
62pub enum PairingKind {
63  /// The device's PIN code, for [`BluetoothAgent::answer_pin_code`].
64  PinCode,
65  /// The passkey the device shows, for
66  /// [`BluetoothAgent::answer_passkey`].
67  Passkey,
68  /// `pin_code` to show, for the user to type on the device. It shows
69  /// until BlueZ is done with it; [`accept`](BluetoothAgent::accept) or
70  /// [`reject`](BluetoothAgent::reject) only hides it.
71  DisplayPinCode {
72    /// At most 16 characters.
73    pin_code: String,
74  },
75  /// `passkey` to show, as [`DisplayPinCode`](Self::DisplayPinCode)
76  /// shows its code. `entered` is how many digits the device has typed,
77  /// and goes up while it shows.
78  DisplayPasskey {
79    /// Six digits, with leading zeros.
80    passkey: u32,
81    /// How many digits were typed on the device.
82    entered: u16,
83  },
84  /// Whether `passkey` is the one the device shows, for
85  /// [`accept`](BluetoothAgent::accept) or
86  /// [`reject`](BluetoothAgent::reject).
87  Confirmation {
88    /// Six digits, with leading zeros.
89    passkey: u32,
90  },
91  /// Whether the device may pair, as one that asks for nothing does.
92  Authorization,
93  /// Whether the device may use the service `uuid`, such as audio.
94  Service {
95    /// The service's UUID, as BlueZ names it.
96    uuid: String,
97  },
98}
99
100/// The shell's Bluetooth pairing agent, from `cx.bluetooth_agent()`. A
101/// clone is cheap and shares the one agent.
102#[derive(Clone)]
103pub struct BluetoothAgent {
104  /// `None` when the shell provided no services.
105  service: Option<Rc<Service>>,
106  request: ReadSignal<Option<PairingRequest>>,
107}
108
109impl BluetoothAgent {
110  /// What BlueZ asks now, or `None`. One shows at a time: a new request
111  /// takes the place of one unanswered, which BlueZ is told was
112  /// cancelled. It goes once answered, or when BlueZ cancels it.
113  pub fn request(&self) -> ReadSignal<Option<PairingRequest>> {
114    self.request
115  }
116
117  /// Answers [`PairingKind::PinCode`] with `pin_code`, 1 to 16 letters
118  /// and digits. Any other, or at any other time, it is dropped and
119  /// logged.
120  pub fn answer_pin_code(&self, pin_code: &str) {
121    let fits = (1..=MAX_PIN).contains(&pin_code.len())
122      && pin_code.bytes().all(|byte| byte.is_ascii_alphanumeric());
123    if !fits {
124      return tracing::warn!("a Bluetooth PIN code must be 1 to 16 letters and digits; dropped");
125    }
126    let pin = matches!(self.kind(), Some(PairingKind::PinCode));
127    self.answer(pin, "a PIN code", Ok(&pin_code));
128  }
129
130  /// Answers [`PairingKind::Passkey`] with `passkey`, at most 999999. Any
131  /// other, or at any other time, it is dropped and logged.
132  pub fn answer_passkey(&self, passkey: u32) {
133    if passkey > MAX_PASSKEY {
134      return tracing::warn!(passkey, "a Bluetooth passkey has six digits; dropped");
135    }
136    let asked = matches!(self.kind(), Some(PairingKind::Passkey));
137    self.answer(asked, "a passkey", Ok(&passkey));
138  }
139
140  /// Says yes to a confirmation, an authorization or a service, and
141  /// hides a code shown. A PIN code or passkey needs its answer instead.
142  pub fn accept(&self) {
143    let answerable = self
144      .kind()
145      .is_some_and(|kind| !matches!(kind, PairingKind::PinCode | PairingKind::Passkey));
146    self.answer(answerable, "a yes", Ok(&()));
147  }
148
149  /// Says no to a question, so the pairing fails. A code shown is only
150  /// hidden: BlueZ took its answer already, and ends the pairing itself.
151  pub fn reject(&self) {
152    let shown = self.kind().is_some();
153    self.answer::<()>(shown, "a no", Err((REJECTED, "the user said no")));
154  }
155
156  /// Asks BlueZ to make the shell its default agent, now and whenever
157  /// BlueZ starts again, so the shell also answers pairings that other
158  /// programs, such as `bluetoothctl`, or the devices themselves start.
159  /// Without it, the shell answers only the pairings
160  /// [`Bluetooth::pair`] starts, since BlueZ asks the agent of whoever
161  /// called `Pair`.
162  ///
163  /// [`Bluetooth::pair`]: crate::Bluetooth::pair
164  pub fn make_default(&self) {
165    if let Some(service) = &self.service {
166      service.make_default();
167    }
168  }
169
170  fn kind(&self) -> Option<PairingKind> {
171    let service = self.service.as_ref()?;
172    let state = service.state.borrow();
173    let current = state.as_ref()?.current.as_ref()?;
174    Some(current.shown.kind.clone())
175  }
176
177  /// Answers the request with `answer` if `fits`, else logs that `what`
178  /// was dropped.
179  fn answer<B>(&self, fits: bool, what: &str, answer: Result<&B, (&str, &str)>)
180  where
181    B: serde::Serialize + zbus::DynamicType,
182  {
183    let Some(service) = &self.service else {
184      return;
185    };
186    if !fits {
187      return tracing::warn!(what, "no Bluetooth request takes it; dropped");
188    }
189    let taken = service
190      .state
191      .borrow_mut()
192      .as_mut()
193      .and_then(|state| state.current.take());
194    service.publish();
195    if let Some(call) = taken.and_then(|pending| pending.call) {
196      service.reply(&call, answer);
197    }
198  }
199}
200
201/// `cx.bluetooth_agent()`.
202pub(crate) fn bluetooth_agent(cx: &Cx) -> BluetoothAgent {
203  let Some(service) = cx.service::<Service>() else {
204    static LOGGED: Once = Once::new();
205    LOGGED.call_once(|| {
206      tracing::warn!("cx.bluetooth_agent() needs the services the shell provides; nothing arrives");
207    });
208    return BluetoothAgent {
209      service: None,
210      request: cx.signal(None).read_only(),
211    };
212  };
213  let request = service.start();
214  BluetoothAgent {
215    service: Some(service),
216    request,
217  }
218}
219
220/// The pairing agent of one shell, registered on first use.
221pub(crate) struct Service {
222  shared: Rc<Shared>,
223  state: RefCell<Option<State>>,
224  /// The number the next request gets.
225  next: Cell<u64>,
226}
227
228struct State {
229  request: Signal<Option<PairingRequest>>,
230  /// The system bus, once connected.
231  connection: Option<Connection>,
232  /// BlueZ's unique name, once it took the registration: the only caller
233  /// the agent answers.
234  bluez: Option<String>,
235  /// Whether the config asked to be BlueZ's default agent.
236  default: bool,
237  current: Option<Pending>,
238}
239
240/// The request shown.
241struct Pending {
242  shown: PairingRequest,
243  /// BlueZ's call, while it waits for the answer. A code to show is
244  /// answered at once, so it has none.
245  call: Option<Message>,
246}
247
248/// Rejects the request and unregisters the agent when the root goes.
249struct StopOnDrop(Rc<Service>);
250
251impl Drop for StopOnDrop {
252  fn drop(&mut self) {
253    self.0.stop();
254  }
255}
256
257impl Service {
258  pub(crate) fn new(shared: Rc<Shared>) -> Service {
259    Service {
260      shared,
261      state: RefCell::new(None),
262      next: Cell::new(1),
263    }
264  }
265
266  /// The request, registering with BlueZ if this is the first ask.
267  fn start(self: &Rc<Self>) -> ReadSignal<Option<PairingRequest>> {
268    if let Some(state) = &*self.state.borrow() {
269      return state.request.read_only();
270    }
271    let request = self.shared.root.signal(None);
272    *self.state.borrow_mut() = Some(State {
273      request,
274      connection: None,
275      bluez: None,
276      default: false,
277      current: None,
278    });
279    self.shared.root.signal(StopOnDrop(Rc::clone(self)));
280    match self.shared.config.system_bus.clone() {
281      Some(address) => self.shared.spawn(run(Rc::clone(self), address)),
282      None => tracing::info!("no system bus, so no Bluetooth pairing requests arrive"),
283    }
284    request.read_only()
285  }
286
287  /// Whether the request is still there: its owner, the root, isn't
288  /// disposed.
289  fn alive(&self) -> bool {
290    let state = self.state.borrow();
291    let alive = state
292      .as_ref()
293      .and_then(|state| state.request.try_with(|_| ()));
294    alive.is_some()
295  }
296
297  /// Shows the request as it is now.
298  fn publish(&self) {
299    let shown = self.state.borrow().as_ref().map(|state| {
300      let current = state.current.as_ref();
301      (state.request, current.map(|pending| pending.shown.clone()))
302    });
303    if let Some((signal, shown)) = shown {
304      set_changed(signal, shown);
305    }
306  }
307
308  /// The connection the agent registered on, while BlueZ holds it.
309  pub(crate) fn connection(&self) -> Option<Connection> {
310    let state = self.state.borrow();
311    let state = state.as_ref()?;
312    state.bluez.as_ref().and(state.connection.clone())
313  }
314
315  fn make_default(self: &Rc<Self>) {
316    if let Some(state) = self.state.borrow_mut().as_mut() {
317      state.default = true;
318    }
319    let connection = self.connection();
320    if let Some(connection) = connection {
321      let service = Rc::clone(self);
322      self
323        .shared
324        .spawn(async move { request_default(&service, &connection).await });
325    }
326  }
327
328  /// The root went: rejects the request and unregisters, as far as the
329  /// loop still runs. Touches no signal, since the root is going.
330  fn stop(&self) {
331    let call = self.state.borrow_mut().as_mut().and_then(|state| {
332      let pending = state.current.take()?;
333      pending.call
334    });
335    if let Some(call) = call {
336      self.reply::<()>(&call, Err((REJECTED, "the shell's agent went")));
337    }
338    let connection = self.state.borrow_mut().as_mut().and_then(|state| {
339      let registered = state.bluez.take().is_some();
340      state.connection.take().filter(|_| registered)
341    });
342    if let Some(connection) = connection {
343      self.shared.spawn(async move {
344        let path = agent_path();
345        let call = connection.call_method(
346          Some(BLUEZ),
347          MANAGER_PATH,
348          Some(MANAGER),
349          "UnregisterAgent",
350          &path,
351        );
352        if let Err(error) = call.await {
353          tracing::debug!(%error, "BlueZ didn't take the agent back");
354        }
355      });
356    }
357  }
358
359  /// One method call from the bus.
360  fn on_call(self: &Rc<Self>, call: Message) {
361    let header = call.header();
362    let sender = header.sender().map(|sender| sender.as_str());
363    let bluez = self
364      .state
365      .borrow()
366      .as_ref()
367      .and_then(|state| state.bluez.clone());
368    if sender.is_none() || sender != bluez.as_deref() {
369      tracing::warn!(
370        ?sender,
371        "a program other than BlueZ called the Bluetooth agent; refused"
372      );
373      return self.reply::<()>(&call, Err((ACCESS_DENIED, "only BlueZ may call the agent")));
374    }
375    let path = header.path().map(|path| path.as_str());
376    let interface = header.interface().map(|interface| interface.as_str());
377    if path != Some(AGENT_PATH) || interface != Some(AGENT) {
378      return self.reply::<()>(&call, Err((UNKNOWN_METHOD, "no such method")));
379    }
380    let member = header.member().map_or("", |member| member.as_str());
381    let body = call.body();
382    let asked = match member {
383      "Release" => {
384        tracing::info!("BlueZ released the Bluetooth agent");
385        self.reply(&call, Ok(&()));
386        if let Some(state) = self.state.borrow_mut().as_mut() {
387          state.bluez = None;
388        }
389        return self.end(CANCELED, "BlueZ released the agent");
390      }
391      "Cancel" => {
392        self.reply(&call, Ok(&()));
393        return self.end(CANCELED, "BlueZ cancelled it");
394      }
395      "RequestPinCode" => body
396        .deserialize::<ObjectPath<'_>>()
397        .map(|device| (device, PairingKind::PinCode, true)),
398      "RequestPasskey" => body
399        .deserialize::<ObjectPath<'_>>()
400        .map(|device| (device, PairingKind::Passkey, true)),
401      "DisplayPinCode" => body
402        .deserialize::<(ObjectPath<'_>, &str)>()
403        .map(|(device, pin_code)| {
404          let pin_code = cut(pin_code, MAX_PIN);
405          (device, PairingKind::DisplayPinCode { pin_code }, false)
406        }),
407      "DisplayPasskey" => {
408        body
409          .deserialize::<(ObjectPath<'_>, u32, u16)>()
410          .map(|(device, passkey, entered)| {
411            let kind = PairingKind::DisplayPasskey { passkey, entered };
412            (device, kind, false)
413          })
414      }
415      "RequestConfirmation" => body
416        .deserialize::<(ObjectPath<'_>, u32)>()
417        .map(|(device, passkey)| (device, PairingKind::Confirmation { passkey }, true)),
418      "RequestAuthorization" => body
419        .deserialize::<ObjectPath<'_>>()
420        .map(|device| (device, PairingKind::Authorization, true)),
421      "AuthorizeService" => body
422        .deserialize::<(ObjectPath<'_>, &str)>()
423        .map(|(device, uuid)| {
424          let uuid = cut(uuid, MAX_UUID);
425          (device, PairingKind::Service { uuid }, true)
426        }),
427      _ => return self.reply::<()>(&call, Err((UNKNOWN_METHOD, "no such method"))),
428    };
429    let Ok((device, kind, waits)) = asked else {
430      return self.reply::<()>(&call, Err((INVALID_ARGS, "not what BlueZ sends")));
431    };
432    tracing::info!(member, "BlueZ asks the Bluetooth agent");
433    let device = device.to_string();
434    if !waits {
435      // BlueZ waits only for the call to arrive, and cancels the code later.
436      self.reply(&call, Ok(&()));
437    }
438    self.show(device, kind, waits.then_some(call.clone()));
439  }
440
441  /// Shows a new request, in place of the one before, which BlueZ is told
442  /// was cancelled if it still waited.
443  fn show(&self, device: String, kind: PairingKind, call: Option<Message>) {
444    let replaced = {
445      let mut state = self.state.borrow_mut();
446      let Some(state) = state.as_mut() else {
447        return;
448      };
449      // A passkey whose typed count went up stays the same request.
450      let same = state.current.as_ref().filter(|pending| {
451        let typing = |kind: &PairingKind| matches!(kind, PairingKind::DisplayPasskey { .. });
452        pending.shown.device == device && typing(&pending.shown.kind) && typing(&kind)
453      });
454      let id = same.map_or_else(
455        || self.next.replace(self.next.get() + 1),
456        |pending| pending.shown.id,
457      );
458      let shown = PairingRequest { id, device, kind };
459      let old = state.current.replace(Pending { shown, call });
460      old.and_then(|pending| pending.call)
461    };
462    if let Some(old) = replaced {
463      self.reply::<()>(&old, Err((CANCELED, "another request came")));
464    }
465    self.publish();
466  }
467
468  /// Takes the request away, telling BlueZ `error` if it still waited.
469  fn end(&self, error: &str, why: &str) {
470    let taken = self
471      .state
472      .borrow_mut()
473      .as_mut()
474      .and_then(|state| state.current.take());
475    let Some(pending) = taken else {
476      return;
477    };
478    if let Some(call) = pending.call {
479      self.reply::<()>(&call, Err((error, why)));
480    }
481    self.publish();
482  }
483
484  /// Answers `call` with `answer`'s body, or with the error and why.
485  fn reply<B>(&self, call: &Message, answer: Result<&B, (&str, &str)>)
486  where
487    B: serde::Serialize + zbus::DynamicType,
488  {
489    let header = call.header();
490    if header.primary().flags().contains(Flags::NO_REPLY_EXPECTED) {
491      return;
492    }
493    let reply = match answer {
494      Ok(body) => Message::method_return(&header).build(body),
495      Err((name, why)) => Message::error(&header, name).build(&why),
496    };
497    let connection = self
498      .state
499      .borrow()
500      .as_ref()
501      .and_then(|state| state.connection.clone());
502    let Some(connection) = connection else {
503      return;
504    };
505    self.shared.spawn(async move {
506      let sent = match reply {
507        Ok(reply) => connection.send(&reply).await,
508        Err(error) => Err(error),
509      };
510      if let Err(error) = sent {
511        tracing::debug!(%error, "the Bluetooth agent's answer wasn't sent");
512      }
513    });
514  }
515}
516
517/// `text`'s first `max` bytes at most, cut at a char boundary.
518fn cut(text: &str, max: usize) -> String {
519  text[..text.floor_char_boundary(max)].to_owned()
520}
521
522fn agent_path() -> ObjectPath<'static> {
523  ObjectPath::from_static_str(AGENT_PATH).expect("invariant: AGENT_PATH is an object path")
524}
525
526/// Joins the system bus at `address`, registers the agent with BlueZ, again
527/// whenever BlueZ starts again, and answers BlueZ's calls, until the bus
528/// closes or the request is disposed. It follows only BlueZ's owner, so
529/// nothing but BlueZ's calls wakes the shell.
530async fn run(service: Rc<Service>, address: zbus::Address) {
531  let connection = match zbus::connection::Builder::address(address).build().await {
532    Ok(connection) => connection,
533    Err(error) => {
534      return tracing::info!(%error, "can't reach the system bus, so no pairing requests arrive");
535    }
536  };
537  // Made before BlueZ can call, so no call is missed.
538  let mut messages = MessageStream::from(&connection);
539  if let Err(error) = bus_call(&connection, "AddMatch", &owner_rule(BLUEZ)).await {
540    return tracing::warn!(%error, "can't follow BlueZ, so no pairing requests arrive");
541  }
542  if let Some(state) = service.state.borrow_mut().as_mut() {
543    state.connection = Some(connection.clone());
544  }
545  register(&service, &connection).await;
546  loop {
547    let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
548    if !service.alive() {
549      return;
550    }
551    match next {
552      Some(Ok(message)) if message.header().message_type() == Kind::MethodCall => {
553        service.on_call(message);
554      }
555      Some(Ok(message)) => {
556        // The bus daemon sends this, so nobody else can fake it.
557        if let Some((name, owner)) = owner_changed(&message)
558          && name == BLUEZ
559        {
560          // Its calls went with it, so nothing is answered.
561          if let Some(state) = service.state.borrow_mut().as_mut() {
562            state.bluez = None;
563            state.current = None;
564          }
565          service.publish();
566          if !owner.is_empty() {
567            tracing::info!("BlueZ started again; registering the Bluetooth agent with it");
568            register(&service, &connection).await;
569          }
570        }
571      }
572      Some(Err(error)) => tracing::warn!(%error, "a bad message on the system bus"),
573      None => break,
574    }
575  }
576  tracing::warn!("the system bus closed, so no more pairing requests arrive");
577  if let Some(state) = service.state.borrow_mut().as_mut() {
578    state.connection = None;
579    state.bluez = None;
580    state.current = None;
581  }
582  service.publish();
583}
584
585/// Registers the agent with the BlueZ on `connection`, which takes its
586/// calls only from the unique name that answered, and makes it the
587/// default if the config asked. A refusal is logged.
588async fn register(service: &Rc<Service>, connection: &Connection) {
589  let body = (agent_path(), CAPABILITY);
590  let call = connection.call_method(
591    Some(BLUEZ),
592    MANAGER_PATH,
593    Some(MANAGER),
594    "RegisterAgent",
595    &body,
596  );
597  let bluez = match service.shared.timeout(CALL_TIMEOUT, call).await {
598    Ok(reply) => reply.header().sender().map(|sender| sender.to_string()),
599    Err(error) => {
600      return tracing::info!(%error, "BlueZ didn't take the agent; it registers when BlueZ starts");
601    }
602  };
603  tracing::info!("registered as a Bluetooth agent");
604  let default = service.state.borrow_mut().as_mut().is_some_and(|state| {
605    state.bluez = bluez;
606    state.default
607  });
608  if default {
609    request_default(service, connection).await;
610  }
611}
612
613/// Asks BlueZ to make the agent its default. A refusal is logged.
614async fn request_default(service: &Rc<Service>, connection: &Connection) {
615  let path = agent_path();
616  let call = connection.call_method(
617    Some(BLUEZ),
618    MANAGER_PATH,
619    Some(MANAGER),
620    "RequestDefaultAgent",
621    &path,
622  );
623  match service.shared.timeout(CALL_TIMEOUT, call).await {
624    Ok(_) => tracing::info!("the Bluetooth agent is BlueZ's default"),
625    Err(error) => tracing::warn!(%error, "BlueZ refused to make the agent its default"),
626  }
627}