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