Skip to main content

webbluetooth_linux/
gatt.rs

1//! A GATT client over an L2CAP socket, with no daemon in the way.
2//!
3//! Connecting an L2CAP socket to CID 4 — the fixed ATT channel — makes the
4//! kernel establish the LE link and hands back a GATT connection. From there
5//! everything is [`crate::att`] PDUs.
6//!
7//! # Serialising requests
8//!
9//! ATT allows exactly **one outstanding request per connection**: the peer will
10//! not answer a second until the first is done. So a request takes a lock,
11//! writes, and waits for its reply, while a reader thread separates replies
12//! from unsolicited notifications — which may arrive at any time, including in
13//! the middle of a request, and must not be mistaken for its answer.
14
15use crate::att::{self, AttError, Characteristic, Descriptor, Response, Service, Uuid};
16use crate::sys::{
17    address_type, bind_le_source, close, connect, errno, parse_address, read, shutdown, socket,
18    wait_ready, write, Ready, SockAddrL2, AF_BLUETOOTH, BTPROTO_L2CAP, EINTR, POLLIN, POLLOUT,
19    SHUT_RDWR, SOCK_SEQPACKET,
20};
21use std::ffi::c_int;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Arc, Condvar, Mutex};
24use std::time::Duration;
25
26const ATT_CID: u16 = 4;
27const DEFAULT_MTU: u16 = 517;
28const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
29
30/// Why a GATT operation failed.
31#[derive(Debug, Clone)]
32pub enum Error {
33    /// The socket could not be opened or connected.
34    Io(String),
35    /// The peer refused, with an ATT error code.
36    Att(AttError),
37    /// No reply within the deadline.
38    Timeout,
39    /// The link dropped.
40    Disconnected,
41    /// A reply that did not decode, or was not the one asked for.
42    Protocol(String),
43}
44
45impl std::fmt::Display for Error {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            Self::Io(m) => write!(f, "{m}"),
49            Self::Att(e) => write!(f, "the peer refused: {e}"),
50            Self::Timeout => f.write_str("the peer did not answer"),
51            Self::Disconnected => f.write_str("the link dropped"),
52            Self::Protocol(m) => write!(f, "protocol error: {m}"),
53        }
54    }
55}
56
57type Result<T> = std::result::Result<T, Error>;
58
59/// Where unsolicited traffic goes.
60pub trait NotificationSink: Send + Sync {
61    /// A `Handle Value Notification` or `Indication` arrived.
62    fn on_notification(&self, handle: u16, value: Vec<u8>);
63    /// The link dropped.
64    fn on_disconnected(&self);
65}
66
67struct Shared {
68    fd: c_int,
69    /// The reply to the request in flight, if it has arrived.
70    reply: Mutex<Option<Response>>,
71    arrived: Condvar,
72    stopped: AtomicBool,
73}
74
75impl Shared {
76    /// Write a PDU with a short deadline, discarding failures.
77    ///
78    /// Used for the replies this side owes the peer. There is nobody to report
79    /// a failure to and nothing useful to do about one, but it still must not
80    /// block the reader thread indefinitely.
81    fn send(&self, pdu: &[u8]) {
82        if !matches!(wait_ready(self.fd, POLLOUT, 1000), Ok(Ready::Yes)) {
83            return;
84        }
85        unsafe { write(self.fd, pdu.as_ptr(), pdu.len()) };
86    }
87
88    /// Answer a request the peer made of us.
89    ///
90    /// This crate is a GATT client and has no attribute database to serve, but
91    /// a client still shares the connection with a peer that may ask. BlueZ
92    /// opens with `Exchange MTU Request`, and leaving it unanswered leaves the
93    /// peer waiting on a reply that never comes. Everything else is declined
94    /// properly, which is what `Error Response` is for.
95    fn answer(&self, opcode: u8, body: &[u8]) {
96        if opcode == att::opcode::EXCHANGE_MTU_REQUEST && body.len() >= 2 {
97            self.send(&att::exchange_mtu_response(DEFAULT_MTU));
98            return;
99        }
100        // The handle, where the request carries one, so the error names it.
101        let handle = if body.len() >= 2 {
102            u16::from_le_bytes([body[0], body[1]])
103        } else {
104            0
105        };
106        self.send(&att::error_response(
107            opcode,
108            handle,
109            AttError(AttError::REQUEST_NOT_SUPPORTED),
110        ));
111    }
112}
113
114impl Drop for Shared {
115    fn drop(&mut self) {
116        unsafe { close(self.fd) };
117    }
118}
119
120/// A GATT connection to one peer.
121pub struct Connection {
122    shared: Arc<Shared>,
123    /// ATT allows one outstanding request; this enforces it.
124    in_flight: Mutex<()>,
125    mtu: Mutex<u16>,
126    peer: String,
127}
128
129impl Connection {
130    /// Open an ATT connection to `address`.
131    ///
132    /// `random_address` must match how the peer advertised — connecting to a
133    /// random address as though it were public simply times out.
134    pub fn open(
135        address: &str,
136        random_address: bool,
137        sink: Arc<dyn NotificationSink>,
138    ) -> Result<Self> {
139        let bdaddr = parse_address(address)
140            .ok_or_else(|| Error::Io(format!("{address:?} is not a Bluetooth address")))?;
141
142        let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
143        if fd < 0 {
144            return Err(Error::Io(format!(
145                "could not create an L2CAP socket (errno {})",
146                errno()
147            )));
148        }
149
150        if let Err(e) = bind_le_source(fd, 0, ATT_CID) {
151            unsafe { close(fd) };
152            return Err(Error::Io(format!(
153                "could not bind an LE ATT socket (errno {e})"
154            )));
155        }
156
157        let addr = SockAddrL2 {
158            family: AF_BLUETOOTH as u16,
159            psm: 0,
160            bdaddr,
161            cid: ATT_CID.to_le(),
162            bdaddr_type: address_type(random_address),
163        };
164        if unsafe { connect(fd, &addr, std::mem::size_of::<SockAddrL2>() as u32) } < 0 {
165            let e = errno();
166            unsafe { close(fd) };
167            return Err(Error::Io(format!(
168                "could not connect to {address} (errno {e})"
169            )));
170        }
171
172        let shared = Arc::new(Shared {
173            fd,
174            reply: Mutex::new(None),
175            arrived: Condvar::new(),
176            stopped: AtomicBool::new(false),
177        });
178        spawn_reader(shared.clone(), sink);
179
180        let connection = Self {
181            shared,
182            in_flight: Mutex::new(()),
183            mtu: Mutex::new(23),
184            peer: address.to_owned(),
185        };
186
187        // Negotiate up from the 23-byte default. A peer that refuses keeps 23,
188        // which is correct rather than fatal.
189        if let Ok(Response::Mtu(mtu)) = connection.request(&att::exchange_mtu_request(DEFAULT_MTU))
190        {
191            *connection.mtu.lock().unwrap() = mtu.clamp(23, DEFAULT_MTU);
192        }
193        Ok(connection)
194    }
195
196    pub fn peer(&self) -> &str {
197        &self.peer
198    }
199
200    /// The negotiated ATT MTU. A write carries `mtu - 3` bytes.
201    pub fn mtu(&self) -> u16 {
202        *self.mtu.lock().unwrap()
203    }
204
205    pub fn is_connected(&self) -> bool {
206        !self.shared.stopped.load(Ordering::Acquire)
207    }
208
209    pub fn close(&self) {
210        self.shared.stopped.store(true, Ordering::Release);
211        unsafe { shutdown(self.shared.fd, SHUT_RDWR) };
212    }
213
214    /// Send one request and wait for its reply.
215    fn request(&self, pdu: &[u8]) -> Result<Response> {
216        let _one_at_a_time = self.in_flight.lock().map_err(|_| Error::Disconnected)?;
217        if !self.is_connected() {
218            return Err(Error::Disconnected);
219        }
220        *self.shared.reply.lock().unwrap() = None;
221
222        let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
223        self.send(pdu, deadline)?;
224
225        let mut guard = self.shared.reply.lock().map_err(|_| Error::Disconnected)?;
226        while guard.is_none() {
227            if !self.is_connected() {
228                return Err(Error::Disconnected);
229            }
230            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
231            if remaining.is_zero() {
232                return Err(Error::Timeout);
233            }
234            let (g, _) = self
235                .shared
236                .arrived
237                .wait_timeout(guard, remaining)
238                .map_err(|_| Error::Disconnected)?;
239            guard = g;
240        }
241        guard.take().ok_or(Error::Disconnected)
242    }
243
244    /// Write one PDU, waiting for the socket rather than blocking in it.
245    ///
246    /// A bare `write` on an L2CAP socket has no deadline: if the channel is
247    /// suspended — which the kernel does while security is pending — the call
248    /// parks in `bt_sock_wait_ready` with `SO_SNDTIMEO` unset and never
249    /// returns. That is a hang with no error and no timeout, below the reach of
250    /// the deadline this request is already carrying. Polling first gives the
251    /// deadline somewhere to apply.
252    fn send(&self, pdu: &[u8], deadline: std::time::Instant) -> Result<()> {
253        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
254        if remaining.is_zero() {
255            return Err(Error::Timeout);
256        }
257        let ms = remaining.as_millis().min(i32::MAX as u128) as i32;
258        match wait_ready(self.shared.fd, POLLOUT, ms) {
259            Ok(Ready::Yes) => {}
260            Ok(Ready::TimedOut) => return Err(Error::Timeout),
261            Ok(Ready::Closed) => return Err(Error::Disconnected),
262            Err(e) => return Err(Error::Io(format!("poll failed (errno {e})"))),
263        }
264        let n = unsafe { write(self.shared.fd, pdu.as_ptr(), pdu.len()) };
265        if n as usize != pdu.len() {
266            return Err(Error::Io(format!("ATT write failed (errno {})", errno())));
267        }
268        Ok(())
269    }
270
271    /// Write a value in `Prepare Write` fragments, then apply them.
272    ///
273    /// One `Write Request` carries at most `MTU - 3` bytes, but a GATT
274    /// attribute holds up to 512. Anything longer has to be queued in
275    /// fragments and committed with `Execute Write`, or the peer rejects the
276    /// oversized request.
277    fn write_long(&self, handle: u16, value: &[u8]) -> Result<()> {
278        // Prepare Write spends two more header bytes than Write Request on the
279        // offset.
280        let chunk = (*self.mtu.lock().unwrap() as usize)
281            .saturating_sub(5)
282            .max(1);
283        for (i, part) in value.chunks(chunk).enumerate() {
284            let offset = (i * chunk) as u16;
285            match self.checked(&att::prepare_write_request(handle, offset, part)) {
286                Ok(Response::PrepareWriteComplete) => {}
287                Ok(other) => {
288                    // Abandon the queue rather than leave a partial value to be
289                    // committed by anyone else.
290                    let _ = self.request(&att::execute_write_request(false));
291                    return Err(Error::Protocol(format!(
292                        "unexpected reply to a prepared write: {other:?}"
293                    )));
294                }
295                Err(e) => {
296                    let _ = self.request(&att::execute_write_request(false));
297                    return Err(e);
298                }
299            }
300        }
301        match self.checked(&att::execute_write_request(true))? {
302            Response::WriteComplete => Ok(()),
303            other => Err(Error::Protocol(format!(
304                "unexpected reply to an executed write: {other:?}"
305            ))),
306        }
307    }
308
309    /// Send a request, turning an ATT error reply into an `Err`.
310    fn checked(&self, pdu: &[u8]) -> Result<Response> {
311        match self.request(pdu)? {
312            Response::Error { error, .. } => Err(Error::Att(error)),
313            other => Ok(other),
314        }
315    }
316
317    /// Every primary service on the peer.
318    ///
319    /// Repeats `Read By Group Type` from where the last reply stopped until the
320    /// peer answers `ATTRIBUTE_NOT_FOUND`, which is how it says "no more".
321    pub fn discover_services(&self) -> Result<Vec<Service>> {
322        let mut found: Vec<Service> = Vec::new();
323        let mut start = 0x0001u16;
324        loop {
325            let pdu =
326                att::read_by_group_type_request(start, 0xFFFF, att::gatt_type::PRIMARY_SERVICE);
327            match self.request(&pdu)? {
328                Response::Services(batch) if !batch.is_empty() => {
329                    let last = batch.last().map(|s| s.end_handle).unwrap_or(0xFFFF);
330                    found.extend(batch);
331                    // `last` is a u16, so this is the only way the range ends.
332                    if last == 0xFFFF {
333                        break;
334                    }
335                    start = last + 1;
336                }
337                Response::Error { error, .. } if error.is_end_of_discovery() => break,
338                Response::Error { error, .. } => return Err(Error::Att(error)),
339                other => {
340                    return Err(Error::Protocol(format!(
341                        "unexpected reply to discovery: {other:?}"
342                    )))
343                }
344            }
345        }
346        Ok(found)
347    }
348
349    /// Every characteristic within a service's handle range.
350    /// The services this one includes.
351    ///
352    /// An `Include` declaration whose included service has a 128-bit UUID does
353    /// not carry it, so the UUID is read from the included service's own
354    /// declaration — otherwise the caller would have a handle range it cannot
355    /// name.
356    pub fn discover_included_services(&self, service: &Service) -> Result<Vec<Service>> {
357        let mut found: Vec<Service> = Vec::new();
358        let mut start = service.start_handle;
359        loop {
360            if start > service.end_handle {
361                break;
362            }
363            let pdu = att::read_by_type_request(start, service.end_handle, att::gatt_type::INCLUDE);
364            match self.request(&pdu)? {
365                Response::Includes(batch) if !batch.is_empty() => {
366                    let last = batch.last().map(|i| i.handle).unwrap_or(service.end_handle);
367                    for include in batch {
368                        let uuid = match include.uuid {
369                            Some(uuid) => uuid,
370                            // A 128-bit included service: read its declaration.
371                            None => match self.read(include.start_handle) {
372                                Ok(bytes) => match att::Uuid::parse(&bytes) {
373                                    Some(uuid) => uuid,
374                                    None => continue,
375                                },
376                                Err(_) => continue,
377                            },
378                        };
379                        found.push(Service {
380                            start_handle: include.start_handle,
381                            end_handle: include.end_handle,
382                            uuid,
383                        });
384                    }
385                    if last >= service.end_handle {
386                        break;
387                    }
388                    start = last + 1;
389                }
390                // An empty batch or "attribute not found" both mean there are
391                // no more; a service that includes nothing is the common case.
392                Response::Includes(_) => break,
393                Response::Error { error, .. } if error.is_end_of_discovery() => break,
394                Response::Error { error, .. } => return Err(Error::Att(error)),
395                other => {
396                    return Err(Error::Protocol(format!(
397                        "unexpected reply to include discovery: {other:?}"
398                    )))
399                }
400            }
401        }
402        Ok(found)
403    }
404
405    pub fn discover_characteristics(&self, service: &Service) -> Result<Vec<Characteristic>> {
406        let mut found: Vec<Characteristic> = Vec::new();
407        let mut start = service.start_handle;
408        loop {
409            if start > service.end_handle {
410                break;
411            }
412            let pdu = att::read_by_type_request(
413                start,
414                service.end_handle,
415                att::gatt_type::CHARACTERISTIC,
416            );
417            match self.request(&pdu)? {
418                Response::Characteristics(batch) if !batch.is_empty() => {
419                    let last = batch.last().map(|c| c.handle).unwrap_or(service.end_handle);
420                    found.extend(batch);
421                    if last >= service.end_handle {
422                        break;
423                    }
424                    start = last + 1;
425                }
426                Response::Error { error, .. } if error.is_end_of_discovery() => break,
427                Response::Error { error, .. } => return Err(Error::Att(error)),
428                other => {
429                    return Err(Error::Protocol(format!(
430                        "unexpected reply to discovery: {other:?}"
431                    )))
432                }
433            }
434        }
435        Ok(found)
436    }
437
438    /// The descriptors of one characteristic — everything between its value
439    /// handle and the next characteristic (or the end of the service).
440    pub fn discover_descriptors(&self, start: u16, end: u16) -> Result<Vec<Descriptor>> {
441        if start > end {
442            return Ok(Vec::new());
443        }
444        let mut found: Vec<Descriptor> = Vec::new();
445        let mut cursor = start;
446        loop {
447            if cursor > end {
448                break;
449            }
450            match self.request(&att::find_information_request(cursor, end))? {
451                Response::Descriptors(batch) if !batch.is_empty() => {
452                    let last = batch.last().map(|d| d.handle).unwrap_or(end);
453                    found.extend(batch);
454                    if last >= end {
455                        break;
456                    }
457                    cursor = last + 1;
458                }
459                Response::Error { error, .. } if error.is_end_of_discovery() => break,
460                Response::Error { error, .. } => return Err(Error::Att(error)),
461                other => {
462                    return Err(Error::Protocol(format!(
463                        "unexpected reply to discovery: {other:?}"
464                    )))
465                }
466            }
467        }
468        Ok(found)
469    }
470
471    /// Read an attribute, following on with `Read Blob` if the value filled the
472    /// MTU — which is the only signal that there is more of it.
473    pub fn read(&self, handle: u16) -> Result<Vec<u8>> {
474        let Response::Value(mut value) = self.checked(&att::read_request(handle))? else {
475            return Err(Error::Protocol("expected a value".into()));
476        };
477        let first_chunk = self.mtu() as usize - 1;
478        while value.len() == first_chunk + (value.len() - first_chunk) && value.len() >= first_chunk
479        {
480            let offset = value.len() as u16;
481            match self.checked(&att::read_blob_request(handle, offset)) {
482                Ok(Response::Value(more)) if !more.is_empty() => value.extend_from_slice(&more),
483                // `ATTRIBUTE_NOT_LONG` and an empty blob both mean "that was all".
484                _ => break,
485            }
486            if value.len() >= 512 {
487                break;
488            }
489        }
490        Ok(value)
491    }
492
493    /// Write and wait for the peer to acknowledge.
494    pub fn write(&self, handle: u16, value: &[u8]) -> Result<()> {
495        // One Write Request carries `MTU - 3` bytes. Longer values have to go
496        // as prepared fragments; sending an oversized request instead gets it
497        // refused, or silently truncated by a lenient peer.
498        let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
499        if value.len() > single {
500            return self.write_long(handle, value);
501        }
502        match self.checked(&att::write_request(handle, value))? {
503            Response::WriteComplete => Ok(()),
504            other => Err(Error::Protocol(format!(
505                "unexpected reply to a write: {other:?}"
506            ))),
507        }
508    }
509
510    /// Write without acknowledgement. Nothing comes back, so nothing is waited
511    /// for and a dropped write is invisible.
512    pub fn write_command(&self, handle: u16, value: &[u8]) -> Result<()> {
513        // There is no unacknowledged form of a long write: `Prepare Write` is
514        // a request and needs its response. Refusing beats sending a truncated
515        // value that the caller believes was delivered whole.
516        let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
517        if value.len() > single {
518            return Err(Error::Protocol(format!(
519                "{} bytes does not fit one unacknowledged write (MTU allows {single}); \
520                 use an acknowledged write",
521                value.len()
522            )));
523        }
524        let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
525        self.send(&att::write_command(handle, value), deadline)
526    }
527
528    /// Subscribe by writing the Client Characteristic Configuration descriptor.
529    ///
530    /// There is no "subscribe" in ATT — `0x0001` asks for notifications,
531    /// `0x0002` for indications, `0x0000` stops both.
532    pub fn set_notify(&self, cccd_handle: u16, notify: bool, indicate: bool) -> Result<()> {
533        let bits: u16 = u16::from(notify) | (u16::from(indicate) << 1);
534        self.write(cccd_handle, &bits.to_le_bytes())
535    }
536}
537
538impl Drop for Connection {
539    fn drop(&mut self) {
540        self.close();
541    }
542}
543
544fn spawn_reader(shared: Arc<Shared>, sink: Arc<dyn NotificationSink>) {
545    std::thread::Builder::new()
546        .name("webbluetooth-att".into())
547        .spawn(move || {
548            let mut buf = vec![0u8; 1024];
549            while !shared.stopped.load(Ordering::Acquire) {
550                // Poll rather than block in `read`, so `close()` is observed
551                // instead of leaving this thread parked on a dead descriptor.
552                match wait_ready(shared.fd, POLLIN, 250) {
553                    Ok(Ready::Yes) => {}
554                    Ok(Ready::TimedOut) => continue,
555                    Ok(Ready::Closed) => break,
556                    Err(e) if e == EINTR => continue,
557                    Err(_) => break,
558                }
559                let n = unsafe { read(shared.fd, buf.as_mut_ptr(), buf.len()) };
560                if n <= 0 {
561                    if n < 0 && errno() == EINTR {
562                        continue; // EINTR
563                    }
564                    break;
565                }
566                let pdu = &buf[..n as usize];
567                let Some(response) = att::parse(pdu) else {
568                    continue;
569                };
570
571                // Three kinds of inbound PDU, and only one of them is a reply.
572                // Unsolicited values are delivered to the sink; the peer's own
573                // requests are answered; everything else is the response to
574                // whatever request is in flight.
575                match response {
576                    Response::Notification { handle, value } => sink.on_notification(handle, value),
577                    Response::Indication { handle, value } => {
578                        sink.on_notification(handle, value);
579                        shared.send(&att::handle_value_confirmation());
580                    }
581                    Response::PeerRequest { opcode, body } => {
582                        shared.answer(opcode, &body);
583                    }
584                    other => {
585                        *shared.reply.lock().unwrap() = Some(other);
586                        shared.arrived.notify_all();
587                    }
588                }
589            }
590            shared.stopped.store(true, Ordering::Release);
591            // Wake anyone waiting on a reply that will never come.
592            shared.arrived.notify_all();
593            sink.on_disconnected();
594        })
595        .expect("could not start the ATT reader thread");
596}
597
598/// Find the Client Characteristic Configuration descriptor among a set.
599pub fn find_cccd(descriptors: &[Descriptor]) -> Option<u16> {
600    descriptors
601        .iter()
602        .find(|d| d.uuid == Uuid::Short(att::gatt_type::CLIENT_CHARACTERISTIC_CONFIGURATION))
603        .map(|d| d.handle)
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609
610    // Address parsing and the socket layout are tested in `sys`.
611
612    #[test]
613    fn the_cccd_is_found_by_uuid() {
614        let descriptors = vec![
615            Descriptor {
616                handle: 0x0010,
617                uuid: Uuid::Short(0x2901),
618            },
619            Descriptor {
620                handle: 0x0011,
621                uuid: Uuid::Short(0x2902),
622            },
623        ];
624        assert_eq!(find_cccd(&descriptors), Some(0x0011));
625        assert_eq!(find_cccd(&[]), None);
626    }
627}