Skip to main content

bluetooth_host/
att.rs

1//! The Attribute Protocol bearer (Core Vol 3, Part F).
2//!
3//! One task per connection reads ATT PDUs: responses go to the client
4//! request waiting for them, requests and commands to our GATT server,
5//! notifications and indications to the application (indications are
6//! confirmed at once).
7
8use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
9use std::sync::{Arc, Mutex};
10use std::time::Duration;
11
12use tokio::sync::{mpsc, oneshot};
13
14use crate::connection::{ConnEvent, ConnState};
15use crate::error::{Error, Result};
16use crate::host::Host;
17use crate::l2cap::cid;
18
19/// ATT opcodes.
20pub mod op {
21    /// Error Response.
22    pub const ERROR_RSP: u8 = 0x01;
23    /// Exchange MTU Request.
24    pub const MTU_REQ: u8 = 0x02;
25    /// Exchange MTU Response.
26    pub const MTU_RSP: u8 = 0x03;
27    /// Find Information Request.
28    pub const FIND_INFO_REQ: u8 = 0x04;
29    /// Find Information Response.
30    pub const FIND_INFO_RSP: u8 = 0x05;
31    /// Find By Type Value Request.
32    pub const FIND_BY_TYPE_REQ: u8 = 0x06;
33    /// Find By Type Value Response.
34    pub const FIND_BY_TYPE_RSP: u8 = 0x07;
35    /// Read By Type Request.
36    pub const READ_BY_TYPE_REQ: u8 = 0x08;
37    /// Read By Type Response.
38    pub const READ_BY_TYPE_RSP: u8 = 0x09;
39    /// Read Request.
40    pub const READ_REQ: u8 = 0x0a;
41    /// Read Response.
42    pub const READ_RSP: u8 = 0x0b;
43    /// Read Blob Request.
44    pub const READ_BLOB_REQ: u8 = 0x0c;
45    /// Read Blob Response.
46    pub const READ_BLOB_RSP: u8 = 0x0d;
47    /// Read Multiple Request.
48    pub const READ_MULTIPLE_REQ: u8 = 0x0e;
49    /// Read Multiple Response.
50    pub const READ_MULTIPLE_RSP: u8 = 0x0f;
51    /// Read By Group Type Request.
52    pub const READ_BY_GROUP_REQ: u8 = 0x10;
53    /// Read By Group Type Response.
54    pub const READ_BY_GROUP_RSP: u8 = 0x11;
55    /// Write Request.
56    pub const WRITE_REQ: u8 = 0x12;
57    /// Write Response.
58    pub const WRITE_RSP: u8 = 0x13;
59    /// Write Command.
60    pub const WRITE_CMD: u8 = 0x52;
61    /// Signed Write Command.
62    pub const SIGNED_WRITE_CMD: u8 = 0xd2;
63    /// Prepare Write Request.
64    pub const PREPARE_WRITE_REQ: u8 = 0x16;
65    /// Prepare Write Response.
66    pub const PREPARE_WRITE_RSP: u8 = 0x17;
67    /// Execute Write Request.
68    pub const EXECUTE_WRITE_REQ: u8 = 0x18;
69    /// Execute Write Response.
70    pub const EXECUTE_WRITE_RSP: u8 = 0x19;
71    /// Handle Value Notification.
72    pub const NOTIFY: u8 = 0x1b;
73    /// Handle Value Indication.
74    pub const INDICATE: u8 = 0x1d;
75    /// Handle Value Confirmation.
76    pub const CONFIRM: u8 = 0x1e;
77    /// Read Multiple Variable Length Request.
78    pub const READ_MULTIPLE_VAR_REQ: u8 = 0x20;
79    /// Read Multiple Variable Length Response.
80    pub const READ_MULTIPLE_VAR_RSP: u8 = 0x21;
81    /// Multiple Handle Value Notification.
82    pub const MULTIPLE_NOTIFY: u8 = 0x23;
83}
84
85/// ATT error codes.
86pub mod ecode {
87    /// Invalid Handle.
88    pub const INVALID_HANDLE: u8 = 0x01;
89    /// Read Not Permitted.
90    pub const READ_NOT_PERMITTED: u8 = 0x02;
91    /// Write Not Permitted.
92    pub const WRITE_NOT_PERMITTED: u8 = 0x03;
93    /// Invalid PDU.
94    pub const INVALID_PDU: u8 = 0x04;
95    /// Insufficient Authentication.
96    pub const INSUFFICIENT_AUTHENTICATION: u8 = 0x05;
97    /// Request Not Supported.
98    pub const REQUEST_NOT_SUPPORTED: u8 = 0x06;
99    /// Invalid Offset.
100    pub const INVALID_OFFSET: u8 = 0x07;
101    /// Insufficient Authorization.
102    pub const INSUFFICIENT_AUTHORIZATION: u8 = 0x08;
103    /// Prepare Queue Full.
104    pub const PREPARE_QUEUE_FULL: u8 = 0x09;
105    /// Attribute Not Found.
106    pub const ATTRIBUTE_NOT_FOUND: u8 = 0x0a;
107    /// Attribute Not Long.
108    pub const ATTRIBUTE_NOT_LONG: u8 = 0x0b;
109    /// Encryption Key Size Too Short.
110    pub const KEY_SIZE_TOO_SHORT: u8 = 0x0c;
111    /// Invalid Attribute Value Length.
112    pub const INVALID_LENGTH: u8 = 0x0d;
113    /// Unlikely Error.
114    pub const UNLIKELY: u8 = 0x0e;
115    /// Insufficient Encryption.
116    pub const INSUFFICIENT_ENCRYPTION: u8 = 0x0f;
117    /// Unsupported Group Type.
118    pub const UNSUPPORTED_GROUP_TYPE: u8 = 0x10;
119    /// Insufficient Resources.
120    pub const INSUFFICIENT_RESOURCES: u8 = 0x11;
121    /// Value Not Allowed.
122    pub const VALUE_NOT_ALLOWED: u8 = 0x13;
123    /// CCCD improperly configured.
124    pub const CCCD_IMPROPER: u8 = 0xfd;
125}
126
127/// The name of an ATT error code.
128pub fn error_name(code: u8) -> &'static str {
129    match code {
130        0x01 => "Invalid Handle",
131        0x02 => "Read Not Permitted",
132        0x03 => "Write Not Permitted",
133        0x04 => "Invalid PDU",
134        0x05 => "Insufficient Authentication",
135        0x06 => "Request Not Supported",
136        0x07 => "Invalid Offset",
137        0x08 => "Insufficient Authorization",
138        0x09 => "Prepare Queue Full",
139        0x0a => "Attribute Not Found",
140        0x0b => "Attribute Not Long",
141        0x0c => "Encryption Key Size Too Short",
142        0x0d => "Invalid Attribute Value Length",
143        0x0e => "Unlikely Error",
144        0x0f => "Insufficient Encryption",
145        0x10 => "Unsupported Group Type",
146        0x11 => "Insufficient Resources",
147        0x12 => "Database Out Of Sync",
148        0x13 => "Value Not Allowed",
149        0x80..=0x9f => "Application Error",
150        0xfc => "Write Request Rejected",
151        0xfd => "Client Characteristic Configuration Descriptor Improperly Configured",
152        0xfe => "Procedure Already in Progress",
153        0xff => "Out of Range",
154        _ => "Reserved",
155    }
156}
157
158/// The default (and minimum) ATT MTU on LE.
159pub const DEFAULT_MTU: u16 = 23;
160/// The MTU we offer: room for a 512-octet attribute value in one PDU.
161pub const MAX_MTU: u16 = 517;
162
163/// A transaction must complete within 30 s (Core Vol 3, Part F, 3.3.3).
164const TRANSACTION_TIMEOUT: Duration = Duration::from_secs(30);
165
166struct Pending {
167    request: u8,
168    tx: oneshot::Sender<Result<Vec<u8>>>,
169}
170
171/// One connection's ATT state.
172pub(crate) struct Bearer {
173    mtu: AtomicU16,
174    mtu_exchanged: AtomicBool,
175    client: tokio::sync::Mutex<()>,
176    pending: Mutex<Option<Pending>>,
177    indications: tokio::sync::Mutex<()>,
178    confirm: Mutex<Option<oneshot::Sender<()>>>,
179}
180
181impl Default for Bearer {
182    fn default() -> Self {
183        Bearer {
184            mtu: AtomicU16::new(DEFAULT_MTU),
185            mtu_exchanged: AtomicBool::new(false),
186            client: tokio::sync::Mutex::new(()),
187            pending: Mutex::new(None),
188            indications: tokio::sync::Mutex::new(()),
189            confirm: Mutex::new(None),
190        }
191    }
192}
193
194impl Bearer {
195    /// The MTU in use.
196    pub(crate) fn mtu(&self) -> u16 {
197        self.mtu.load(Ordering::Relaxed)
198    }
199
200    fn set_mtu(&self, m: u16) {
201        self.mtu
202            .store(m.clamp(DEFAULT_MTU, MAX_MTU), Ordering::Relaxed);
203    }
204
205    pub(crate) fn close(&self) {
206        if let Some(p) = self
207            .pending
208            .lock()
209            .unwrap_or_else(|e| e.into_inner())
210            .take()
211        {
212            let _ = p.tx.send(Err(Error::Disconnected));
213        }
214        self.confirm
215            .lock()
216            .unwrap_or_else(|e| e.into_inner())
217            .take();
218    }
219
220    /// Sends a request and waits for its response (or Error Response).
221    pub(crate) async fn request(
222        &self,
223        host: &Host,
224        conn: &ConnState,
225        pdu: Vec<u8>,
226    ) -> Result<Vec<u8>> {
227        let _one = self.client.lock().await;
228        let (tx, rx) = oneshot::channel();
229        *self.pending.lock().unwrap_or_else(|e| e.into_inner()) = Some(Pending {
230            request: pdu[0],
231            tx,
232        });
233        conn.send(host, cid::ATT, &pdu).await?;
234        match tokio::time::timeout(TRANSACTION_TIMEOUT, rx).await {
235            Ok(Ok(r)) => r,
236            Ok(Err(_)) => Err(Error::Disconnected),
237            Err(_) => {
238                // No further ATT traffic is allowed on this bearer.
239                self.pending
240                    .lock()
241                    .unwrap_or_else(|e| e.into_inner())
242                    .take();
243                Err(Error::Timeout("an ATT response"))
244            }
245        }
246    }
247
248    /// Sends a command (no response).
249    pub(crate) async fn command(&self, host: &Host, conn: &ConnState, pdu: &[u8]) -> Result<()> {
250        conn.send(host, cid::ATT, pdu).await
251    }
252
253    /// Sends an indication and waits for the confirmation.
254    pub(crate) async fn indicate(
255        &self,
256        host: &Host,
257        conn: &ConnState,
258        handle: u16,
259        value: &[u8],
260    ) -> Result<()> {
261        let _one = self.indications.lock().await;
262        let (tx, rx) = oneshot::channel();
263        *self.confirm.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx);
264        let mut pdu = vec![op::INDICATE];
265        pdu.extend_from_slice(&handle.to_le_bytes());
266        pdu.extend_from_slice(&value[..value.len().min(usize::from(self.mtu()) - 3)]);
267        conn.send(host, cid::ATT, &pdu).await?;
268        match tokio::time::timeout(TRANSACTION_TIMEOUT, rx).await {
269            Ok(Ok(())) => Ok(()),
270            Ok(Err(_)) => Err(Error::Disconnected),
271            Err(_) => Err(Error::Timeout("an indication's confirmation")),
272        }
273    }
274
275    /// Sends a notification, truncated to the MTU as the specification says.
276    pub(crate) async fn notify(
277        &self,
278        host: &Host,
279        conn: &ConnState,
280        handle: u16,
281        value: &[u8],
282    ) -> Result<()> {
283        let mut pdu = vec![op::NOTIFY];
284        pdu.extend_from_slice(&handle.to_le_bytes());
285        pdu.extend_from_slice(&value[..value.len().min(usize::from(self.mtu()) - 3)]);
286        conn.send(host, cid::ATT, &pdu).await
287    }
288
289    /// Exchanges the MTU (client side); returns the MTU in use.
290    pub(crate) async fn exchange_mtu(
291        &self,
292        host: &Host,
293        conn: &ConnState,
294        ours: u16,
295    ) -> Result<u16> {
296        let ours = ours.clamp(DEFAULT_MTU, MAX_MTU);
297        let mut pdu = vec![op::MTU_REQ];
298        pdu.extend_from_slice(&ours.to_le_bytes());
299        let rsp = self.request(host, conn, pdu).await?;
300        let theirs = match rsp.as_slice() {
301            [op::MTU_RSP, a, b] => u16::from_le_bytes([*a, *b]),
302            _ => return Err(Error::Protocol("malformed Exchange MTU Response".into())),
303        };
304        let m = ours.min(theirs).max(DEFAULT_MTU);
305        self.set_mtu(m);
306        self.mtu_exchanged.store(true, Ordering::Relaxed);
307        let _ = conn.events.send(ConnEvent::MtuExchanged(m));
308        Ok(m)
309    }
310}
311
312/// Whether an opcode is a response, and to which request.
313fn response_to(opcode: u8) -> Option<u8> {
314    match opcode {
315        op::MTU_RSP
316        | op::FIND_INFO_RSP
317        | op::FIND_BY_TYPE_RSP
318        | op::READ_BY_TYPE_RSP
319        | op::READ_RSP
320        | op::READ_BLOB_RSP
321        | op::READ_MULTIPLE_RSP
322        | op::READ_BY_GROUP_RSP
323        | op::WRITE_RSP
324        | op::PREPARE_WRITE_RSP
325        | op::EXECUTE_WRITE_RSP
326        | op::READ_MULTIPLE_VAR_RSP => Some(opcode - 1),
327        _ => None,
328    }
329}
330
331/// Reads one connection's ATT PDUs until it closes.
332pub(crate) async fn run(host: Host, conn: Arc<ConnState>, mut rx: mpsc::Receiver<Vec<u8>>) {
333    loop {
334        let pdu = tokio::select! {
335            p = rx.recv() => match p { Some(p) => p, None => return },
336            _ = conn.wait_closed() => return,
337        };
338        if let Err(e) = on_pdu(&host, &conn, pdu).await {
339            tracing::debug!("ATT on {:#05x}: {e}", conn.handle);
340        }
341    }
342}
343
344async fn on_pdu(host: &Host, conn: &Arc<ConnState>, pdu: Vec<u8>) -> Result<()> {
345    let Some(&opcode) = pdu.first() else {
346        return Ok(());
347    };
348    let bearer = &conn.att;
349    if opcode == op::ERROR_RSP {
350        if pdu.len() == 5 {
351            let (request, handle, code) = (pdu[1], u16::from_le_bytes([pdu[2], pdu[3]]), pdu[4]);
352            let mut p = bearer.pending.lock().unwrap_or_else(|e| e.into_inner());
353            if p.as_ref().is_some_and(|p| p.request == request) {
354                if let Some(p) = p.take() {
355                    let _ = p.tx.send(Err(Error::Att {
356                        request,
357                        handle,
358                        code,
359                    }));
360                }
361            }
362        }
363        return Ok(());
364    }
365    if let Some(request) = response_to(opcode) {
366        let mut p = bearer.pending.lock().unwrap_or_else(|e| e.into_inner());
367        if p.as_ref().is_some_and(|p| p.request == request) {
368            if let Some(p) = p.take() {
369                let _ = p.tx.send(Ok(pdu));
370            }
371        } else {
372            tracing::debug!("unexpected ATT response {opcode:#04x}");
373        }
374        return Ok(());
375    }
376    match opcode {
377        op::NOTIFY | op::INDICATE if pdu.len() >= 3 => {
378            let handle = u16::from_le_bytes([pdu[1], pdu[2]]);
379            let indication = opcode == op::INDICATE;
380            let _ = conn.events.send(ConnEvent::Notification {
381                handle,
382                value: pdu[3..].to_vec(),
383                indication,
384            });
385            if indication {
386                bearer.command(host, conn, &[op::CONFIRM]).await?;
387            }
388        }
389        op::MULTIPLE_NOTIFY => {
390            let mut rest = &pdu[1..];
391            while rest.len() >= 4 {
392                let handle = u16::from_le_bytes([rest[0], rest[1]]);
393                let len = usize::from(u16::from_le_bytes([rest[2], rest[3]]));
394                let Some(value) = rest.get(4..4 + len) else {
395                    break;
396                };
397                let _ = conn.events.send(ConnEvent::Notification {
398                    handle,
399                    value: value.to_vec(),
400                    indication: false,
401                });
402                rest = &rest[4 + len..];
403            }
404        }
405        op::CONFIRM => {
406            if let Some(tx) = bearer
407                .confirm
408                .lock()
409                .unwrap_or_else(|e| e.into_inner())
410                .take()
411            {
412                let _ = tx.send(());
413            }
414        }
415        op::MTU_REQ => {
416            let theirs = match pdu.as_slice() {
417                [_, a, b] => u16::from_le_bytes([*a, *b]),
418                _ => return send_error(host, conn, opcode, 0, ecode::INVALID_PDU).await,
419            };
420            let mut rsp = vec![op::MTU_RSP];
421            rsp.extend_from_slice(&MAX_MTU.to_le_bytes());
422            bearer.command(host, conn, &rsp).await?;
423            // The new MTU applies after the response is sent.
424            bearer.set_mtu(theirs.min(MAX_MTU));
425            bearer.mtu_exchanged.store(true, Ordering::Relaxed);
426            let _ = conn.events.send(ConnEvent::MtuExchanged(bearer.mtu()));
427        }
428        _ => {
429            let rsp = host.inner.gatt.handle(host, conn, &pdu).await;
430            if let Some(rsp) = rsp {
431                bearer.command(host, conn, &rsp).await?;
432            }
433        }
434    }
435    Ok(())
436}
437
438pub(crate) async fn send_error(
439    host: &Host,
440    conn: &ConnState,
441    request: u8,
442    handle: u16,
443    code: u8,
444) -> Result<()> {
445    conn.att
446        .command(host, conn, &error_pdu(request, handle, code))
447        .await
448}
449
450/// An Error Response PDU.
451pub(crate) fn error_pdu(request: u8, handle: u16, code: u8) -> Vec<u8> {
452    let h = handle.to_le_bytes();
453    vec![op::ERROR_RSP, request, h[0], h[1], code]
454}