Skip to main content

webbluetooth_linux/
att.rs

1//! The Attribute Protocol.
2//!
3//! ATT is what GATT is made of, and on Linux it is reachable directly: an
4//! L2CAP socket bound to the fixed ATT channel (CID 4) is a GATT connection,
5//! with the kernel establishing the LE link when the socket connects. No
6//! daemon, no D-Bus, no privileges.
7//!
8//! The protocol is small. Every PDU is an opcode byte and a payload, all
9//! little-endian, and every request gets exactly one response — the peer will
10//! not accept a second request until the first is answered, which is why a
11//! client has to serialise them.
12//!
13//! GATT's discovery procedures are built from four of them:
14//!
15//! | To find | Send | Over |
16//! |---|---|---|
17//! | primary services | `Read By Group Type` of `0x2800` | `0x0001..=0xFFFF` |
18//! | characteristics | `Read By Type` of `0x2803` | the service's handle range |
19//! | descriptors | `Find Information` | after the value handle |
20//! | a value | `Read` / `Read Blob` | one handle |
21//!
22//! Subscribing is not a protocol operation at all: you write `0x0001` to the
23//! characteristic's Client Characteristic Configuration descriptor, and
24//! notifications then arrive unsolicited as `Handle Value Notification`.
25
26/// ATT opcodes.
27pub mod opcode {
28    pub const ERROR_RESPONSE: u8 = 0x01;
29    pub const EXCHANGE_MTU_REQUEST: u8 = 0x02;
30    pub const EXCHANGE_MTU_RESPONSE: u8 = 0x03;
31    pub const FIND_INFORMATION_REQUEST: u8 = 0x04;
32    pub const FIND_INFORMATION_RESPONSE: u8 = 0x05;
33    pub const READ_BY_TYPE_REQUEST: u8 = 0x08;
34    pub const READ_BY_TYPE_RESPONSE: u8 = 0x09;
35    pub const READ_REQUEST: u8 = 0x0A;
36    pub const READ_RESPONSE: u8 = 0x0B;
37    pub const READ_BLOB_REQUEST: u8 = 0x0C;
38    pub const READ_BLOB_RESPONSE: u8 = 0x0D;
39    pub const READ_BY_GROUP_TYPE_REQUEST: u8 = 0x10;
40    pub const READ_BY_GROUP_TYPE_RESPONSE: u8 = 0x11;
41    pub const WRITE_REQUEST: u8 = 0x12;
42    pub const WRITE_RESPONSE: u8 = 0x13;
43    pub const PREPARE_WRITE_REQUEST: u8 = 0x16;
44    pub const PREPARE_WRITE_RESPONSE: u8 = 0x17;
45    pub const EXECUTE_WRITE_REQUEST: u8 = 0x18;
46    pub const EXECUTE_WRITE_RESPONSE: u8 = 0x19;
47    pub const WRITE_COMMAND: u8 = 0x52;
48    pub const HANDLE_VALUE_NOTIFICATION: u8 = 0x1B;
49    pub const HANDLE_VALUE_INDICATION: u8 = 0x1D;
50    pub const HANDLE_VALUE_CONFIRMATION: u8 = 0x1E;
51}
52
53/// GATT's own attribute types.
54pub mod gatt_type {
55    pub const PRIMARY_SERVICE: u16 = 0x2800;
56    pub const SECONDARY_SERVICE: u16 = 0x2801;
57    pub const INCLUDE: u16 = 0x2802;
58    pub const CHARACTERISTIC: u16 = 0x2803;
59    pub const CLIENT_CHARACTERISTIC_CONFIGURATION: u16 = 0x2902;
60}
61
62/// An ATT error code, as the peer reports it.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct AttError(pub u8);
65
66impl AttError {
67    pub const INVALID_HANDLE: u8 = 0x01;
68    pub const READ_NOT_PERMITTED: u8 = 0x02;
69    pub const WRITE_NOT_PERMITTED: u8 = 0x03;
70    pub const INSUFFICIENT_AUTHENTICATION: u8 = 0x05;
71    pub const REQUEST_NOT_SUPPORTED: u8 = 0x06;
72    pub const INVALID_OFFSET: u8 = 0x07;
73    pub const INSUFFICIENT_AUTHORIZATION: u8 = 0x08;
74    pub const ATTRIBUTE_NOT_FOUND: u8 = 0x0A;
75    pub const ATTRIBUTE_NOT_LONG: u8 = 0x0B;
76    pub const INVALID_ATTRIBUTE_VALUE_LENGTH: u8 = 0x0D;
77    pub const UNLIKELY_ERROR: u8 = 0x0E;
78    pub const INSUFFICIENT_ENCRYPTION: u8 = 0x0F;
79    pub const INSUFFICIENT_RESOURCES: u8 = 0x11;
80
81    /// `ATTRIBUTE_NOT_FOUND` ends a discovery loop rather than failing it —
82    /// it is how the peer says "no more".
83    pub fn is_end_of_discovery(self) -> bool {
84        self.0 == Self::ATTRIBUTE_NOT_FOUND
85    }
86
87    pub fn describe(self) -> &'static str {
88        match self.0 {
89            Self::INVALID_HANDLE => "invalid handle",
90            Self::READ_NOT_PERMITTED => "read not permitted",
91            Self::WRITE_NOT_PERMITTED => "write not permitted",
92            Self::INSUFFICIENT_AUTHENTICATION => "insufficient authentication",
93            Self::REQUEST_NOT_SUPPORTED => "request not supported",
94            Self::INVALID_OFFSET => "invalid offset",
95            Self::INSUFFICIENT_AUTHORIZATION => "insufficient authorization",
96            Self::ATTRIBUTE_NOT_FOUND => "attribute not found",
97            Self::ATTRIBUTE_NOT_LONG => "attribute not long",
98            Self::INVALID_ATTRIBUTE_VALUE_LENGTH => "invalid attribute value length",
99            Self::UNLIKELY_ERROR => "unlikely error",
100            Self::INSUFFICIENT_ENCRYPTION => "insufficient encryption",
101            Self::INSUFFICIENT_RESOURCES => "insufficient resources",
102            _ => "unknown ATT error",
103        }
104    }
105}
106
107impl std::fmt::Display for AttError {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        write!(f, "{} (0x{:02x})", self.describe(), self.0)
110    }
111}
112
113/// A 16- or 128-bit attribute type, as it appears on the wire.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum Uuid {
116    Short(u16),
117    Long([u8; 16]),
118}
119
120impl Uuid {
121    /// Decode from wire bytes: 2 for a short UUID, 16 for a long one.
122    ///
123    /// Both go out least-significant byte first, so a 128-bit UUID on the wire
124    /// is the reverse of how it is written.
125    pub fn parse(bytes: &[u8]) -> Option<Self> {
126        match bytes.len() {
127            2 => Some(Self::Short(u16::from_le_bytes([bytes[0], bytes[1]]))),
128            16 => {
129                let mut be = [0u8; 16];
130                for (i, b) in bytes.iter().enumerate() {
131                    be[15 - i] = *b;
132                }
133                Some(Self::Long(be))
134            }
135            _ => None,
136        }
137    }
138
139    /// Encode to wire bytes, least-significant first.
140    pub fn to_wire(&self) -> Vec<u8> {
141        match self {
142            Self::Short(v) => v.to_le_bytes().to_vec(),
143            Self::Long(be) => be.iter().rev().copied().collect(),
144        }
145    }
146
147    /// The canonical 128-bit lowercase string, expanding the Bluetooth base
148    /// UUID for short forms.
149    pub fn to_canonical(&self) -> String {
150        let bytes = match self {
151            Self::Short(v) => {
152                let mut b = [
153                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F,
154                    0x9B, 0x34, 0xFB,
155                ];
156                b[2] = (*v >> 8) as u8;
157                b[3] = *v as u8;
158                b
159            }
160            Self::Long(b) => *b,
161        };
162        let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
163        format!(
164            "{}-{}-{}-{}-{}",
165            &hex[0..8],
166            &hex[8..12],
167            &hex[12..16],
168            &hex[16..20],
169            &hex[20..32]
170        )
171    }
172}
173
174/// A discovered primary service.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct Service {
177    pub start_handle: u16,
178    pub end_handle: u16,
179    pub uuid: Uuid,
180}
181
182/// A discovered characteristic.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct Characteristic {
185    /// The handle of the characteristic *declaration*.
186    pub handle: u16,
187    /// The handle its value lives at — what reads and writes address.
188    pub value_handle: u16,
189    pub properties: u8,
190    pub uuid: Uuid,
191}
192
193/// A discovered descriptor.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct Descriptor {
196    pub handle: u16,
197    pub uuid: Uuid,
198}
199
200// ── Encoding requests ───────────────────────────────────────────────────────
201
202pub fn exchange_mtu_request(mtu: u16) -> Vec<u8> {
203    let mut pdu = vec![opcode::EXCHANGE_MTU_REQUEST];
204    pdu.extend_from_slice(&mtu.to_le_bytes());
205    pdu
206}
207
208pub fn read_by_group_type_request(start: u16, end: u16, group_type: u16) -> Vec<u8> {
209    let mut pdu = vec![opcode::READ_BY_GROUP_TYPE_REQUEST];
210    pdu.extend_from_slice(&start.to_le_bytes());
211    pdu.extend_from_slice(&end.to_le_bytes());
212    pdu.extend_from_slice(&group_type.to_le_bytes());
213    pdu
214}
215
216pub fn read_by_type_request(start: u16, end: u16, attribute_type: u16) -> Vec<u8> {
217    let mut pdu = vec![opcode::READ_BY_TYPE_REQUEST];
218    pdu.extend_from_slice(&start.to_le_bytes());
219    pdu.extend_from_slice(&end.to_le_bytes());
220    pdu.extend_from_slice(&attribute_type.to_le_bytes());
221    pdu
222}
223
224pub fn find_information_request(start: u16, end: u16) -> Vec<u8> {
225    let mut pdu = vec![opcode::FIND_INFORMATION_REQUEST];
226    pdu.extend_from_slice(&start.to_le_bytes());
227    pdu.extend_from_slice(&end.to_le_bytes());
228    pdu
229}
230
231pub fn read_request(handle: u16) -> Vec<u8> {
232    let mut pdu = vec![opcode::READ_REQUEST];
233    pdu.extend_from_slice(&handle.to_le_bytes());
234    pdu
235}
236
237pub fn read_blob_request(handle: u16, offset: u16) -> Vec<u8> {
238    let mut pdu = vec![opcode::READ_BLOB_REQUEST];
239    pdu.extend_from_slice(&handle.to_le_bytes());
240    pdu.extend_from_slice(&offset.to_le_bytes());
241    pdu
242}
243
244pub fn write_request(handle: u16, value: &[u8]) -> Vec<u8> {
245    let mut pdu = vec![opcode::WRITE_REQUEST];
246    pdu.extend_from_slice(&handle.to_le_bytes());
247    pdu.extend_from_slice(value);
248    pdu
249}
250
251/// A write with no response. The peer never acknowledges it, so there is
252/// nothing to wait for and nothing to learn if it is dropped.
253/// `Prepare Write Request` — one fragment of a value too long for one write.
254///
255/// The peer queues the fragment and echoes it back; nothing is applied until
256/// [`execute_write_request`]. `offset` is the position within the attribute,
257/// so the fragments together spell the whole value.
258pub fn prepare_write_request(handle: u16, offset: u16, value: &[u8]) -> Vec<u8> {
259    let mut pdu = Vec::with_capacity(5 + value.len());
260    pdu.push(opcode::PREPARE_WRITE_REQUEST);
261    pdu.extend_from_slice(&handle.to_le_bytes());
262    pdu.extend_from_slice(&offset.to_le_bytes());
263    pdu.extend_from_slice(value);
264    pdu
265}
266
267/// `Execute Write Request` — apply the queued fragments, or discard them.
268pub fn execute_write_request(apply: bool) -> Vec<u8> {
269    vec![opcode::EXECUTE_WRITE_REQUEST, u8::from(apply)]
270}
271
272/// `Exchange MTU Response` — our answer when the *peer* opens the exchange.
273pub fn exchange_mtu_response(mtu: u16) -> Vec<u8> {
274    let mut pdu = Vec::with_capacity(3);
275    pdu.push(opcode::EXCHANGE_MTU_RESPONSE);
276    pdu.extend_from_slice(&mtu.to_le_bytes());
277    pdu
278}
279
280/// `Error Response` — how a server declines a request it will not serve.
281pub fn error_response(request: u8, handle: u16, error: AttError) -> Vec<u8> {
282    let mut pdu = Vec::with_capacity(5);
283    pdu.push(opcode::ERROR_RESPONSE);
284    pdu.push(request);
285    pdu.extend_from_slice(&handle.to_le_bytes());
286    pdu.push(error.0);
287    pdu
288}
289
290/// Is this opcode a request the *peer* is making of us?
291///
292/// ATT numbers requests even and responses odd, but not uniformly, and both
293/// travel the same connection: a client that treats every inbound PDU as the
294/// reply to its own outstanding request will consume the peer's questions as
295/// answers. Commands (bit 6) and notifications are excluded — they need no
296/// reply and are handled elsewhere.
297pub fn is_peer_request(opcode: u8) -> bool {
298    matches!(
299        opcode,
300        opcode::EXCHANGE_MTU_REQUEST
301            | opcode::FIND_INFORMATION_REQUEST
302            | opcode::READ_BY_TYPE_REQUEST
303            | opcode::READ_REQUEST
304            | opcode::READ_BLOB_REQUEST
305            | opcode::READ_BY_GROUP_TYPE_REQUEST
306            | opcode::WRITE_REQUEST
307            | opcode::PREPARE_WRITE_REQUEST
308            | opcode::EXECUTE_WRITE_REQUEST
309    )
310}
311
312pub fn write_command(handle: u16, value: &[u8]) -> Vec<u8> {
313    let mut pdu = vec![opcode::WRITE_COMMAND];
314    pdu.extend_from_slice(&handle.to_le_bytes());
315    pdu.extend_from_slice(value);
316    pdu
317}
318
319pub fn handle_value_confirmation() -> Vec<u8> {
320    vec![opcode::HANDLE_VALUE_CONFIRMATION]
321}
322
323// ── Decoding responses ──────────────────────────────────────────────────────
324
325/// One `Include` declaration: a service pointing at another service.
326///
327/// `uuid` is absent when the included service has a 128-bit UUID, which does
328/// not fit the declaration — the UUID then has to be read from the included
329/// service's own declaration.
330#[derive(Debug, Clone, PartialEq)]
331pub struct Include {
332    /// Where the declaration itself lives.
333    pub handle: u16,
334    /// The included service's first handle.
335    pub start_handle: u16,
336    /// Its last handle.
337    pub end_handle: u16,
338    pub uuid: Option<Uuid>,
339}
340
341/// What came back.
342#[derive(Debug, Clone, PartialEq)]
343pub enum Response {
344    /// The peer refused. `opcode` is the request it refused.
345    Error {
346        opcode: u8,
347        handle: u16,
348        error: AttError,
349    },
350    Mtu(u16),
351    Services(Vec<Service>),
352    Characteristics(Vec<Characteristic>),
353    Includes(Vec<Include>),
354    Descriptors(Vec<Descriptor>),
355    Value(Vec<u8>),
356    WriteComplete,
357    /// Unsolicited: a subscription delivering a value.
358    Notification {
359        handle: u16,
360        value: Vec<u8>,
361    },
362    /// Unsolicited, and must be confirmed.
363    Indication {
364        handle: u16,
365        value: Vec<u8>,
366    },
367    /// One fragment of a long write was queued by the peer.
368    PrepareWriteComplete,
369    /// The peer is making a request of us, which is not a reply to anything.
370    PeerRequest {
371        opcode: u8,
372        body: Vec<u8>,
373    },
374    /// An opcode this client does not implement.
375    Unknown(u8),
376}
377
378/// Decode one PDU.
379pub fn parse(pdu: &[u8]) -> Option<Response> {
380    let opcode = *pdu.first()?;
381    let body = &pdu[1..];
382    Some(match opcode {
383        opcode::ERROR_RESPONSE => {
384            if body.len() < 4 {
385                return None;
386            }
387            Response::Error {
388                opcode: body[0],
389                handle: u16::from_le_bytes([body[1], body[2]]),
390                error: AttError(body[3]),
391            }
392        }
393
394        opcode::EXCHANGE_MTU_RESPONSE => {
395            if body.len() < 2 {
396                return None;
397            }
398            Response::Mtu(u16::from_le_bytes([body[0], body[1]]))
399        }
400
401        // The peer asking *us* something. Kept separate from every reply so it
402        // can never be mistaken for one.
403        op if is_peer_request(op) => Response::PeerRequest {
404            opcode: op,
405            body: body.to_vec(),
406        },
407
408        // A prepared fragment is echoed back; the echo is only an
409        // acknowledgement, so the contents are not needed.
410        opcode::PREPARE_WRITE_RESPONSE => Response::PrepareWriteComplete,
411        opcode::EXECUTE_WRITE_RESPONSE => Response::WriteComplete,
412
413        // Each entry is `length` bytes: handle, end-group handle, then the UUID.
414        opcode::READ_BY_GROUP_TYPE_RESPONSE => {
415            let length = *body.first()? as usize;
416            if length < 6 {
417                return None;
418            }
419            let mut services = Vec::new();
420            for entry in body[1..].chunks(length) {
421                if entry.len() < length {
422                    break;
423                }
424                let Some(uuid) = Uuid::parse(&entry[4..length]) else {
425                    break;
426                };
427                services.push(Service {
428                    start_handle: u16::from_le_bytes([entry[0], entry[1]]),
429                    end_handle: u16::from_le_bytes([entry[2], entry[3]]),
430                    uuid,
431                });
432            }
433            Response::Services(services)
434        }
435
436        // Each entry: declaration handle, then the declaration value —
437        // properties byte, value handle, UUID.
438        // `Read By Type Response` does not say which type it answered, and the
439        // two declarations this client asks for arrive on the same opcode. GATT
440        // gives them non-overlapping entry lengths, which is the only
441        // discriminator there is:
442        //
443        //   characteristic: handle + properties + value handle + UUID = 7 or 21
444        //   include:        handle + start + end [+ 16-bit UUID]      = 6 or 8
445        //
446        // A 128-bit included service has no UUID in its declaration, which is
447        // why the 6-byte form exists; the caller reads it from the service
448        // itself.
449        opcode::READ_BY_TYPE_RESPONSE if matches!(*body.first()?, 6 | 8) => {
450            let length = *body.first()? as usize;
451            let mut includes = Vec::new();
452            for entry in body[1..].chunks(length) {
453                if entry.len() < length {
454                    break;
455                }
456                includes.push(Include {
457                    handle: u16::from_le_bytes([entry[0], entry[1]]),
458                    start_handle: u16::from_le_bytes([entry[2], entry[3]]),
459                    end_handle: u16::from_le_bytes([entry[4], entry[5]]),
460                    uuid: if length == 8 {
461                        Uuid::parse(&entry[6..8])
462                    } else {
463                        None
464                    },
465                });
466            }
467            Response::Includes(includes)
468        }
469
470        opcode::READ_BY_TYPE_RESPONSE => {
471            let length = *body.first()? as usize;
472            if length < 7 {
473                return None;
474            }
475            let mut characteristics = Vec::new();
476            for entry in body[1..].chunks(length) {
477                if entry.len() < length {
478                    break;
479                }
480                let Some(uuid) = Uuid::parse(&entry[5..length]) else {
481                    break;
482                };
483                characteristics.push(Characteristic {
484                    handle: u16::from_le_bytes([entry[0], entry[1]]),
485                    properties: entry[2],
486                    value_handle: u16::from_le_bytes([entry[3], entry[4]]),
487                    uuid,
488                });
489            }
490            Response::Characteristics(characteristics)
491        }
492
493        // Format 1 is 16-bit UUIDs, format 2 is 128-bit.
494        opcode::FIND_INFORMATION_RESPONSE => {
495            let format = *body.first()?;
496            let uuid_len = match format {
497                0x01 => 2,
498                0x02 => 16,
499                _ => return None,
500            };
501            let entry_len = 2 + uuid_len;
502            let mut descriptors = Vec::new();
503            for entry in body[1..].chunks(entry_len) {
504                if entry.len() < entry_len {
505                    break;
506                }
507                let Some(uuid) = Uuid::parse(&entry[2..entry_len]) else {
508                    break;
509                };
510                descriptors.push(Descriptor {
511                    handle: u16::from_le_bytes([entry[0], entry[1]]),
512                    uuid,
513                });
514            }
515            Response::Descriptors(descriptors)
516        }
517
518        opcode::READ_RESPONSE | opcode::READ_BLOB_RESPONSE => Response::Value(body.to_vec()),
519        opcode::WRITE_RESPONSE => Response::WriteComplete,
520
521        opcode::HANDLE_VALUE_NOTIFICATION => {
522            if body.len() < 2 {
523                return None;
524            }
525            Response::Notification {
526                handle: u16::from_le_bytes([body[0], body[1]]),
527                value: body[2..].to_vec(),
528            }
529        }
530
531        opcode::HANDLE_VALUE_INDICATION => {
532            if body.len() < 2 {
533                return None;
534            }
535            Response::Indication {
536                handle: u16::from_le_bytes([body[0], body[1]]),
537                value: body[2..].to_vec(),
538            }
539        }
540
541        other => Response::Unknown(other),
542    })
543}
544
545/// Whether a PDU arrived unprompted, and so must not be matched to a request.
546pub fn is_unsolicited(opcode: u8) -> bool {
547    matches!(
548        opcode,
549        opcode::HANDLE_VALUE_NOTIFICATION | opcode::HANDLE_VALUE_INDICATION
550    )
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    #[test]
558    fn short_uuids_expand_to_the_bluetooth_base() {
559        assert_eq!(
560            Uuid::Short(0x180D).to_canonical(),
561            "0000180d-0000-1000-8000-00805f9b34fb"
562        );
563        assert_eq!(
564            Uuid::Short(0x2A37).to_canonical(),
565            "00002a37-0000-1000-8000-00805f9b34fb"
566        );
567    }
568
569    #[test]
570    fn uuids_go_on_the_wire_least_significant_first() {
571        assert_eq!(Uuid::Short(0x180D).to_wire(), vec![0x0D, 0x18]);
572        assert_eq!(Uuid::parse(&[0x0D, 0x18]), Some(Uuid::Short(0x180D)));
573
574        // A 128-bit UUID is the written order reversed.
575        let nordic_uart = [
576            0x6E, 0x40, 0x00, 0x01, 0xB5, 0xA3, 0xF3, 0x93, 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC,
577            0xCA, 0x9E,
578        ];
579        let long = Uuid::Long(nordic_uart);
580        assert_eq!(long.to_canonical(), "6e400001-b5a3-f393-e0a9-e50e24dcca9e");
581        let wire = long.to_wire();
582        assert_eq!(wire[0], 0x9E, "wire order must be reversed");
583        assert_eq!(Uuid::parse(&wire), Some(long));
584    }
585
586    #[test]
587    fn a_bad_uuid_length_is_rejected() {
588        assert_eq!(Uuid::parse(&[]), None);
589        assert_eq!(Uuid::parse(&[1, 2, 3]), None);
590    }
591
592    #[test]
593    fn requests_encode_little_endian() {
594        assert_eq!(read_request(0x0025), vec![0x0A, 0x25, 0x00]);
595        assert_eq!(write_command(0x0012, &[0xAB]), vec![0x52, 0x12, 0x00, 0xAB]);
596    }
597
598    /// `Read By Type Response` does not name the type it answered, and both
599    /// declarations this client asks for share the opcode. The entry length is
600    /// the only thing that distinguishes them, and GATT is careful to make the
601    /// two sets disjoint — 6 or 8 for an include, 7 or 21 for a characteristic.
602    #[test]
603    fn an_include_declaration_is_not_read_as_a_characteristic() {
604        // 8-byte entries: declaration handle, start, end, 16-bit UUID.
605        let pdu = [
606            0x09, 0x08, // response, entry length 8
607            0x02, 0x00, // declaration at 0x0002
608            0x10, 0x00, // included service starts at 0x0010
609            0x1F, 0x00, // …and ends at 0x001F
610            0x0F, 0x18, // UUID 0x180F
611        ];
612        assert_eq!(
613            parse(&pdu),
614            Some(Response::Includes(vec![Include {
615                handle: 0x0002,
616                start_handle: 0x0010,
617                end_handle: 0x001F,
618                uuid: Some(Uuid::Short(0x180F)),
619            }]))
620        );
621    }
622
623    /// A 128-bit included service does not fit its declaration, so the UUID is
624    /// absent and the caller has to read it from the service itself. Returning
625    /// a wrong UUID here instead of `None` would name the wrong service.
626    #[test]
627    fn a_six_byte_include_has_no_uuid_to_give() {
628        let pdu = [
629            0x09, 0x06, // response, entry length 6
630            0x02, 0x00, 0x10, 0x00, 0x1F, 0x00,
631        ];
632        let Some(Response::Includes(includes)) = parse(&pdu) else {
633            panic!("expected includes");
634        };
635        assert_eq!(includes.len(), 1);
636        assert_eq!(includes[0].start_handle, 0x0010);
637        assert!(
638            includes[0].uuid.is_none(),
639            "a 6-byte declaration carries no UUID"
640        );
641    }
642
643    #[test]
644    fn a_characteristic_declaration_still_parses_as_one() {
645        // 7-byte entries keep their old meaning.
646        let pdu = [
647            0x09, 0x07, // response, entry length 7
648            0x03, 0x00, // declaration at 0x0003
649            0x12, // read | write
650            0x04, 0x00, // value handle 0x0004
651            0x19, 0x2A, // UUID 0x2A19
652        ];
653        let Some(Response::Characteristics(found)) = parse(&pdu) else {
654            panic!("expected characteristics");
655        };
656        assert_eq!(found.len(), 1);
657        assert_eq!(found[0].value_handle, 0x0004);
658        assert_eq!(found[0].uuid, Uuid::Short(0x2A19));
659    }
660
661    #[test]
662    fn several_includes_come_back_in_one_response() {
663        let pdu = [
664            0x09, 0x08, //
665            0x02, 0x00, 0x10, 0x00, 0x1F, 0x00, 0x0F, 0x18, //
666            0x03, 0x00, 0x20, 0x00, 0x2F, 0x00, 0x0D, 0x18,
667        ];
668        let Some(Response::Includes(includes)) = parse(&pdu) else {
669            panic!("expected includes");
670        };
671        assert_eq!(includes.len(), 2);
672        assert_eq!(includes[1].uuid, Some(Uuid::Short(0x180D)));
673        assert_eq!(includes[1].end_handle, 0x002F);
674    }
675
676    #[test]
677    fn a_truncated_include_entry_is_dropped_not_guessed() {
678        // Entry length claims 8, only 5 bytes follow.
679        let pdu = [0x09, 0x08, 0x02, 0x00, 0x10, 0x00, 0x1F];
680        assert_eq!(parse(&pdu), Some(Response::Includes(vec![])));
681    }
682
683    #[test]
684    fn long_writes_encode_offset_and_commit() {
685        assert_eq!(
686            prepare_write_request(0x0012, 0x0014, &[0xAA, 0xBB]),
687            vec![0x16, 0x12, 0x00, 0x14, 0x00, 0xAA, 0xBB]
688        );
689        assert_eq!(execute_write_request(true), vec![0x18, 0x01]);
690        // Abandoning a queue is the same request with the flag cleared, which
691        // is how a half-sent value is prevented from being committed.
692        assert_eq!(execute_write_request(false), vec![0x18, 0x00]);
693    }
694
695    #[test]
696    fn a_prepared_write_echo_is_only_an_acknowledgement() {
697        // The peer echoes handle, offset and value; none of it is needed.
698        let echoed = [0x17, 0x12, 0x00, 0x14, 0x00, 0xAA, 0xBB];
699        assert_eq!(parse(&echoed), Some(Response::PrepareWriteComplete));
700        assert_eq!(parse(&[0x19]), Some(Response::WriteComplete));
701    }
702
703    #[test]
704    fn the_peers_own_requests_are_not_replies() {
705        // BlueZ opens with this, and treating it as the answer to our own
706        // Exchange MTU Request is how a client ends up with the wrong MTU and
707        // a peer waiting forever for a response.
708        let request = [0x02, 0x17, 0x02];
709        assert_eq!(
710            parse(&request),
711            Some(Response::PeerRequest {
712                opcode: 0x02,
713                body: vec![0x17, 0x02],
714            })
715        );
716        // The response form still parses as ours.
717        assert_eq!(parse(&[0x03, 0x17, 0x02]), Some(Response::Mtu(0x0217)));
718
719        for op in [0x04u8, 0x08, 0x0A, 0x0C, 0x10, 0x12, 0x16, 0x18] {
720            assert!(is_peer_request(op), "{op:#04x} should be a peer request");
721        }
722        // Responses, commands and notifications are not requests of us.
723        for op in [0x01u8, 0x03, 0x05, 0x0B, 0x11, 0x13, 0x1B, 0x1D, 0x52] {
724            assert!(!is_peer_request(op), "{op:#04x} is not a peer request");
725        }
726    }
727
728    #[test]
729    fn declining_a_request_names_it() {
730        let pdu = error_response(0x0A, 0x0021, AttError(AttError::REQUEST_NOT_SUPPORTED));
731        assert_eq!(pdu, vec![0x01, 0x0A, 0x21, 0x00, 0x06]);
732        assert_eq!(exchange_mtu_response(517), vec![0x03, 0x05, 0x02]);
733        assert_eq!(
734            read_by_group_type_request(0x0001, 0xFFFF, gatt_type::PRIMARY_SERVICE),
735            vec![0x10, 0x01, 0x00, 0xFF, 0xFF, 0x00, 0x28]
736        );
737        assert_eq!(exchange_mtu_request(517), vec![0x02, 0x05, 0x02]);
738    }
739
740    #[test]
741    fn an_error_response_decodes() {
742        // The peer refused a read of handle 0x0025: read not permitted.
743        let pdu = [0x01, 0x0A, 0x25, 0x00, 0x02];
744        assert_eq!(
745            parse(&pdu),
746            Some(Response::Error {
747                opcode: opcode::READ_REQUEST,
748                handle: 0x0025,
749                error: AttError(AttError::READ_NOT_PERMITTED),
750            })
751        );
752    }
753
754    #[test]
755    fn attribute_not_found_ends_discovery_rather_than_failing_it() {
756        // Every discovery loop runs until the peer says this.
757        assert!(AttError(AttError::ATTRIBUTE_NOT_FOUND).is_end_of_discovery());
758        assert!(!AttError(AttError::READ_NOT_PERMITTED).is_end_of_discovery());
759    }
760
761    #[test]
762    fn a_service_discovery_response_decodes() {
763        // Two services, 16-bit UUIDs: entry length 6.
764        let pdu = [
765            0x11, 0x06, //
766            0x01, 0x00, 0x09, 0x00, 0x00, 0x18, // 0x0001..0x0009 Generic Access
767            0x0A, 0x00, 0x0F, 0x00, 0x0D, 0x18, // 0x000A..0x000F Heart Rate
768        ];
769        let Some(Response::Services(services)) = parse(&pdu) else {
770            panic!("not a service response");
771        };
772        assert_eq!(services.len(), 2);
773        assert_eq!(services[1].start_handle, 0x000A);
774        assert_eq!(services[1].end_handle, 0x000F);
775        assert_eq!(
776            services[1].uuid.to_canonical(),
777            "0000180d-0000-1000-8000-00805f9b34fb"
778        );
779    }
780
781    #[test]
782    fn a_characteristic_discovery_response_decodes() {
783        // Entry length 7: handle, properties, value handle, 16-bit UUID.
784        let pdu = [
785            0x09, 0x07, //
786            0x0B, 0x00, 0x10, 0x0C, 0x00, 0x37, 0x2A, // notify, value at 0x000C
787        ];
788        let Some(Response::Characteristics(chars)) = parse(&pdu) else {
789            panic!("not a characteristic response");
790        };
791        assert_eq!(chars.len(), 1);
792        assert_eq!(chars[0].handle, 0x000B);
793        assert_eq!(
794            chars[0].value_handle, 0x000C,
795            "reads address the value handle"
796        );
797        assert_eq!(chars[0].properties, 0x10);
798        assert_eq!(
799            chars[0].uuid.to_canonical(),
800            "00002a37-0000-1000-8000-00805f9b34fb"
801        );
802    }
803
804    #[test]
805    fn descriptor_discovery_decodes_both_formats() {
806        // Format 1: 16-bit UUIDs.
807        let short = [0x05, 0x01, 0x0D, 0x00, 0x02, 0x29];
808        let Some(Response::Descriptors(d)) = parse(&short) else {
809            panic!()
810        };
811        assert_eq!(d.len(), 1);
812        assert_eq!(d[0].handle, 0x000D);
813        assert_eq!(d[0].uuid, Uuid::Short(0x2902));
814
815        // Format 2: 128-bit.
816        let mut long = vec![0x05, 0x02, 0x0E, 0x00];
817        long.extend_from_slice(&Uuid::Short(0x2902).to_wire());
818        long.extend_from_slice(&[0; 14]);
819        let Some(Response::Descriptors(d)) = parse(&long) else {
820            panic!()
821        };
822        assert_eq!(d[0].handle, 0x000E);
823
824        // An unknown format is rejected rather than misread.
825        assert_eq!(parse(&[0x05, 0x03, 0x00, 0x00]), None);
826    }
827
828    #[test]
829    fn notifications_are_recognised_as_unsolicited() {
830        let pdu = [0x1B, 0x0C, 0x00, 0x00, 0x48];
831        assert_eq!(
832            parse(&pdu),
833            Some(Response::Notification {
834                handle: 0x000C,
835                value: vec![0x00, 0x48]
836            })
837        );
838        assert!(is_unsolicited(opcode::HANDLE_VALUE_NOTIFICATION));
839        assert!(is_unsolicited(opcode::HANDLE_VALUE_INDICATION));
840        // A read response is a reply and must be matched to its request.
841        assert!(!is_unsolicited(opcode::READ_RESPONSE));
842    }
843
844    #[test]
845    fn truncated_pdus_are_rejected_rather_than_misread() {
846        // Every one of these is reachable from a hostile or broken peer.
847        assert_eq!(parse(&[]), None);
848        assert_eq!(parse(&[0x01, 0x0A]), None);
849        assert_eq!(parse(&[0x03]), None);
850        assert_eq!(parse(&[0x1B, 0x0C]), None);
851        // An entry length smaller than the fixed fields would underflow.
852        assert_eq!(parse(&[0x11, 0x02, 0x00, 0x00]), None);
853        assert_eq!(parse(&[0x09, 0x03, 0x00, 0x00]), None);
854    }
855
856    #[test]
857    fn a_trailing_partial_entry_is_dropped_not_decoded() {
858        // Three and a half entries: the half must not become a bogus service.
859        let pdu = [0x11, 0x06, 0x01, 0x00, 0x09, 0x00, 0x00, 0x18, 0x0A, 0x00];
860        let Some(Response::Services(services)) = parse(&pdu) else {
861            panic!()
862        };
863        assert_eq!(services.len(), 1);
864    }
865}