Skip to main content

bluetooth_host/gatt/
server.rs

1//! Our GATT server: a database built at run time (services can be added and
2//! removed while running), with per-attribute security, client
3//! configuration per connection (kept across reconnections for bonded
4//! peers), long writes, and the GATT service's Service Changed and
5//! Database Hash so clients can cache.
6
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex};
9
10use bluetooth_adv::Uuid;
11use serde::{Deserialize, Serialize};
12
13use super::{uuid, uuid_bytes, Properties};
14use crate::att::{ecode, error_pdu, op};
15use crate::connection::{ConnState, Security};
16use crate::error::{Error, Result};
17use crate::host::{Host, HostEvent};
18
19/// Who may read or write an attribute.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
21#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
22#[serde(rename_all = "snake_case")]
23pub enum Access {
24    /// Nobody.
25    Never,
26    /// Anyone connected.
27    #[default]
28    Open,
29    /// An encrypted link.
30    Encrypted,
31    /// An encrypted link with an authenticated (MITM-protected) key.
32    Authenticated,
33    /// Authenticated LE Secure Connections with a 128-bit key.
34    SecureConnections,
35}
36
37impl Access {
38    /// `None` when allowed, else the ATT error to return.
39    fn check(self, s: &Security) -> Option<u8> {
40        match self {
41            Access::Never => Some(0), // replaced by the caller with read/write-not-permitted
42            Access::Open => None,
43            Access::Encrypted if s.encrypted => None,
44            Access::Authenticated if s.encrypted && s.authenticated => None,
45            Access::SecureConnections if s.level() == 4 => None,
46            // Without encryption the client should pair (or encrypt with its bond).
47            _ if !s.encrypted => Some(ecode::INSUFFICIENT_AUTHENTICATION),
48            _ if s.key_size < 16 && self == Access::SecureConnections => {
49                Some(ecode::KEY_SIZE_TOO_SHORT)
50            }
51            _ => Some(ecode::INSUFFICIENT_AUTHENTICATION),
52        }
53    }
54}
55
56/// A descriptor to add.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59pub struct DescriptorDef {
60    /// Its UUID.
61    #[cfg_attr(feature = "schema", schemars(with = "String"))]
62    pub uuid: Uuid,
63    /// Read access.
64    #[serde(default)]
65    pub read: Access,
66    /// Write access.
67    #[serde(default = "never")]
68    pub write: Access,
69    /// The value.
70    #[serde(default, with = "hex_bytes")]
71    #[cfg_attr(feature = "schema", schemars(with = "String"))]
72    pub value: Vec<u8>,
73}
74
75fn never() -> Access {
76    Access::Never
77}
78
79/// A characteristic to add.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
82pub struct CharacteristicDef {
83    /// Its UUID.
84    #[cfg_attr(feature = "schema", schemars(with = "String"))]
85    pub uuid: Uuid,
86    /// Its properties, by name: `read`, `write`, `write_without_response`,
87    /// `notify`, `indicate`, `broadcast`.
88    pub properties: Vec<String>,
89    /// Read access.
90    #[serde(default)]
91    pub read: Access,
92    /// Write access.
93    #[serde(default)]
94    pub write: Access,
95    /// The initial value.
96    #[serde(default, with = "hex_bytes")]
97    #[cfg_attr(feature = "schema", schemars(with = "String"))]
98    pub value: Vec<u8>,
99    /// The longest value a client may write (at most 512).
100    #[serde(default = "max_len")]
101    pub max_len: usize,
102    /// A Characteristic User Description.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub description: Option<String>,
105    /// Other descriptors.
106    #[serde(default, skip_serializing_if = "Vec::is_empty")]
107    pub descriptors: Vec<DescriptorDef>,
108}
109
110fn max_len() -> usize {
111    512
112}
113
114/// A service to add.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
117pub struct ServiceDef {
118    /// Its UUID.
119    #[cfg_attr(feature = "schema", schemars(with = "String"))]
120    pub uuid: Uuid,
121    /// Primary (the default) or secondary.
122    #[serde(default = "yes")]
123    pub primary: bool,
124    /// Its characteristics.
125    pub characteristics: Vec<CharacteristicDef>,
126}
127
128fn yes() -> bool {
129    true
130}
131
132mod hex_bytes {
133    pub fn serialize<S: serde::Serializer>(v: &[u8], s: S) -> Result<S::Ok, S::Error> {
134        s.serialize_str(&hex::encode(v))
135    }
136    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
137        let s = <String as serde::Deserialize>::deserialize(d)?;
138        hex::decode(s.trim()).map_err(serde::de::Error::custom)
139    }
140}
141
142/// The handles of an added service.
143#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
144pub struct ServiceHandles {
145    /// The service declaration.
146    pub start: u16,
147    /// The last handle.
148    pub end: u16,
149    /// Each characteristic's value handle, in the order given.
150    pub characteristics: Vec<(Uuid, u16)>,
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154enum Kind {
155    Service,
156    Declaration,
157    Value {
158        props: Properties,
159        max_len: usize,
160        cccd: Option<u16>,
161    },
162    Cccd {
163        value: u16,
164    },
165    Descriptor,
166}
167
168#[derive(Debug, Clone)]
169struct Attr {
170    handle: u16,
171    ty: Uuid,
172    kind: Kind,
173    read: Access,
174    write: Access,
175    value: Vec<u8>,
176    /// The service this attribute belongs to (its declaration's handle).
177    service: u16,
178}
179
180struct Db {
181    attrs: Vec<Attr>,
182    /// Client configuration: (connection handle, value handle) -> bits.
183    cccd: HashMap<(u16, u16), u16>,
184    /// Queued prepared writes, per connection.
185    prepared: HashMap<u16, Vec<(u16, u16, Vec<u8>)>>,
186    service_changed: u16,
187    hash_handle: u16,
188}
189
190/// The server's attribute database.
191pub struct Database {
192    db: Mutex<Db>,
193}
194
195/// Prepared writes a client may queue before executing.
196const MAX_PREPARED: usize = 64;
197
198impl Database {
199    pub(crate) fn new(name: &str, appearance: u16) -> Self {
200        let d = Database {
201            db: Mutex::new(Db {
202                attrs: Vec::new(),
203                cccd: HashMap::new(),
204                prepared: HashMap::new(),
205                service_changed: 0,
206                hash_handle: 0,
207            }),
208        };
209        let p = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
210        d.add(&ServiceDef {
211            uuid: Uuid::Uuid16(uuid::GAP),
212            primary: true,
213            characteristics: vec![
214                CharacteristicDef {
215                    uuid: Uuid::Uuid16(uuid::DEVICE_NAME),
216                    properties: p(&["read"]),
217                    read: Access::Open,
218                    write: Access::Never,
219                    value: name.as_bytes().to_vec(),
220                    max_len: 248,
221                    description: None,
222                    descriptors: vec![],
223                },
224                CharacteristicDef {
225                    uuid: Uuid::Uuid16(uuid::APPEARANCE),
226                    properties: p(&["read"]),
227                    read: Access::Open,
228                    write: Access::Never,
229                    value: appearance.to_le_bytes().to_vec(),
230                    max_len: 2,
231                    description: None,
232                    descriptors: vec![],
233                },
234                // We resolve private addresses, so a peer may direct to our RPA.
235                CharacteristicDef {
236                    uuid: Uuid::Uuid16(uuid::CENTRAL_ADDRESS_RESOLUTION),
237                    properties: p(&["read"]),
238                    read: Access::Open,
239                    write: Access::Never,
240                    value: vec![1],
241                    max_len: 1,
242                    description: None,
243                    descriptors: vec![],
244                },
245            ],
246        })
247        .expect("the GAP service fits");
248        let gatt = d
249            .add(&ServiceDef {
250                uuid: Uuid::Uuid16(uuid::GATT),
251                primary: true,
252                characteristics: vec![
253                    CharacteristicDef {
254                        uuid: Uuid::Uuid16(uuid::SERVICE_CHANGED),
255                        properties: p(&["indicate"]),
256                        read: Access::Never,
257                        write: Access::Never,
258                        value: vec![0; 4],
259                        max_len: 4,
260                        description: None,
261                        descriptors: vec![],
262                    },
263                    CharacteristicDef {
264                        uuid: Uuid::Uuid16(uuid::CLIENT_SUPPORTED_FEATURES),
265                        properties: p(&["read", "write"]),
266                        read: Access::Open,
267                        write: Access::Open,
268                        value: vec![0],
269                        max_len: 1,
270                        description: None,
271                        descriptors: vec![],
272                    },
273                    CharacteristicDef {
274                        uuid: Uuid::Uuid16(uuid::DATABASE_HASH),
275                        properties: p(&["read"]),
276                        read: Access::Open,
277                        write: Access::Never,
278                        value: vec![0; 16],
279                        max_len: 16,
280                        description: None,
281                        descriptors: vec![],
282                    },
283                ],
284            })
285            .expect("the GATT service fits");
286        {
287            let mut db = d.lock();
288            db.service_changed = gatt.characteristics[0].1;
289            db.hash_handle = gatt.characteristics[2].1;
290            update_hash(&mut db);
291        }
292        d
293    }
294
295    fn lock(&self) -> std::sync::MutexGuard<'_, Db> {
296        self.db.lock().unwrap_or_else(|e| e.into_inner())
297    }
298
299    /// Adds a service at the end of the database.
300    pub fn add(&self, s: &ServiceDef) -> Result<ServiceHandles> {
301        let mut db = self.lock();
302        let mut next = db.attrs.last().map(|a| a.handle + 1).unwrap_or(1);
303        let needed = 1 + s
304            .characteristics
305            .iter()
306            .map(|c| {
307                let p = Properties::from_names(&c.properties).unwrap_or_default();
308                2 + usize::from(p.has(Properties::NOTIFY) || p.has(Properties::INDICATE))
309                    + usize::from(c.description.is_some())
310                    + c.descriptors.len()
311            })
312            .sum::<usize>();
313        if usize::from(next) + needed > 0xffff {
314            return Err(Error::InvalidParameter("the GATT database is full".into()));
315        }
316        let start = next;
317        let mut new = Vec::with_capacity(needed);
318        new.push(Attr {
319            handle: next,
320            ty: Uuid::Uuid16(if s.primary {
321                uuid::PRIMARY_SERVICE
322            } else {
323                uuid::SECONDARY_SERVICE
324            }),
325            kind: Kind::Service,
326            read: Access::Open,
327            write: Access::Never,
328            value: uuid_bytes(&s.uuid),
329            service: start,
330        });
331        next += 1;
332        let mut chars = Vec::new();
333        for c in &s.characteristics {
334            let props = Properties::from_names(&c.properties).map_err(Error::InvalidParameter)?;
335            if c.max_len > 512 || c.value.len() > c.max_len {
336                return Err(Error::InvalidParameter(format!(
337                    "characteristic {} value over {} octets",
338                    c.uuid, c.max_len
339                )));
340            }
341            let decl = next;
342            let value_handle = next + 1;
343            let mut dv = vec![props.0];
344            dv.extend_from_slice(&value_handle.to_le_bytes());
345            dv.extend_from_slice(&uuid_bytes(&c.uuid));
346            new.push(Attr {
347                handle: decl,
348                ty: Uuid::Uuid16(uuid::CHARACTERISTIC),
349                kind: Kind::Declaration,
350                read: Access::Open,
351                write: Access::Never,
352                value: dv,
353                service: start,
354            });
355            let notifies = props.has(Properties::NOTIFY) || props.has(Properties::INDICATE);
356            let read = if props.has(Properties::READ) {
357                c.read
358            } else {
359                Access::Never
360            };
361            let write =
362                if props.has(Properties::WRITE) || props.has(Properties::WRITE_WITHOUT_RESPONSE) {
363                    c.write
364                } else {
365                    Access::Never
366                };
367            next += 2;
368            let cccd = notifies.then_some(next);
369            new.push(Attr {
370                handle: value_handle,
371                ty: c.uuid,
372                kind: Kind::Value {
373                    props,
374                    max_len: c.max_len,
375                    cccd,
376                },
377                read,
378                write,
379                value: c.value.clone(),
380                service: start,
381            });
382            if let Some(h) = cccd {
383                new.push(Attr {
384                    handle: h,
385                    ty: Uuid::Uuid16(uuid::CCCD),
386                    kind: Kind::Cccd {
387                        value: value_handle,
388                    },
389                    read: Access::Open,
390                    write: c.read.max_open(),
391                    value: vec![0, 0],
392                    service: start,
393                });
394                next += 1;
395            }
396            if let Some(d) = &c.description {
397                new.push(Attr {
398                    handle: next,
399                    ty: Uuid::Uuid16(uuid::USER_DESCRIPTION),
400                    kind: Kind::Descriptor,
401                    read: Access::Open,
402                    write: Access::Never,
403                    value: d.as_bytes().to_vec(),
404                    service: start,
405                });
406                next += 1;
407            }
408            for d in &c.descriptors {
409                new.push(Attr {
410                    handle: next,
411                    ty: d.uuid,
412                    kind: Kind::Descriptor,
413                    read: d.read,
414                    write: d.write,
415                    value: d.value.clone(),
416                    service: start,
417                });
418                next += 1;
419            }
420            chars.push((c.uuid, value_handle));
421        }
422        let end = next - 1;
423        db.attrs.extend(new);
424        update_hash(&mut db);
425        Ok(ServiceHandles {
426            start,
427            end,
428            characteristics: chars,
429        })
430    }
431
432    /// Removes the service whose declaration is at `start`; returns the
433    /// range it held (for Service Changed).
434    pub fn remove(&self, start: u16) -> Result<(u16, u16)> {
435        let mut db = self.lock();
436        let range: Vec<u16> = db
437            .attrs
438            .iter()
439            .filter(|a| a.service == start)
440            .map(|a| a.handle)
441            .collect();
442        let (Some(&first), Some(&last)) = (range.first(), range.last()) else {
443            return Err(Error::InvalidParameter(format!(
444                "no service at handle {start:#06x}"
445            )));
446        };
447        if db
448            .attrs
449            .iter()
450            .any(|a| a.handle == first && a.ty == Uuid::Uuid16(uuid::GATT))
451            || first <= db.hash_handle
452        {
453            return Err(Error::InvalidParameter(
454                "the GAP and GATT services stay".into(),
455            ));
456        }
457        db.attrs.retain(|a| a.service != start);
458        db.cccd.retain(|(_, h), _| *h < first || *h > last);
459        update_hash(&mut db);
460        Ok((first, last))
461    }
462
463    /// A value.
464    pub fn value(&self, handle: u16) -> Option<Vec<u8>> {
465        self.lock()
466            .attrs
467            .iter()
468            .find(|a| a.handle == handle)
469            .map(|a| a.value.clone())
470    }
471
472    /// Sets a value (no notification).
473    pub fn set_value(&self, handle: u16, value: &[u8]) -> Result<()> {
474        let mut db = self.lock();
475        let a = db
476            .attrs
477            .iter_mut()
478            .find(|a| a.handle == handle)
479            .ok_or_else(|| Error::InvalidParameter(format!("no attribute {handle:#06x}")))?;
480        if let Kind::Value { max_len, .. } = a.kind {
481            if value.len() > max_len {
482                return Err(Error::InvalidParameter(format!(
483                    "value over {max_len} octets"
484                )));
485            }
486        }
487        a.value = value.to_vec();
488        Ok(())
489    }
490
491    /// Which connections subscribed to a value: (connection, notify, indicate).
492    pub(crate) fn subscribers(&self, value_handle: u16) -> Vec<(u16, bool, bool)> {
493        self.lock()
494            .cccd
495            .iter()
496            .filter(|((_, h), _)| *h == value_handle)
497            .map(|((c, _), bits)| (*c, bits & 1 != 0, bits & 2 != 0))
498            .collect()
499    }
500
501    /// A connection closed: forget its configuration and queued writes.
502    /// Returns its configuration for storing with a bond.
503    pub(crate) fn connection_closed(&self, conn: u16) -> Vec<(u16, u16)> {
504        let mut db = self.lock();
505        db.prepared.remove(&conn);
506        let mine: Vec<(u16, u16)> = db
507            .cccd
508            .iter()
509            .filter(|((c, _), _)| *c == conn)
510            .map(|((_, h), v)| (*h, *v))
511            .collect();
512        db.cccd.retain(|(c, _), _| *c != conn);
513        mine
514    }
515
516    /// A connection's current client configuration: (value handle, bits).
517    pub(crate) fn subscriptions_of(&self, conn: u16) -> Vec<(u16, u16)> {
518        self.lock()
519            .cccd
520            .iter()
521            .filter(|((c, _), _)| *c == conn)
522            .map(|((_, h), v)| (*h, *v))
523            .collect()
524    }
525
526    /// Restores a bonded client's configuration on a new connection.
527    pub(crate) fn restore(&self, conn: u16, cccds: &[(u16, u16)]) {
528        let mut db = self.lock();
529        for (h, v) in cccds {
530            if db
531                .attrs
532                .iter()
533                .any(|a| a.handle == *h && matches!(a.kind, Kind::Value { cccd: Some(_), .. }))
534            {
535                db.cccd.insert((conn, *h), *v);
536            }
537        }
538    }
539
540    /// The Service Changed characteristic's value handle.
541    pub(crate) fn service_changed_handle(&self) -> u16 {
542        self.lock().service_changed
543    }
544
545    /// Runs a request without a connection (the fuzz targets).
546    #[cfg(feature = "fuzzing")]
547    pub(crate) fn handle_fuzz(
548        &self,
549        conn: u16,
550        sec: &Security,
551        mtu: usize,
552        pdu: &[u8],
553    ) -> Option<Vec<u8>> {
554        let mut events = Vec::new();
555        let mut db = self.lock();
556        match handle_locked(&mut db, conn, sec, mtu, pdu, &mut events) {
557            Ok(r) => r,
558            Err((h, code)) => Some(error_pdu(pdu[0], h, code)),
559        }
560    }
561
562    /// Handles an ATT request or command; returns the response to send.
563    pub(crate) async fn handle(
564        &self,
565        host: &Host,
566        conn: &Arc<ConnState>,
567        pdu: &[u8],
568    ) -> Option<Vec<u8>> {
569        let sec = *conn.security.borrow();
570        let mtu = usize::from(conn.att.mtu());
571        let opcode = pdu[0];
572        let mut events = Vec::new();
573        let rsp = {
574            let mut db = self.lock();
575            match handle_locked(&mut db, conn.handle, &sec, mtu, pdu, &mut events) {
576                Ok(r) => r,
577                Err((h, code)) => Some(error_pdu(opcode, h, code)),
578            }
579        };
580        for e in events {
581            host.emit(e);
582        }
583        // Commands get no answer; neither does anything we cannot parse as a request.
584        if opcode & 0x40 != 0 {
585            return None;
586        }
587        rsp
588    }
589}
590
591trait MaxOpen {
592    fn max_open(self) -> Access;
593}
594
595impl MaxOpen for Access {
596    /// The CCCD is writable by anyone who could read the value.
597    fn max_open(self) -> Access {
598        match self {
599            Access::Never => Access::Open,
600            a => a,
601        }
602    }
603}
604
605type Failure = (u16, u8);
606
607fn le16(b: &[u8], i: usize) -> Result<u16, Failure> {
608    b.get(i..i + 2)
609        .map(|s| u16::from_le_bytes([s[0], s[1]]))
610        .ok_or((0, ecode::INVALID_PDU))
611}
612
613fn range(pdu: &[u8]) -> Result<(u16, u16), Failure> {
614    let (s, e) = (le16(pdu, 1)?, le16(pdu, 3)?);
615    if s == 0 || s > e {
616        return Err((s, ecode::INVALID_HANDLE));
617    }
618    Ok((s, e))
619}
620
621fn group_end(db: &Db, service: u16) -> u16 {
622    db.attrs
623        .iter()
624        .filter(|a| a.service == service)
625        .map(|a| a.handle)
626        .max()
627        .unwrap_or(service)
628}
629
630fn readable(a: &Attr, sec: &Security) -> Result<(), Failure> {
631    match a.read.check(sec) {
632        None => Ok(()),
633        Some(0) => Err((a.handle, ecode::READ_NOT_PERMITTED)),
634        Some(c) => Err((a.handle, c)),
635    }
636}
637
638fn writable(a: &Attr, sec: &Security) -> Result<(), Failure> {
639    match a.write.check(sec) {
640        None => Ok(()),
641        Some(0) => Err((a.handle, ecode::WRITE_NOT_PERMITTED)),
642        Some(c) => Err((a.handle, c)),
643    }
644}
645
646/// The value a read returns: the CCCD is per connection.
647fn read_value(db: &Db, conn: u16, a: &Attr) -> Vec<u8> {
648    match a.kind {
649        Kind::Cccd { value } => db
650            .cccd
651            .get(&(conn, value))
652            .copied()
653            .unwrap_or(0)
654            .to_le_bytes()
655            .to_vec(),
656        _ => a.value.clone(),
657    }
658}
659
660fn handle_locked(
661    db: &mut Db,
662    conn: u16,
663    sec: &Security,
664    mtu: usize,
665    pdu: &[u8],
666    events: &mut Vec<HostEvent>,
667) -> Result<Option<Vec<u8>>, Failure> {
668    let opcode = pdu[0];
669    match opcode {
670        op::READ_BY_GROUP_REQ => {
671            let (s, e) = range(pdu)?;
672            let ty = Uuid::from_le_bytes(&pdu[5..]).ok_or((0, ecode::INVALID_PDU))?;
673            if ty != Uuid::Uuid16(uuid::PRIMARY_SERVICE)
674                && ty != Uuid::Uuid16(uuid::SECONDARY_SERVICE)
675            {
676                return Err((s, ecode::UNSUPPORTED_GROUP_TYPE));
677            }
678            let mut out = vec![op::READ_BY_GROUP_RSP, 0];
679            let mut len = 0usize;
680            for a in db
681                .attrs
682                .iter()
683                .filter(|a| a.handle >= s && a.handle <= e && a.ty == ty)
684            {
685                let entry_len = 4 + a.value.len();
686                if len == 0 {
687                    len = entry_len;
688                } else if entry_len != len || out.len() + entry_len > mtu {
689                    break;
690                }
691                out.extend_from_slice(&a.handle.to_le_bytes());
692                out.extend_from_slice(&group_end(db, a.service).to_le_bytes());
693                out.extend_from_slice(&a.value);
694            }
695            if len == 0 {
696                return Err((s, ecode::ATTRIBUTE_NOT_FOUND));
697            }
698            out[1] = len as u8;
699            Ok(Some(out))
700        }
701        op::FIND_INFO_REQ => {
702            let (s, e) = range(pdu)?;
703            let mut out = vec![op::FIND_INFO_RSP, 0];
704            for a in db.attrs.iter().filter(|a| a.handle >= s && a.handle <= e) {
705                let short = a.ty.as_u16().is_some();
706                let format = if short { 1 } else { 2 };
707                if out[1] == 0 {
708                    out[1] = format;
709                } else if out[1] != format {
710                    break;
711                }
712                let b = uuid_bytes(&a.ty);
713                if out.len() + 2 + b.len() > mtu {
714                    break;
715                }
716                out.extend_from_slice(&a.handle.to_le_bytes());
717                out.extend_from_slice(&b);
718            }
719            if out[1] == 0 {
720                return Err((s, ecode::ATTRIBUTE_NOT_FOUND));
721            }
722            Ok(Some(out))
723        }
724        op::FIND_BY_TYPE_REQ => {
725            let (s, e) = range(pdu)?;
726            let ty = Uuid::Uuid16(le16(pdu, 5)?);
727            let value = &pdu[7..];
728            let mut out = vec![op::FIND_BY_TYPE_RSP];
729            for a in db
730                .attrs
731                .iter()
732                .filter(|a| a.handle >= s && a.handle <= e && a.ty == ty && a.value == value)
733            {
734                if out.len() + 4 > mtu {
735                    break;
736                }
737                let end = if a.kind == Kind::Service {
738                    group_end(db, a.service)
739                } else {
740                    a.handle
741                };
742                out.extend_from_slice(&a.handle.to_le_bytes());
743                out.extend_from_slice(&end.to_le_bytes());
744            }
745            if out.len() == 1 {
746                return Err((s, ecode::ATTRIBUTE_NOT_FOUND));
747            }
748            Ok(Some(out))
749        }
750        op::READ_BY_TYPE_REQ => {
751            let (s, e) = range(pdu)?;
752            let ty = Uuid::from_le_bytes(&pdu[5..]).ok_or((0, ecode::INVALID_PDU))?;
753            let mut out = vec![op::READ_BY_TYPE_RSP, 0];
754            let mut len = 0usize;
755            for a in db
756                .attrs
757                .iter()
758                .filter(|a| a.handle >= s && a.handle <= e && a.ty == ty)
759            {
760                if let Err(f) = readable(a, sec) {
761                    if len == 0 {
762                        return Err(f);
763                    }
764                    break;
765                }
766                let v = read_value(db, conn, a);
767                let v = &v[..v.len().min(mtu - 4).min(253)];
768                let entry = 2 + v.len();
769                if len == 0 {
770                    len = entry;
771                } else if entry != len || out.len() + entry > mtu {
772                    break;
773                }
774                out.extend_from_slice(&a.handle.to_le_bytes());
775                out.extend_from_slice(v);
776            }
777            if len == 0 {
778                return Err((s, ecode::ATTRIBUTE_NOT_FOUND));
779            }
780            out[1] = len as u8;
781            Ok(Some(out))
782        }
783        op::READ_REQ | op::READ_BLOB_REQ => {
784            let h = le16(pdu, 1)?;
785            let offset = if opcode == op::READ_BLOB_REQ {
786                usize::from(le16(pdu, 3)?)
787            } else {
788                0
789            };
790            let a = db
791                .attrs
792                .iter()
793                .find(|a| a.handle == h)
794                .ok_or((h, ecode::INVALID_HANDLE))?;
795            readable(a, sec)?;
796            let v = read_value(db, conn, a);
797            if offset > v.len() {
798                return Err((h, ecode::INVALID_OFFSET));
799            }
800            let mut out = vec![opcode + 1];
801            let part = &v[offset..];
802            out.extend_from_slice(&part[..part.len().min(mtu - 1)]);
803            Ok(Some(out))
804        }
805        op::READ_MULTIPLE_REQ | op::READ_MULTIPLE_VAR_REQ => {
806            let mut out = vec![opcode + 1];
807            for c in pdu[1..].as_chunks::<2>().0 {
808                let h = u16::from_le_bytes(*c);
809                let a = db
810                    .attrs
811                    .iter()
812                    .find(|a| a.handle == h)
813                    .ok_or((h, ecode::INVALID_HANDLE))?;
814                readable(a, sec)?;
815                let v = read_value(db, conn, a);
816                if opcode == op::READ_MULTIPLE_VAR_REQ {
817                    out.extend_from_slice(&(v.len() as u16).to_le_bytes());
818                }
819                out.extend_from_slice(&v);
820            }
821            out.truncate(mtu);
822            Ok(Some(out))
823        }
824        op::WRITE_REQ | op::WRITE_CMD => {
825            let h = le16(pdu, 1)?;
826            let value = pdu[3..].to_vec();
827            write_value(db, conn, sec, h, 0, value, opcode == op::WRITE_CMD, events)?;
828            Ok((opcode == op::WRITE_REQ).then(|| vec![op::WRITE_RSP]))
829        }
830        op::PREPARE_WRITE_REQ => {
831            let (h, offset) = (le16(pdu, 1)?, le16(pdu, 3)?);
832            let a = db
833                .attrs
834                .iter()
835                .find(|a| a.handle == h)
836                .ok_or((h, ecode::INVALID_HANDLE))?;
837            writable(a, sec)?;
838            let q = db.prepared.entry(conn).or_default();
839            if q.len() >= MAX_PREPARED {
840                return Err((h, ecode::PREPARE_QUEUE_FULL));
841            }
842            q.push((h, offset, pdu[5..].to_vec()));
843            let mut out = pdu.to_vec();
844            out[0] = op::PREPARE_WRITE_RSP;
845            Ok(Some(out))
846        }
847        op::EXECUTE_WRITE_REQ => {
848            let flags = *pdu.get(1).ok_or((0, ecode::INVALID_PDU))?;
849            let queue = db.prepared.remove(&conn).unwrap_or_default();
850            if flags == 0x01 {
851                // Assemble each handle's value from its parts, in order.
852                let mut values: Vec<(u16, Vec<u8>)> = Vec::new();
853                for (h, offset, part) in queue {
854                    let i = match values.iter().position(|(x, _)| *x == h) {
855                        Some(i) => i,
856                        None => {
857                            let cur = db
858                                .attrs
859                                .iter()
860                                .find(|a| a.handle == h)
861                                .map(|a| a.value.clone())
862                                .unwrap_or_default();
863                            values.push((h, cur));
864                            values.len() - 1
865                        }
866                    };
867                    let v = &mut values[i].1;
868                    let offset = usize::from(offset);
869                    if offset > v.len() {
870                        return Err((h, ecode::INVALID_OFFSET));
871                    }
872                    v.truncate(offset);
873                    v.extend_from_slice(&part);
874                }
875                for (h, v) in values {
876                    write_value(db, conn, sec, h, 0, v, false, events)?;
877                }
878            }
879            Ok(Some(vec![op::EXECUTE_WRITE_RSP]))
880        }
881        op::SIGNED_WRITE_CMD => {
882            // Signed writes need the peer's CSRK and sign counter; not taken.
883            Ok(None)
884        }
885        _ => Err((0, ecode::REQUEST_NOT_SUPPORTED)),
886    }
887}
888
889#[allow(clippy::too_many_arguments)]
890fn write_value(
891    db: &mut Db,
892    conn: u16,
893    sec: &Security,
894    h: u16,
895    _offset: usize,
896    value: Vec<u8>,
897    command: bool,
898    events: &mut Vec<HostEvent>,
899) -> Result<(), Failure> {
900    let a = db
901        .attrs
902        .iter()
903        .find(|a| a.handle == h)
904        .ok_or((h, ecode::INVALID_HANDLE))?;
905    writable(a, sec)?;
906    match a.kind {
907        Kind::Cccd { value: vh } => {
908            if value.len() != 2 {
909                return Err((h, ecode::INVALID_LENGTH));
910            }
911            let bits = u16::from_le_bytes([value[0], value[1]]);
912            let props = db
913                .attrs
914                .iter()
915                .find(|x| x.handle == vh)
916                .and_then(|x| match x.kind {
917                    Kind::Value { props, .. } => Some(props),
918                    _ => None,
919                })
920                .unwrap_or_default();
921            if bits & !3 != 0
922                || (bits & 1 != 0 && !props.has(Properties::NOTIFY))
923                || (bits & 2 != 0 && !props.has(Properties::INDICATE))
924            {
925                return Err((h, ecode::CCCD_IMPROPER));
926            }
927            if bits == 0 {
928                db.cccd.remove(&(conn, vh));
929            } else {
930                db.cccd.insert((conn, vh), bits);
931            }
932            events.push(HostEvent::GattSubscription {
933                handle: conn,
934                attribute: vh,
935                notify: bits & 1 != 0,
936                indicate: bits & 2 != 0,
937            });
938        }
939        Kind::Value { props, max_len, .. } => {
940            let allowed = if command {
941                props.has(Properties::WRITE_WITHOUT_RESPONSE)
942            } else {
943                props.has(Properties::WRITE)
944            };
945            if !allowed {
946                return Err((h, ecode::WRITE_NOT_PERMITTED));
947            }
948            if value.len() > max_len {
949                return Err((h, ecode::INVALID_LENGTH));
950            }
951            let a = db
952                .attrs
953                .iter_mut()
954                .find(|a| a.handle == h)
955                .ok_or((h, ecode::INVALID_HANDLE))?;
956            a.value = value.clone();
957            events.push(HostEvent::GattWrite {
958                handle: conn,
959                attribute: h,
960                value,
961            });
962        }
963        Kind::Descriptor => {
964            let a = db
965                .attrs
966                .iter_mut()
967                .find(|a| a.handle == h)
968                .ok_or((h, ecode::INVALID_HANDLE))?;
969            a.value = value.clone();
970            events.push(HostEvent::GattWrite {
971                handle: conn,
972                attribute: h,
973                value,
974            });
975        }
976        _ => return Err((h, ecode::WRITE_NOT_PERMITTED)),
977    }
978    Ok(())
979}
980
981/// The Database Hash (Core Vol 3, Part G, 7.3): AES-CMAC with a zero key
982/// over the handle, type and (for declarations and Extended Properties)
983/// value of the declarations and descriptors that shape the database.
984fn update_hash(db: &mut Db) {
985    let mut m = Vec::new();
986    for a in &db.attrs {
987        let Some(t) = a.ty.as_u16() else { continue };
988        let with_value = matches!(
989            t,
990            uuid::PRIMARY_SERVICE
991                | uuid::SECONDARY_SERVICE
992                | uuid::INCLUDE
993                | uuid::CHARACTERISTIC
994                | uuid::EXTENDED_PROPERTIES
995        );
996        let without = matches!(
997            t,
998            uuid::USER_DESCRIPTION
999                | uuid::CCCD
1000                | uuid::SCCD
1001                | uuid::PRESENTATION_FORMAT
1002                | uuid::AGGREGATE_FORMAT
1003        );
1004        if with_value || without {
1005            m.extend_from_slice(&a.handle.to_le_bytes());
1006            m.extend_from_slice(&t.to_le_bytes());
1007            if with_value {
1008                m.extend_from_slice(&a.value);
1009            }
1010        }
1011    }
1012    let hash = {
1013        use cmac::Mac;
1014        let mut mac = <cmac::Cmac<aes::Aes128> as aes::cipher::KeyInit>::new(&[0u8; 16].into());
1015        mac.update(&m);
1016        let h: [u8; 16] = mac.finalize().into_bytes().into();
1017        h
1018    };
1019    let hh = db.hash_handle;
1020    if let Some(a) = db.attrs.iter_mut().find(|a| a.handle == hh && hh != 0) {
1021        // Sent least significant octet first.
1022        a.value = hash.iter().rev().copied().collect();
1023    }
1024}
1025
1026/// The application's handle on the GATT server.
1027#[derive(Clone)]
1028pub struct Server {
1029    pub(crate) host: Host,
1030}
1031
1032impl Server {
1033    /// Adds a service; connected clients are told with Service Changed.
1034    pub async fn add(&self, s: &ServiceDef) -> Result<ServiceHandles> {
1035        let h = self.host.inner.gatt.add(s)?;
1036        self.service_changed(h.start, h.end).await;
1037        Ok(h)
1038    }
1039
1040    /// Removes the service declared at `start`.
1041    pub async fn remove(&self, start: u16) -> Result<()> {
1042        let (a, b) = self.host.inner.gatt.remove(start)?;
1043        self.service_changed(a, b).await;
1044        Ok(())
1045    }
1046
1047    async fn service_changed(&self, start: u16, end: u16) {
1048        let db = &self.host.inner.gatt;
1049        let sc = db.service_changed_handle();
1050        let mut v = start.to_le_bytes().to_vec();
1051        v.extend_from_slice(&end.to_le_bytes());
1052        for (conn, _, indicate) in db.subscribers(sc) {
1053            if indicate {
1054                if let Some(c) = self.host.state(conn) {
1055                    let _ = c.att.indicate(&self.host, &c, sc, &v).await;
1056                }
1057            }
1058        }
1059    }
1060
1061    /// A value.
1062    pub fn value(&self, handle: u16) -> Option<Vec<u8>> {
1063        self.host.inner.gatt.value(handle)
1064    }
1065
1066    /// Sets a value without telling anyone.
1067    pub fn set(&self, handle: u16, value: &[u8]) -> Result<()> {
1068        self.host.inner.gatt.set_value(handle, value)
1069    }
1070
1071    /// Sets a value and notifies (or indicates) every subscribed client.
1072    /// Returns how many clients were told.
1073    pub async fn notify(&self, handle: u16, value: &[u8]) -> Result<usize> {
1074        self.set(handle, value)?;
1075        let mut n = 0;
1076        for (conn, notify, indicate) in self.host.inner.gatt.subscribers(handle) {
1077            let Some(c) = self.host.state(conn) else {
1078                continue;
1079            };
1080            let r = if indicate {
1081                c.att.indicate(&self.host, &c, handle, value).await
1082            } else if notify {
1083                c.att.notify(&self.host, &c, handle, value).await
1084            } else {
1085                continue;
1086            };
1087            match r {
1088                Ok(()) => n += 1,
1089                Err(e) => tracing::debug!("could not update {conn:#05x}: {e}"),
1090            }
1091        }
1092        Ok(n)
1093    }
1094}
1095
1096#[cfg(test)]
1097mod tests {
1098    use super::*;
1099
1100    fn sec() -> Security {
1101        Security::default()
1102    }
1103
1104    #[test]
1105    fn database_layout_and_requests() {
1106        let db = Database::new("test", 0);
1107        let h = db
1108            .add(&ServiceDef {
1109                uuid: Uuid::Uuid16(0x180f),
1110                primary: true,
1111                characteristics: vec![CharacteristicDef {
1112                    uuid: Uuid::Uuid16(0x2a19),
1113                    properties: vec!["read".into(), "notify".into()],
1114                    read: Access::Open,
1115                    write: Access::Never,
1116                    value: vec![99],
1117                    max_len: 1,
1118                    description: Some("Battery".into()),
1119                    descriptors: vec![],
1120                }],
1121            })
1122            .unwrap();
1123        let vh = h.characteristics[0].1;
1124        let mut d = db.lock();
1125        let mut ev = Vec::new();
1126        // Discover primary services.
1127        let r = handle_locked(
1128            &mut d,
1129            1,
1130            &sec(),
1131            23,
1132            &[0x10, 1, 0, 0xff, 0xff, 0x00, 0x28],
1133            &mut ev,
1134        )
1135        .unwrap()
1136        .unwrap();
1137        assert_eq!(r[0], op::READ_BY_GROUP_RSP);
1138        assert_eq!(r[1], 6);
1139        // Read the battery level.
1140        let v = vh.to_le_bytes();
1141        let r = handle_locked(&mut d, 1, &sec(), 23, &[0x0a, v[0], v[1]], &mut ev)
1142            .unwrap()
1143            .unwrap();
1144        assert_eq!(r, vec![op::READ_RSP, 99]);
1145        // Writing it is not permitted.
1146        let e = handle_locked(&mut d, 1, &sec(), 23, &[0x12, v[0], v[1], 1], &mut ev).unwrap_err();
1147        assert_eq!(e.1, ecode::WRITE_NOT_PERMITTED);
1148        // Subscribe, then indications are refused (notify only).
1149        let c = (vh + 1).to_le_bytes();
1150        handle_locked(&mut d, 1, &sec(), 23, &[0x12, c[0], c[1], 1, 0], &mut ev).unwrap();
1151        let e =
1152            handle_locked(&mut d, 1, &sec(), 23, &[0x12, c[0], c[1], 2, 0], &mut ev).unwrap_err();
1153        assert_eq!(e.1, ecode::CCCD_IMPROPER);
1154        drop(d);
1155        assert_eq!(db.subscribers(vh), vec![(1, true, false)]);
1156        assert!(matches!(
1157            ev[0],
1158            HostEvent::GattSubscription { notify: true, .. }
1159        ));
1160        assert_eq!(db.connection_closed(1), vec![(vh, 1)]);
1161        assert!(db.subscribers(vh).is_empty());
1162    }
1163
1164    #[test]
1165    fn security_is_enforced() {
1166        let db = Database::new("t", 0);
1167        let h = db
1168            .add(&ServiceDef {
1169                uuid: Uuid::parse("12345678-1234-5678-1234-56789abcdef0").unwrap(),
1170                primary: true,
1171                characteristics: vec![CharacteristicDef {
1172                    uuid: Uuid::Uuid16(0x2a00),
1173                    properties: vec!["read".into(), "write".into()],
1174                    read: Access::Encrypted,
1175                    write: Access::Authenticated,
1176                    value: vec![1],
1177                    max_len: 4,
1178                    description: None,
1179                    descriptors: vec![],
1180                }],
1181            })
1182            .unwrap();
1183        let v = h.characteristics[0].1.to_le_bytes();
1184        let mut d = db.lock();
1185        let mut ev = Vec::new();
1186        let e = handle_locked(&mut d, 1, &sec(), 23, &[0x0a, v[0], v[1]], &mut ev).unwrap_err();
1187        assert_eq!(e.1, ecode::INSUFFICIENT_AUTHENTICATION);
1188        let enc = Security {
1189            encrypted: true,
1190            key_size: 16,
1191            ..Security::default()
1192        };
1193        assert!(handle_locked(&mut d, 1, &enc, 23, &[0x0a, v[0], v[1]], &mut ev).is_ok());
1194        let e = handle_locked(&mut d, 1, &enc, 23, &[0x12, v[0], v[1], 7], &mut ev).unwrap_err();
1195        assert_eq!(e.1, ecode::INSUFFICIENT_AUTHENTICATION);
1196        let auth = Security {
1197            authenticated: true,
1198            ..enc
1199        };
1200        assert!(handle_locked(&mut d, 1, &auth, 23, &[0x12, v[0], v[1], 7], &mut ev).is_ok());
1201        let e = handle_locked(
1202            &mut d,
1203            1,
1204            &auth,
1205            23,
1206            &[0x12, v[0], v[1], 1, 2, 3, 4, 5],
1207            &mut ev,
1208        )
1209        .unwrap_err();
1210        assert_eq!(e.1, ecode::INVALID_LENGTH);
1211    }
1212
1213    #[test]
1214    fn long_write_assembles_parts() {
1215        let db = Database::new("t", 0);
1216        let h = db
1217            .add(&ServiceDef {
1218                uuid: Uuid::Uuid16(0xfff0),
1219                primary: true,
1220                characteristics: vec![CharacteristicDef {
1221                    uuid: Uuid::Uuid16(0xfff1),
1222                    properties: vec!["read".into(), "write".into()],
1223                    read: Access::Open,
1224                    write: Access::Open,
1225                    value: vec![],
1226                    max_len: 512,
1227                    description: None,
1228                    descriptors: vec![],
1229                }],
1230            })
1231            .unwrap();
1232        let v = h.characteristics[0].1.to_le_bytes();
1233        let mut d = db.lock();
1234        let mut ev = Vec::new();
1235        handle_locked(
1236            &mut d,
1237            1,
1238            &sec(),
1239            23,
1240            &[0x16, v[0], v[1], 0, 0, 1, 2, 3],
1241            &mut ev,
1242        )
1243        .unwrap();
1244        handle_locked(
1245            &mut d,
1246            1,
1247            &sec(),
1248            23,
1249            &[0x16, v[0], v[1], 3, 0, 4, 5],
1250            &mut ev,
1251        )
1252        .unwrap();
1253        handle_locked(&mut d, 1, &sec(), 23, &[0x18, 0x01], &mut ev).unwrap();
1254        drop(d);
1255        assert_eq!(db.value(h.characteristics[0].1), Some(vec![1, 2, 3, 4, 5]));
1256    }
1257}