Skip to main content

webbluetooth_linux/
peripheral_backend.rs

1//! The Linux peripheral engine: a GATT application exported over D-Bus.
2//!
3//! BlueZ owns the controller, so a peripheral is not built by talking to
4//! hardware but by *becoming a D-Bus service* and handing `bluetoothd` the
5//! object tree it should publish:
6//!
7//! ```text
8//! /io/webbluetooth/peripheral            org.freedesktop.DBus.ObjectManager
9//!   service0                             org.bluez.GattService1
10//!     service0/char0                     org.bluez.GattCharacteristic1
11//!       service0/char0/desc0             org.bluez.GattDescriptor1
12//! ```
13//!
14//! `GattManager1.RegisterApplication` points BlueZ at the root; it walks the
15//! tree with `GetManagedObjects`, then calls back into our characteristics
16//! whenever a central reads, writes or subscribes. Advertising is a second,
17//! separate object registered with `LEAdvertisingManager1`.
18//!
19//! Two consequences worth knowing:
20//!
21//! * **Every read is a blocking D-Bus call.** BlueZ expects `ReadValue` to
22//!   return the bytes, but this crate's API hands the application a
23//!   [`ReadRequest`] to answer whenever it likes. The handler therefore parks
24//!   until the application responds, with a deadline — which is why inbound
25//!   method calls each get their own thread rather than running on the D-Bus
26//!   reader.
27//! * **Notifications are property changes.** There is no "notify" call; a
28//!   subscribed central is sent a value by emitting `PropertiesChanged` for the
29//!   characteristic's `Value`. BlueZ decides whether that becomes a
30//!   notification or an indication from the characteristic's flags.
31
32use crate::bluez::{interfaces, Bluez, Event, EventSink};
33use crate::dbus::connection::ObjectHandler;
34use crate::dbus::{Message, Value};
35use futures_core::Stream;
36use std::pin::Pin;
37use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
38use std::sync::mpsc::{channel, Sender};
39use std::sync::{Arc, Mutex};
40use std::task::{Context, Poll};
41use std::time::Duration;
42use webbluetooth_core::error::{Availability, Error, Result};
43use webbluetooth_core::gatt::CharacteristicProperties as Properties;
44use webbluetooth_core::peripheral::{Advertising, AttError, RestoredPeripheral, Service, Write};
45use webbluetooth_core::uuid::{BluetoothUuid, IntoUuid};
46
47/// Where our objects live. Anything unique works; BlueZ only follows the path
48/// it is given.
49const ROOT: &str = "/io/webbluetooth/peripheral";
50const ADVERTISEMENT: &str = "/io/webbluetooth/peripheral/advertisement0";
51
52const DBUS_PROPERTIES: &str = "org.freedesktop.DBus.Properties";
53/// How long a `ReadValue` or `WriteValue` waits for the application.
54///
55/// BlueZ gives a GATT operation rather longer than this, so timing out here
56/// first means the central sees a proper ATT error instead of a stalled link.
57const ANSWER_TIMEOUT: Duration = Duration::from_secs(10);
58
59/// What a notification can carry before the MTU has been negotiated.
60const DEFAULT_NOTIFY_LEN: usize = 20;
61
62/// One `u64` out of a BlueZ options dictionary.
63fn option_u64(options: Option<&Value>, key: &str) -> Option<u64> {
64    options?.as_map().get(key)?.peel().as_u64()
65}
66
67/// The flag strings BlueZ expects, derived from our property bits.
68fn flags_for(properties: Properties) -> Vec<String> {
69    let mut flags = Vec::new();
70    if properties.read() {
71        flags.push("read".to_string());
72    }
73    if properties.write() {
74        flags.push("write".to_string());
75    }
76    if properties.write_without_response() {
77        flags.push("write-without-response".to_string());
78    }
79    if properties.notify() {
80        flags.push("notify".to_string());
81    }
82    if properties.indicate() {
83        flags.push("indicate".to_string());
84    }
85    flags
86}
87
88// ── Requests ────────────────────────────────────────────────────────────────
89
90/// A central that is connected to us.
91///
92/// BlueZ identifies it by device object path; the address is the last element.
93#[derive(Debug, Clone)]
94pub struct RemoteCentral {
95    id: String,
96    mtu: usize,
97}
98
99impl RemoteCentral {
100    fn from_options(options: Option<&Value>, fallback_mtu: usize) -> Self {
101        let device = options.map(|o| o.as_map()).and_then(|m| {
102            m.get("device")
103                .and_then(|v| v.peel().as_str().map(str::to_owned))
104        });
105        // `/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF` — the address is the tail.
106        let id = device
107            .as_deref()
108            .and_then(|path| path.rsplit('/').next())
109            .and_then(|last| last.strip_prefix("dev_"))
110            .map(|a| a.replace('_', ":"))
111            .or(device)
112            .unwrap_or_else(|| "unknown".to_string());
113        // The ATT MTU, of which a notification can use all but three bytes.
114        let mtu = option_u64(options, "mtu")
115            .map(|v| (v as usize).saturating_sub(3))
116            .unwrap_or(fallback_mtu);
117        Self { id, mtu }
118    }
119
120    pub fn id(&self) -> &str {
121        &self.id
122    }
123
124    /// The most bytes one notification to this central can carry.
125    pub fn max_notification_length(&self) -> usize {
126        self.mtu
127    }
128}
129
130/// A central is reading a characteristic and is waiting for the bytes.
131pub struct ReadRequest {
132    characteristic: BluetoothUuid,
133    central: RemoteCentral,
134    offset: usize,
135    answer: Option<Sender<std::result::Result<Vec<u8>, AttError>>>,
136}
137
138impl ReadRequest {
139    pub fn characteristic(&self) -> &BluetoothUuid {
140        &self.characteristic
141    }
142
143    pub fn central(&self) -> &RemoteCentral {
144        &self.central
145    }
146
147    /// Where in the attribute the central is reading from, for long reads.
148    pub fn offset(&self) -> usize {
149        self.offset
150    }
151
152    /// Answer with a value.
153    pub fn respond(mut self, value: &[u8]) -> Result<()> {
154        let Some(answer) = self.answer.take() else {
155            return Err(Error::InvalidState("this read was already answered".into()));
156        };
157        answer
158            .send(Ok(value.to_vec()))
159            .map_err(|_| Error::InvalidState("the central stopped waiting".into()))
160    }
161
162    /// Refuse, with an ATT error the central will see.
163    pub fn reject(mut self, error: AttError) {
164        if let Some(answer) = self.answer.take() {
165            let _ = answer.send(Err(error));
166        }
167    }
168}
169
170impl Drop for ReadRequest {
171    fn drop(&mut self) {
172        // An unanswered read would hold the handler until its deadline and
173        // stall the central for no reason. Dropping it is a refusal.
174        if let Some(answer) = self.answer.take() {
175            let _ = answer.send(Err(AttError::UnlikelyError));
176        }
177    }
178}
179
180impl std::fmt::Debug for ReadRequest {
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        f.debug_struct("ReadRequest")
183            .field("characteristic", &self.characteristic.as_str())
184            .field("central", &self.central.id)
185            .field("offset", &self.offset)
186            .finish()
187    }
188}
189
190/// A central has written. BlueZ delivers one write at a time.
191pub struct WriteRequest {
192    writes: Vec<Write>,
193    central: RemoteCentral,
194    answer: Option<Sender<std::result::Result<(), AttError>>>,
195}
196
197impl WriteRequest {
198    pub fn writes(&self) -> &[Write] {
199        &self.writes
200    }
201
202    pub fn central(&self) -> &RemoteCentral {
203        &self.central
204    }
205
206    /// Accept the write.
207    pub fn accept(mut self) {
208        if let Some(answer) = self.answer.take() {
209            let _ = answer.send(Ok(()));
210        }
211    }
212
213    /// Refuse it, with an ATT error the central will see.
214    pub fn reject_all(mut self, error: AttError) {
215        if let Some(answer) = self.answer.take() {
216            let _ = answer.send(Err(error));
217        }
218    }
219}
220
221impl Drop for WriteRequest {
222    fn drop(&mut self) {
223        if let Some(answer) = self.answer.take() {
224            let _ = answer.send(Err(AttError::UnlikelyError));
225        }
226    }
227}
228
229impl std::fmt::Debug for WriteRequest {
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        f.debug_struct("WriteRequest")
232            .field("writes", &self.writes.len())
233            .field("central", &self.central.id)
234            .finish()
235    }
236}
237
238/// Something a central did that the application has to deal with.
239#[derive(Debug)]
240pub enum Request {
241    Read(ReadRequest),
242    Write(WriteRequest),
243    Subscribed {
244        central: RemoteCentral,
245        characteristic: BluetoothUuid,
246    },
247    Unsubscribed {
248        central: RemoteCentral,
249        characteristic: BluetoothUuid,
250    },
251    /// Never emitted on Linux.
252    ///
253    /// BlueZ has no equivalent of CoreBluetooth's
254    /// `peripheralManagerIsReadyToUpdateSubscribers:` — a value change is
255    /// emitted on the bus and BlueZ queues it — but the variant exists so code
256    /// written against the other engines still compiles here.
257    ReadyToNotify,
258    /// A central connected to a published L2CAP channel.
259    ChannelOpened(crate::l2cap::L2capChannel),
260}
261
262/// The stream of [`Request`]s, returned once by [`Peripheral::new`].
263/// How many requests from a central queue before one is dropped.
264const REQUEST_BACKLOG: usize = 1024;
265
266pub struct Requests {
267    rx: webbluetooth_core::backlog::Receiver<Request>,
268}
269
270impl Requests {
271    /// How many requests were dropped because this stream was not being read
272    /// fast enough.
273    ///
274    /// A central can write as fast as the link allows and the callback
275    /// delivering those writes cannot be made to wait, so a handler that falls
276    /// behind loses the newest — the ones already queued are answered first.
277    /// Anything treating these as an ordered command stream should check this
278    /// rather than assume it saw them all.
279    pub fn lost(&self) -> u64 {
280        self.rx.lost()
281    }
282}
283
284impl Stream for Requests {
285    type Item = Request;
286    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Request>> {
287        Pin::new(&mut self.rx).poll_next(cx)
288    }
289}
290
291// ── Engine ──────────────────────────────────────────────────────────────────
292
293/// One published characteristic's live state.
294struct CharacteristicState {
295    uuid: BluetoothUuid,
296    path: String,
297    flags: Vec<String>,
298    /// The last value, which is what a `Value` property read returns and what
299    /// a notification carries.
300    value: Mutex<Vec<u8>>,
301    /// Centrals BlueZ has told us are subscribed.
302    subscribers: Mutex<Vec<RemoteCentral>>,
303    descriptors: Vec<DescriptorState>,
304}
305
306struct DescriptorState {
307    uuid: BluetoothUuid,
308    path: String,
309    value: Vec<u8>,
310}
311
312struct ServiceState {
313    uuid: BluetoothUuid,
314    path: String,
315    primary: bool,
316    characteristics: Vec<Arc<CharacteristicState>>,
317}
318
319struct Inner {
320    bluez: Option<Arc<Bluez>>,
321    to_app: webbluetooth_core::backlog::Sender<Request>,
322    services: Mutex<Vec<Arc<ServiceState>>>,
323    registered: AtomicBool,
324    advertising: AtomicBool,
325    next_index: AtomicUsize,
326    /// The advertisement's `a{sv}` properties, which BlueZ reads back off the
327    /// object rather than taking as call arguments.
328    advertisement: Mutex<Vec<(Value, Value)>>,
329}
330
331impl Inner {
332    fn adapter(&self) -> Result<(Arc<Bluez>, String)> {
333        let bluez = self
334            .bluez
335            .clone()
336            .ok_or(Error::NotAvailable(Availability::Unsupported))?;
337        let adapter = bluez
338            .adapter()
339            .ok_or(Error::NotAvailable(Availability::Unsupported))?;
340        Ok((bluez, adapter))
341    }
342
343    fn characteristic_at(&self, path: &str) -> Option<Arc<CharacteristicState>> {
344        self.services
345            .lock()
346            .unwrap()
347            .iter()
348            .flat_map(|s| s.characteristics.clone())
349            .find(|c| c.path == path)
350    }
351
352    fn descriptor_at(&self, path: &str) -> Option<(Arc<CharacteristicState>, Vec<u8>)> {
353        for service in self.services.lock().unwrap().iter() {
354            for characteristic in &service.characteristics {
355                for descriptor in &characteristic.descriptors {
356                    if descriptor.path == path {
357                        return Some((characteristic.clone(), descriptor.value.clone()));
358                    }
359                }
360            }
361        }
362        None
363    }
364
365    /// The whole tree, in the shape `GetManagedObjects` must return.
366    fn managed_objects(&self) -> Value {
367        let mut objects: Vec<(Value, Value)> = Vec::new();
368        for service in self.services.lock().unwrap().iter() {
369            objects.push((
370                Value::ObjectPath(service.path.clone()),
371                interfaces_of(vec![(
372                    interfaces::SERVICE,
373                    properties(vec![
374                        ("UUID", Value::Str(service.uuid.as_str().to_owned())),
375                        ("Primary", Value::Bool(service.primary)),
376                    ]),
377                )]),
378            ));
379            for characteristic in &service.characteristics {
380                objects.push((
381                    Value::ObjectPath(characteristic.path.clone()),
382                    interfaces_of(vec![(
383                        interfaces::CHARACTERISTIC,
384                        properties(vec![
385                            ("UUID", Value::Str(characteristic.uuid.as_str().to_owned())),
386                            ("Service", Value::ObjectPath(service.path.clone())),
387                            (
388                                "Flags",
389                                Value::string_array(characteristic.flags.iter().cloned()),
390                            ),
391                        ]),
392                    )]),
393                ));
394                for descriptor in &characteristic.descriptors {
395                    objects.push((
396                        Value::ObjectPath(descriptor.path.clone()),
397                        interfaces_of(vec![(
398                            interfaces::DESCRIPTOR,
399                            properties(vec![
400                                ("UUID", Value::Str(descriptor.uuid.as_str().to_owned())),
401                                (
402                                    "Characteristic",
403                                    Value::ObjectPath(characteristic.path.clone()),
404                                ),
405                                ("Flags", Value::string_array(["read".to_string()])),
406                            ]),
407                        )]),
408                    ));
409                }
410            }
411        }
412        dict_of("{oa{sa{sv}}}", objects)
413    }
414}
415
416fn dict_of(element: &str, entries: Vec<(Value, Value)>) -> Value {
417    Value::Array {
418        element: element.into(),
419        items: entries
420            .into_iter()
421            .map(|(k, v)| Value::DictEntry(Box::new(k), Box::new(v)))
422            .collect(),
423    }
424}
425
426/// `a{sv}` — a property dictionary, whose values are variants.
427fn properties(entries: Vec<(&str, Value)>) -> Value {
428    dict_of(
429        "{sv}",
430        entries
431            .into_iter()
432            .map(|(name, value)| (Value::Str(name.to_owned()), Value::Variant(Box::new(value))))
433            .collect(),
434    )
435}
436
437/// `a{sa{sv}}` — one object's interfaces and their properties.
438fn interfaces_of(entries: Vec<(&str, Value)>) -> Value {
439    dict_of(
440        "{sa{sv}}",
441        entries
442            .into_iter()
443            .map(|(interface, props)| (Value::Str(interface.to_owned()), props))
444            .collect(),
445    )
446}
447
448/// Serves our whole object tree. One handler, because D-Bus dispatch matches by
449/// path prefix and every object we export lives under [`ROOT`].
450struct Application {
451    inner: Arc<Inner>,
452}
453
454impl ObjectHandler for Application {
455    fn handle(&self, call: &Message) -> std::result::Result<Vec<Value>, (String, String)> {
456        let path = call.path.clone().unwrap_or_default();
457        let interface = call.interface.clone().unwrap_or_default();
458        let member = call.member.clone().unwrap_or_default();
459
460        match (interface.as_str(), member.as_str()) {
461            (interfaces::OBJECT_MANAGER, "GetManagedObjects") => {
462                Ok(vec![self.inner.managed_objects()])
463            }
464
465            (DBUS_PROPERTIES, "GetAll") => Ok(vec![self.properties_of(&path)]),
466
467            (DBUS_PROPERTIES, "Get") => {
468                let name = call.arg(1).and_then(Value::as_str).unwrap_or_default();
469                self.property(&path, name)
470                    .map(|v| vec![Value::Variant(Box::new(v))])
471                    .ok_or_else(|| {
472                        (
473                            "org.freedesktop.DBus.Error.InvalidArgs".to_string(),
474                            format!("no property {name} at {path}"),
475                        )
476                    })
477            }
478
479            (interfaces::CHARACTERISTIC, "ReadValue") => self.read(&path, call.arg(0)),
480            (interfaces::CHARACTERISTIC, "WriteValue") => {
481                self.write(&path, call.arg(0), call.arg(1))
482            }
483            (interfaces::CHARACTERISTIC, "StartNotify") => self.set_subscribed(&path, true),
484            (interfaces::CHARACTERISTIC, "StopNotify") => self.set_subscribed(&path, false),
485
486            // A descriptor's value is fixed at publication, so it needs no
487            // round trip to the application.
488            (interfaces::DESCRIPTOR, "ReadValue") => match self.inner.descriptor_at(&path) {
489                Some((_, value)) => Ok(vec![Value::bytes(&value)]),
490                None => Err((
491                    "org.bluez.Error.Failed".to_string(),
492                    format!("no descriptor at {path}"),
493                )),
494            },
495
496            // Registered advertisements are released rather than unregistered
497            // when BlueZ drops them.
498            (interfaces::LE_ADVERTISEMENT, "Release") => Ok(Vec::new()),
499
500            _ => Err((
501                "org.freedesktop.DBus.Error.UnknownMethod".to_string(),
502                format!("{interface}.{member} is not implemented"),
503            )),
504        }
505    }
506}
507
508impl Application {
509    fn properties_of(&self, path: &str) -> Value {
510        if path == ADVERTISEMENT {
511            // BlueZ reads the advertisement's properties rather than taking
512            // them as arguments to RegisterAdvertisement.
513            return dict_of("{sv}", self.inner.advertisement.lock().unwrap().clone());
514        }
515        if let Some(characteristic) = self.inner.characteristic_at(path) {
516            return properties(vec![
517                ("UUID", Value::Str(characteristic.uuid.as_str().to_owned())),
518                (
519                    "Flags",
520                    Value::string_array(characteristic.flags.iter().cloned()),
521                ),
522                ("Value", Value::bytes(&characteristic.value.lock().unwrap())),
523            ]);
524        }
525        properties(Vec::new())
526    }
527
528    fn property(&self, path: &str, name: &str) -> Option<Value> {
529        let characteristic = self.inner.characteristic_at(path)?;
530        match name {
531            "UUID" => Some(Value::Str(characteristic.uuid.as_str().to_owned())),
532            "Value" => Some(Value::bytes(&characteristic.value.lock().unwrap())),
533            "Flags" => Some(Value::string_array(characteristic.flags.iter().cloned())),
534            _ => None,
535        }
536    }
537
538    /// Hand a read to the application and park until it answers.
539    fn read(
540        &self,
541        path: &str,
542        options: Option<&Value>,
543    ) -> std::result::Result<Vec<Value>, (String, String)> {
544        let Some(characteristic) = self.inner.characteristic_at(path) else {
545            return Err((
546                "org.bluez.Error.Failed".to_string(),
547                format!("no characteristic at {path}"),
548            ));
549        };
550        let central = RemoteCentral::from_options(options, DEFAULT_NOTIFY_LEN);
551        let offset = option_u64(options, "offset").unwrap_or(0) as usize;
552
553        let (tx, rx) = channel();
554        let request = Request::Read(ReadRequest {
555            characteristic: characteristic.uuid,
556            central,
557            offset,
558            answer: Some(tx),
559        });
560        if self.inner.to_app.send(request).is_err() {
561            // Nobody is listening, so the last value is the best answer there
562            // is — which is also what a static characteristic would give.
563            return Ok(vec![Value::bytes(&characteristic.value.lock().unwrap())]);
564        }
565
566        match rx.recv_timeout(ANSWER_TIMEOUT) {
567            Ok(Ok(value)) => {
568                *characteristic.value.lock().unwrap() = value.clone();
569                Ok(vec![Value::bytes(&value)])
570            }
571            Ok(Err(error)) => Err((att_error_name(error), format!("read refused: {error:?}"))),
572            Err(reason) => Err((
573                "org.bluez.Error.Failed".to_string(),
574                format!("the application did not answer the read: {reason}"),
575            )),
576        }
577    }
578
579    fn write(
580        &self,
581        path: &str,
582        value: Option<&Value>,
583        options: Option<&Value>,
584    ) -> std::result::Result<Vec<Value>, (String, String)> {
585        let Some(characteristic) = self.inner.characteristic_at(path) else {
586            return Err((
587                "org.bluez.Error.Failed".to_string(),
588                format!("no characteristic at {path}"),
589            ));
590        };
591        let written: Vec<u8> = value.and_then(Value::as_bytes).unwrap_or_default();
592        let central = RemoteCentral::from_options(options, DEFAULT_NOTIFY_LEN);
593        let offset = option_u64(options, "offset").unwrap_or(0) as usize;
594
595        let (tx, rx) = channel();
596        let request = Request::Write(WriteRequest {
597            writes: vec![Write {
598                characteristic: characteristic.uuid,
599                offset,
600                value: written.clone(),
601            }],
602            central,
603            answer: Some(tx),
604        });
605        if self.inner.to_app.send(request).is_err() {
606            *characteristic.value.lock().unwrap() = written;
607            return Ok(Vec::new());
608        }
609
610        match rx.recv_timeout(ANSWER_TIMEOUT) {
611            Ok(Ok(())) => {
612                *characteristic.value.lock().unwrap() = written;
613                Ok(Vec::new())
614            }
615            Ok(Err(error)) => Err((att_error_name(error), format!("write refused: {error:?}"))),
616            Err(reason) => Err((
617                "org.bluez.Error.Failed".to_string(),
618                format!("the application did not answer the write: {reason}"),
619            )),
620        }
621    }
622
623    /// `StartNotify` / `StopNotify`. BlueZ does not say which central, so the
624    /// subscription is recorded against the connected device it knows about.
625    fn set_subscribed(
626        &self,
627        path: &str,
628        subscribed: bool,
629    ) -> std::result::Result<Vec<Value>, (String, String)> {
630        let Some(characteristic) = self.inner.characteristic_at(path) else {
631            return Err((
632                "org.bluez.Error.Failed".to_string(),
633                format!("no characteristic at {path}"),
634            ));
635        };
636        // BlueZ passes no options to StartNotify, so there is no MTU or device
637        // to read: the subscriber is described as far as it can be.
638        let central = RemoteCentral {
639            id: "subscribed".to_string(),
640            mtu: DEFAULT_NOTIFY_LEN,
641        };
642        {
643            let mut subscribers = characteristic.subscribers.lock().unwrap();
644            if subscribed {
645                subscribers.push(central.clone());
646            } else {
647                subscribers.clear();
648            }
649        }
650        let request = if subscribed {
651            Request::Subscribed {
652                central,
653                characteristic: characteristic.uuid,
654            }
655        } else {
656            Request::Unsubscribed {
657                central,
658                characteristic: characteristic.uuid,
659            }
660        };
661        let _ = self.inner.to_app.send(request);
662        Ok(Vec::new())
663    }
664}
665
666/// The ATT error names BlueZ recognises on a GATT reply.
667fn att_error_name(error: AttError) -> String {
668    // BlueZ maps its own error names back onto ATT codes, so a refusal reaches
669    // the central as the error the application asked for rather than a generic
670    // failure. Anything without a name falls back to `Failed`, which BlueZ
671    // sends as `UnlikelyError`.
672    match error {
673        AttError::ReadNotPermitted | AttError::WriteNotPermitted => "org.bluez.Error.NotPermitted",
674        AttError::InsufficientAuthentication | AttError::InsufficientEncryption => {
675            "org.bluez.Error.NotPaired"
676        }
677        AttError::InsufficientAuthorization => "org.bluez.Error.NotAuthorized",
678        AttError::RequestNotSupported => "org.bluez.Error.NotSupported",
679        AttError::InvalidOffset => "org.bluez.Error.InvalidOffset",
680        AttError::InvalidAttributeValueLength => "org.bluez.Error.InvalidValueLength",
681        _ => "org.bluez.Error.Failed",
682    }
683    .to_string()
684}
685
686/// Discards BlueZ's central-role events; a peripheral has no use for them.
687struct Discard;
688impl EventSink for Discard {
689    fn emit(&self, _event: Event) {}
690}
691
692// ── Peripheral ──────────────────────────────────────────────────────────────
693
694/// A local GATT server, published through `bluetoothd`.
695#[derive(Clone)]
696pub struct Peripheral {
697    inner: Arc<Inner>,
698}
699
700impl Peripheral {
701    /// Open the peripheral role, returning the handle and its request stream.
702    pub fn new() -> (Self, Requests) {
703        // Requests from a connected central: reads and writes against the
704        // GATT server this process publishes. Bounded, keeping the *oldest*,
705        // because these are commands in order — a control point told to do
706        // three things wants the first three, not the last three.
707        let (to_app, rx) = webbluetooth_core::backlog::bounded(
708            REQUEST_BACKLOG,
709            webbluetooth_core::backlog::Overflow::KeepOldest,
710        );
711        let bluez = Bluez::new(Arc::new(Discard)).ok().map(Arc::new);
712        let inner = Arc::new(Inner {
713            bluez,
714            to_app,
715            services: Mutex::new(Vec::new()),
716            registered: AtomicBool::new(false),
717            advertising: AtomicBool::new(false),
718            next_index: AtomicUsize::new(0),
719            advertisement: Mutex::new(Vec::new()),
720        });
721        if let Some(bluez) = &inner.bluez {
722            bluez.export(
723                ROOT,
724                Arc::new(Application {
725                    inner: inner.clone(),
726                }),
727            );
728        }
729        (Self { inner }, Requests { rx })
730    }
731
732    /// Linux has no state restoration; this is [`Peripheral::new`].
733    pub fn with_restoration(_restoration: webbluetooth_core::Restoration) -> (Self, Requests) {
734        Self::new()
735    }
736
737    /// Why the peripheral role is not usable, if it is not.
738    pub async fn availability(&self) -> std::result::Result<(), Availability> {
739        let Some(bluez) = &self.inner.bluez else {
740            return Err(Availability::Unauthorized);
741        };
742        if bluez.adapter().is_none() {
743            return Err(Availability::Unsupported);
744        }
745        if !bluez.is_powered() {
746            return Err(Availability::PoweredOff);
747        }
748        Ok(())
749    }
750
751    /// Publish a service into the local GATT database.
752    ///
753    /// The first call registers the application with BlueZ; later ones
754    /// re-register it, because `GattManager1` has no way to add a service to an
755    /// application it has already walked.
756    pub async fn publish(&self, service: Service) -> Result<PublishedService> {
757        service.validate()?;
758        let (bluez, adapter) = self.inner.adapter()?;
759        if !bluez.is_powered() {
760            return Err(Error::NotAvailable(Availability::PoweredOff));
761        }
762
763        let index = self.inner.next_index.fetch_add(1, Ordering::Relaxed);
764        let service_path = format!("{ROOT}/service{index}");
765        let mut characteristics = Vec::new();
766
767        for (i, definition) in service.characteristics.iter().enumerate() {
768            let path = format!("{service_path}/char{i}");
769            let descriptors = definition
770                .descriptors
771                .iter()
772                .enumerate()
773                .map(|(j, d)| DescriptorState {
774                    uuid: d.uuid,
775                    path: format!("{path}/desc{j}"),
776                    value: d.value.clone(),
777                })
778                .collect();
779            characteristics.push(Arc::new(CharacteristicState {
780                uuid: definition.uuid,
781                path,
782                flags: flags_for(Properties(definition.properties)),
783                value: Mutex::new(definition.value.clone().unwrap_or_default()),
784                subscribers: Mutex::new(Vec::new()),
785                descriptors,
786            }));
787        }
788
789        let state = Arc::new(ServiceState {
790            uuid: service.uuid,
791            path: service_path,
792            primary: service.primary,
793            characteristics,
794        });
795        self.inner.services.lock().unwrap().push(state.clone());
796
797        // Re-register so BlueZ walks the tree again and sees the addition.
798        if self.inner.registered.swap(true, Ordering::SeqCst) {
799            let _ = call(
800                &bluez,
801                &adapter,
802                interfaces::GATT_MANAGER,
803                "UnregisterApplication",
804                vec![Value::ObjectPath(ROOT.to_string())],
805            );
806        }
807        call(
808            &bluez,
809            &adapter,
810            interfaces::GATT_MANAGER,
811            "RegisterApplication",
812            vec![Value::ObjectPath(ROOT.to_string()), properties(Vec::new())],
813        )
814        .inspect_err(|_| {
815            // A service BlueZ refused must not stay in the tree, or the next
816            // registration fails the same way.
817            self.inner
818                .services
819                .lock()
820                .unwrap()
821                .retain(|s| s.path != state.path);
822            self.inner.registered.store(false, Ordering::SeqCst);
823        })?;
824
825        Ok(PublishedService {
826            inner: self.inner.clone(),
827            state,
828        })
829    }
830
831    /// Withdraw every published service.
832    pub fn unpublish_all(&self) {
833        self.inner.services.lock().unwrap().clear();
834        if self.inner.registered.swap(false, Ordering::SeqCst) {
835            if let Ok((bluez, adapter)) = self.inner.adapter() {
836                let _ = call(
837                    &bluez,
838                    &adapter,
839                    interfaces::GATT_MANAGER,
840                    "UnregisterApplication",
841                    vec![Value::ObjectPath(ROOT.to_string())],
842                );
843            }
844        }
845    }
846
847    /// Start advertising.
848    pub async fn start_advertising(&self, advertising: Advertising) -> Result<()> {
849        let (bluez, adapter) = self.inner.adapter()?;
850        if self.inner.advertising.load(Ordering::SeqCst) {
851            self.stop_advertising();
852        }
853
854        // The advertisement is its own object, and BlueZ reads its properties
855        // rather than taking them as call arguments.
856        let mut entries: Vec<(Value, Value)> = vec![(
857            Value::Str("Type".into()),
858            Value::Variant(Box::new(Value::Str("peripheral".into()))),
859        )];
860        if !advertising.services.is_empty() {
861            entries.push((
862                Value::Str("ServiceUUIDs".into()),
863                Value::Variant(Box::new(Value::string_array(
864                    advertising.services.iter().map(|u| u.as_str().to_owned()),
865                ))),
866            ));
867        }
868        if let Some(name) = &advertising.local_name {
869            entries.push((
870                Value::Str("LocalName".into()),
871                Value::Variant(Box::new(Value::Str(name.clone()))),
872            ));
873        }
874        *self.inner.advertisement.lock().unwrap() = entries;
875
876        bluez.export(
877            ADVERTISEMENT,
878            Arc::new(Application {
879                inner: self.inner.clone(),
880            }),
881        );
882        call(
883            &bluez,
884            &adapter,
885            interfaces::LE_ADVERTISING_MANAGER,
886            "RegisterAdvertisement",
887            vec![
888                Value::ObjectPath(ADVERTISEMENT.to_string()),
889                properties(Vec::new()),
890            ],
891        )?;
892        self.inner.advertising.store(true, Ordering::SeqCst);
893        Ok(())
894    }
895
896    /// Stop advertising.
897    pub fn stop_advertising(&self) {
898        if !self.inner.advertising.swap(false, Ordering::SeqCst) {
899            return;
900        }
901        if let Ok((bluez, adapter)) = self.inner.adapter() {
902            let _ = call(
903                &bluez,
904                &adapter,
905                interfaces::LE_ADVERTISING_MANAGER,
906                "UnregisterAdvertisement",
907                vec![Value::ObjectPath(ADVERTISEMENT.to_string())],
908            );
909        }
910    }
911
912    pub fn is_advertising(&self) -> bool {
913        self.inner.advertising.load(Ordering::SeqCst)
914    }
915
916    /// Not available through BlueZ's GATT manager.
917    pub async fn publish_l2cap_channel(
918        &self,
919        _encryption_required: bool,
920    ) -> Result<webbluetooth_core::Psm> {
921        Err(Error::NotSupported(
922            "BlueZ has no D-Bus API for publishing an L2CAP channel; a peripheral \
923             would have to listen on an L2CAP socket itself"
924                .into(),
925        ))
926    }
927
928    pub async fn unpublish_l2cap_channel(&self, _psm: webbluetooth_core::Psm) -> Result<()> {
929        Err(Error::NotSupported(
930            "no L2CAP channel can be published on this platform".into(),
931        ))
932    }
933
934    /// Linux preserves nothing across a relaunch.
935    pub async fn restored_state(&self) -> Option<RestoredPeripheral> {
936        None
937    }
938}
939
940impl std::fmt::Debug for Peripheral {
941    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
942        f.debug_struct("Peripheral")
943            .field("services", &self.inner.services.lock().unwrap().len())
944            .field("advertising", &self.is_advertising())
945            .finish()
946    }
947}
948
949fn call(
950    bluez: &Arc<Bluez>,
951    path: &str,
952    interface: &str,
953    member: &str,
954    body: Vec<Value>,
955) -> Result<Message> {
956    bluez
957        .call(path, interface, member, body)
958        .map_err(|e| Error::Network(format!("{interface}.{member} failed: {e}")))
959}
960
961// ── Published objects ───────────────────────────────────────────────────────
962
963/// A service that is live in the local GATT database.
964pub struct PublishedService {
965    inner: Arc<Inner>,
966    state: Arc<ServiceState>,
967}
968
969impl PublishedService {
970    pub fn uuid(&self) -> &BluetoothUuid {
971        &self.state.uuid
972    }
973
974    pub fn characteristics(&self) -> Vec<PublishedCharacteristic> {
975        self.state
976            .characteristics
977            .iter()
978            .map(|c| PublishedCharacteristic {
979                inner: self.inner.clone(),
980                state: c.clone(),
981            })
982            .collect()
983    }
984
985    pub fn characteristic(&self, uuid: impl IntoUuid) -> Option<PublishedCharacteristic> {
986        let uuid = uuid.into_uuid().ok()?;
987        self.state
988            .characteristics
989            .iter()
990            .find(|c| c.uuid == uuid)
991            .map(|c| PublishedCharacteristic {
992                inner: self.inner.clone(),
993                state: c.clone(),
994            })
995    }
996
997    /// Remove just this service.
998    ///
999    /// BlueZ has no way to withdraw one service from a registered application,
1000    /// so the application is re-registered without it.
1001    pub fn unpublish(self) {
1002        self.inner
1003            .services
1004            .lock()
1005            .unwrap()
1006            .retain(|s| s.path != self.state.path);
1007        if let Ok((bluez, adapter)) = self.inner.adapter() {
1008            let _ = call(
1009                &bluez,
1010                &adapter,
1011                interfaces::GATT_MANAGER,
1012                "UnregisterApplication",
1013                vec![Value::ObjectPath(ROOT.to_string())],
1014            );
1015            let empty = self.inner.services.lock().unwrap().is_empty();
1016            if empty {
1017                self.inner.registered.store(false, Ordering::SeqCst);
1018            } else {
1019                let _ = call(
1020                    &bluez,
1021                    &adapter,
1022                    interfaces::GATT_MANAGER,
1023                    "RegisterApplication",
1024                    vec![Value::ObjectPath(ROOT.to_string()), properties(Vec::new())],
1025                );
1026            }
1027        }
1028    }
1029}
1030
1031impl std::fmt::Debug for PublishedService {
1032    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1033        f.debug_struct("PublishedService")
1034            .field("uuid", &self.state.uuid.as_str())
1035            .field("characteristics", &self.state.characteristics.len())
1036            .finish()
1037    }
1038}
1039
1040/// A characteristic that is live in the local GATT database.
1041#[derive(Clone)]
1042pub struct PublishedCharacteristic {
1043    inner: Arc<Inner>,
1044    state: Arc<CharacteristicState>,
1045}
1046
1047impl PublishedCharacteristic {
1048    pub fn uuid(&self) -> &BluetoothUuid {
1049        &self.state.uuid
1050    }
1051
1052    /// The centrals BlueZ has told us are subscribed.
1053    ///
1054    /// BlueZ reports that *someone* subscribed, not who: `StartNotify` carries
1055    /// no device. The entries here therefore stand for the subscription rather
1056    /// than identifying a peer.
1057    pub fn subscribers(&self) -> Vec<RemoteCentral> {
1058        self.state.subscribers.lock().unwrap().clone()
1059    }
1060
1061    /// Push a value to whoever is subscribed, without waiting.
1062    ///
1063    /// There is no "notify" call in BlueZ's GATT API. A subscribed central is
1064    /// sent a value by emitting `PropertiesChanged` for this characteristic's
1065    /// `Value`; BlueZ decides from the flags whether that goes out as a
1066    /// notification or an indication.
1067    pub fn try_notify(&self, value: &[u8]) -> bool {
1068        *self.state.value.lock().unwrap() = value.to_vec();
1069        if self.state.subscribers.lock().unwrap().is_empty() {
1070            return false;
1071        }
1072        let Some(bluez) = &self.inner.bluez else {
1073            return false;
1074        };
1075        let signal = Message::signal(&self.state.path, DBUS_PROPERTIES, "PropertiesChanged")
1076            .with_body(vec![
1077                Value::Str(interfaces::CHARACTERISTIC.to_string()),
1078                properties(vec![("Value", Value::bytes(value))]),
1079                Value::string_array(Vec::<String>::new()),
1080            ]);
1081        bluez.connection().send(signal).is_ok()
1082    }
1083
1084    /// Push a value to whoever is subscribed.
1085    pub async fn notify(&self, value: &[u8]) -> Result<()> {
1086        if self.try_notify(value) {
1087            return Ok(());
1088        }
1089        if self.state.subscribers.lock().unwrap().is_empty() {
1090            return Err(Error::InvalidState(format!(
1091                "nothing is subscribed to {}",
1092                self.state.uuid
1093            )));
1094        }
1095        Err(Error::Network(
1096            "could not emit the value change on the bus".into(),
1097        ))
1098    }
1099}
1100
1101impl std::fmt::Debug for PublishedCharacteristic {
1102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1103        f.debug_struct("PublishedCharacteristic")
1104            .field("uuid", &self.state.uuid.as_str())
1105            .field("subscribers", &self.subscribers().len())
1106            .finish()
1107    }
1108}