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