garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /bt/src/host.rs

raw

//! The host: what a device does with its controller. Commands go out one
//! at a time (the controller allows one outstanding), ACL data within the
//! controller's buffers; events and data coming back drive the state
//! machines for scanning, advertising, connections and ATT, as client and
//! as server.

use crate::att;
use crate::gatt::{self, Characteristic, Service, Table, Uuid};
use crate::hci::{self, Address, Framer, Packet};
use crate::smp;
use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;

/// What happened, for whoever runs the host.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Event {
    /// The controller is set up; this is its address.
    Ready {
        address: Address,
    },
    /// A device advertised: new, or its name just learnt.
    Found {
        address: Address,
        name: Option<String>,
        rssi: i8,
    },
    Connected {
        connection: u16,
        peer: Address,
        /// This device asked for the connection (the GATT client's usual side).
        central: bool,
    },
    Disconnected {
        connection: u16,
        peer: Address,
    },
    /// The peer's services and characteristics, as asked by `discover`.
    Discovered {
        connection: u16,
        services: Vec<Service>,
    },
    Read {
        connection: u16,
        handle: u16,
        value: Vec<u8>,
    },
    ReadFailed {
        connection: u16,
        handle: u16,
        error: u8,
    },
    Written {
        connection: u16,
        handle: u16,
        ok: bool,
    },
    /// The peer notified a value we subscribed to.
    Notified {
        connection: u16,
        handle: u16,
        value: Vec<u8>,
    },
    /// The peer wrote one of this device's characteristics.
    Changed {
        connection: u16,
        handle: u16,
        value: Vec<u8>,
    },
    /// The peer turned notifications of one of this device's
    /// characteristics on or off.
    Subscribed {
        connection: u16,
        handle: u16,
        on: bool,
    },
    /// Pairing asks this device's person: does the other device show
    /// `code`, or, with `None`, may the peer pair at all (it has no
    /// display). [`Host::confirm`] answers.
    Confirm {
        connection: u16,
        peer: Address,
        code: Option<u32>,
    },
    /// Pairing by passkey: show `passkey` to this device's person, to be
    /// typed on the other device (a keyboard), or, with `None`, ask them to
    /// type the one the other device shows ([`Host::enter_passkey`]).
    /// [`Host::confirm`] with no cancels either.
    Passkey {
        connection: u16,
        peer: Address,
        passkey: Option<u32>,
    },
    /// Paired, the link encrypted with the new key: the bond to keep.
    Paired {
        connection: u16,
        bond: Bond,
    },
    PairingFailed {
        connection: u16,
        peer: Address,
        /// Why ([`smp::reason_text`]).
        reason: u8,
    },
    /// The link is encrypted, with a key from a pairing now or before.
    Encrypted {
        connection: u16,
        peer: Address,
    },
    /// A bonded peer did not take our key ([`hci::KEY_MISSING`]: it forgot
    /// the pairing).
    EncryptionFailed {
        connection: u16,
        peer: Address,
        status: u8,
    },
}

/// A device paired with: what encrypts the link to it again without
/// pairing anew, and knows it by whatever address it uses.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Bond {
    /// Its identity address where it gave one, else the address it paired
    /// from.
    pub address: Address,
    /// Its address type (0 public, 1 random).
    pub kind: u8,
    /// The long-term key, as the controller takes it.
    pub key: [u8; 16],
    /// Whether the pairing compared numbers (a device in the middle would
    /// have shown a different one); not, for a device without a display.
    pub compared: bool,
    /// Its identity resolving key: the private addresses it moves to are
    /// known by it ([`smp::resolves`]).
    pub irk: Option<[u8; 16]>,
}

/// In a kept bond's last byte besides "compared": an IRK follows.
const HAS_IRK: u8 = 0x02;

impl Bond {
    /// Address, type, key, compared, and the IRK where there is one: for
    /// keeping it on disk. 24 bytes without one, as bonds were kept before
    /// identities, or 40 with.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut b = self.address.0.to_vec();
        b.push(self.kind);
        b.extend_from_slice(&self.key);
        b.push(u8::from(self.compared) | if self.irk.is_some() { HAS_IRK } else { 0 });
        if let Some(irk) = self.irk {
            b.extend_from_slice(&irk);
        }
        b
    }

    /// The bond at the start of `b`, and how many bytes it took.
    pub fn from_bytes(b: &[u8]) -> Option<(Bond, usize)> {
        let flags = *b.get(23)?;
        let irk = match flags & HAS_IRK {
            0 => None,
            _ => Some(b.get(24..40)?.try_into().unwrap()),
        };
        let bond = Bond {
            address: Address(b[..6].try_into().unwrap()),
            kind: b[6],
            key: b[7..23].try_into().unwrap(),
            compared: flags & 1 != 0,
            irk,
        };
        Some((bond, if irk.is_some() { 40 } else { 24 }))
    }

    /// Whether `address` is this device's: its own, or one it moved to.
    pub fn knows(&self, address: Address) -> bool {
        address == self.address || self.irk.is_some_and(|irk| smp::resolves(&irk, &address.0))
    }
}

/// A device seen while scanning.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Found {
    /// Its address, or a paired device's identity whatever address it
    /// advertised from.
    pub address: Address,
    /// The address it was last heard from, which a connection goes to.
    pub air: Address,
    pub name: Option<String>,
    pub rssi: i8,
    /// When it was last heard (ms, the caller's clock).
    pub seen: u64,
    /// Its advertising data, as last heard.
    pub data: Vec<u8>,
}

#[derive(Clone, PartialEq, Eq, Debug)]
enum Request {
    Mtu,
    Groups { start: u16 },
    Characteristics { service: usize, start: u16 },
    Read { handle: u16 },
    Write { handle: u16 },
}

struct Connection {
    handle: u16,
    /// The peer, by its identity once known ([`Bond::address`]).
    peer: Address,
    /// The address it connected from, which pairing's functions take.
    air: Address,
    central: bool,
    mtu: usize,
    /// An L2CAP frame being put together from ACL fragments, and its
    /// whole length (header included).
    rx: Vec<u8>,
    rx_len: usize,
    /// The ATT request outstanding (one at a time), when it went, and
    /// those waiting behind it.
    request: Option<(Request, u64)>,
    queue: VecDeque<(Request, Vec<u8>)>,
    /// Services found so far by `discover`.
    discovering: Option<Vec<Service>>,
    /// Value handles of this device's characteristics the peer subscribed to.
    subscriptions: Vec<u16>,
    /// The peer's address type.
    peer_kind: u8,
    encrypted: bool,
    pairing: Option<smp::Pairing>,
    /// The key a pairing just agreed, until the link is encrypted with it.
    paired: Option<([u8; 16], bool)>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Step {
    Reset,
    Address,
    EventMask,
    LeEventMask,
    BufferSize,
    Ready,
}

/// How long a request may go unanswered before the connection is dropped,
/// and how long a connection attempt may take.
const ATT_TIMEOUT_MS: u64 = 30_000;
const CONNECT_TIMEOUT_MS: u64 = 5_000;
/// The ATT fixed channel, LE signalling, and the security manager.
const CID_ATT: u16 = 0x0004;
const CID_SIGNALLING: u16 = 0x0005;
const CID_SMP: u16 = 0x0006;

pub struct Host {
    framer: Framer,
    out: VecDeque<Vec<u8>>,
    events: VecDeque<Event>,
    step: Step,
    address: Address,
    name: String,
    table: Table,
    connections: Vec<Connection>,
    found: Vec<Found>,
    scanning: bool,
    scan_wanted: bool,
    advertising: bool,
    advertise_wanted: bool,
    /// A connection asked for, and when.
    connecting: Option<(Address, u64)>,
    /// What the controller holds: ACL packets at once, bytes each; and how
    /// many are out there now.
    acl_packets: u16,
    acl_len: usize,
    in_flight: u16,
    acl_queue: VecDeque<(u16, Vec<u8>)>,
    command_pending: bool,
    command_queue: VecDeque<(u16, Vec<u8>)>,
    now: u64,
    bonds: Vec<Bond>,
    /// What this device can show and take, for pairing.
    io: u8,
    /// Where pairing's secrets come from; none, and pairing is refused.
    random: Option<Random>,
    /// This device's identity resolving key, handed to every device it
    /// pairs with.
    irk: Option<[u8; 16]>,
}

/// Secret bytes for pairings: HMAC-SHA-256 of a seed over a count.
struct Random {
    seed: [u8; 32],
    drawn: u64,
}

impl Random {
    fn fill(&mut self, out: &mut [u8]) {
        for chunk in out.chunks_mut(32) {
            self.drawn += 1;
            let block = pinnacle_crypto::sha2::hmac(&self.seed, &[b"pinnacle-bt", &self.drawn.to_le_bytes()]);
            chunk.copy_from_slice(&block[..chunk.len()]);
        }
    }
}

impl Host {
    /// A host for a device called `name`, offering `services` besides the
    /// Generic Access service (its name) that every device has. It starts
    /// by resetting the controller; [`Event::Ready`] says when it is.
    pub fn new(name: &str, services: Vec<Service>) -> Host {
        let mut all = alloc::vec![Service::new(
            Uuid::Short(gatt::GENERIC_ACCESS),
            alloc::vec![
                Characteristic::new(Uuid::Short(gatt::DEVICE_NAME), gatt::PROP_READ, name.as_bytes()),
                Characteristic::new(Uuid::Short(gatt::APPEARANCE), gatt::PROP_READ, &[0x40, 0x00]),
            ],
        )];
        all.extend(services);
        let mut host = Host {
            framer: Framer::default(),
            out: VecDeque::new(),
            events: VecDeque::new(),
            step: Step::Reset,
            address: Address::default(),
            name: name.into(),
            table: Table::new(all),
            connections: Vec::new(),
            found: Vec::new(),
            scanning: false,
            scan_wanted: false,
            advertising: false,
            advertise_wanted: false,
            connecting: None,
            acl_packets: 1,
            acl_len: 27,
            in_flight: 0,
            acl_queue: VecDeque::new(),
            command_pending: false,
            command_queue: VecDeque::new(),
            now: 0,
            bonds: Vec::new(),
            io: smp::NO_INPUT_NO_OUTPUT,
            random: None,
            irk: None,
        };
        host.command(hci::RESET, &[]);
        host
    }

    pub fn address(&self) -> Address {
        self.address
    }

    pub fn ready(&self) -> bool {
        self.step == Step::Ready
    }

    /// This device's GATT table: the handles of what it offers.
    pub fn table(&self) -> &Table {
        &self.table
    }

    /// The devices heard while scanning, latest first.
    pub fn found(&self) -> &[Found] {
        &self.found
    }

    pub fn forget_found(&mut self) {
        self.found.clear();
    }

    /// Lets this device pair: `seed` fresh secret bytes its pairings' keys
    /// and nonces are drawn from, `io` what it can show and take
    /// ([`smp::DISPLAY_YES_NO`] for a screen with buttons). Without a
    /// seed a peer asking to pair is refused.
    pub fn enable_pairing(&mut self, seed: [u8; 32], io: u8) {
        self.random = Some(Random { seed, drawn: 0 });
        self.io = io;
    }

    /// This device's identity resolving key, kept by whoever runs the host
    /// (it must stay the same across starts): handed with this device's
    /// address to each device it pairs with, so a peer that keeps it knows
    /// this device by it. Without one, peers get no identity of ours, and
    /// theirs is still asked for.
    pub fn set_identity(&mut self, irk: [u8; 16]) {
        self.irk = Some(irk);
    }

    /// The devices paired with, kept by whoever runs the host and given
    /// back to it at start ([`Host::remember`]).
    pub fn bonds(&self) -> &[Bond] {
        &self.bonds
    }

    pub fn remember(&mut self, bond: Bond) {
        self.bonds.retain(|b| b.address != bond.address);
        self.bonds.push(bond);
        // Heard before it was known: now by its identity, once.
        for f in &mut self.found {
            if bond.knows(f.air) {
                f.address = bond.address;
            }
        }
        let mut seen = Vec::new();
        self.found.retain(|f| {
            let first = !seen.contains(&f.address);
            seen.push(f.address);
            first
        });
    }

    /// The identity of a paired device `air` is, or `air` itself.
    fn resolve(&self, air: Address) -> Address {
        self.bonds
            .iter()
            .find(|b| b.knows(air))
            .map_or(air, |b| b.address)
    }

    /// Forgets a pairing: the next connection is in the open until paired
    /// again. A link to it now is dropped.
    pub fn forget(&mut self, address: Address) {
        self.bonds.retain(|b| b.address != address);
        for f in &mut self.found {
            if f.address == address {
                f.address = f.air;
            }
        }
        let connected: Vec<u16> = self
            .connections
            .iter()
            .filter(|c| c.peer == address)
            .map(|c| c.handle)
            .collect();
        for handle in connected {
            self.disconnect(handle);
        }
    }

    /// Whether the link is encrypted.
    pub fn encrypted(&self, connection: u16) -> bool {
        self.connections
            .iter()
            .any(|c| c.handle == connection && c.encrypted)
    }

    /// This device's address and the peer's, for the pairing functions.
    fn addresses(&self, connection: u16) -> Option<([u8; 7], [u8; 7])> {
        let c = self.connections.iter().find(|c| c.handle == connection)?;
        Some((
            smp::address_bytes(self.address.0, 0),
            smp::address_bytes(c.air.0, c.peer_kind),
        ))
    }

    /// Pairs with a connected peer, as the central: [`Event::Confirm`]
    /// asks for the number to be compared where both have displays, then
    /// [`Event::Paired`] or [`Event::PairingFailed`]. A bonded peer's link
    /// is encrypted with the key kept instead.
    pub fn pair(&mut self, connection: u16) {
        let Some(c) = self.connections.iter().find(|c| c.handle == connection) else {
            return;
        };
        if c.pairing.as_ref().is_some_and(|p| !p.over()) || c.encrypted {
            return;
        }
        if let Some(bond) = self.bonds.iter().find(|b| b.address == c.peer).copied() {
            if c.central {
                self.start_encryption(connection, &bond.key);
            }
            return;
        }
        let (central, peer) = (c.central, c.peer);
        if !central || self.random.is_none() {
            self.events.push_back(Event::PairingFailed {
                connection,
                peer,
                reason: smp::NOT_SUPPORTED,
            });
            return;
        }
        let Some((own, peer_bytes)) = self.addresses(connection) else {
            return;
        };
        let (io, irk, now) = (self.io, self.irk, self.now);
        let Some(random) = self.random.as_mut() else {
            return;
        };
        let (pairing, out) =
            smp::Pairing::start(io, own, peer_bytes, irk, &mut |b: &mut [u8]| random.fill(b), now);
        if let Some(c) = self.connection(connection) {
            c.pairing = Some(pairing);
        }
        self.smp_outputs(connection, out);
    }

    /// The passkey the person typed, asked for by [`Event::Passkey`].
    pub fn enter_passkey(&mut self, connection: u16, passkey: u32) {
        let now = self.now;
        let Some(out) = self
            .connection(connection)
            .and_then(|c| c.pairing.as_mut())
            .map(|p| p.enter(passkey, now))
        else {
            return;
        };
        self.smp_outputs(connection, out);
    }

    /// The person's answer to [`Event::Confirm`].
    pub fn confirm(&mut self, connection: u16, yes: bool) {
        let now = self.now;
        let Some(out) = self
            .connection(connection)
            .and_then(|c| c.pairing.as_mut())
            .map(|p| p.confirm(yes, now))
        else {
            return;
        };
        self.smp_outputs(connection, out);
    }

    fn start_encryption(&mut self, connection: u16, key: &[u8; 16]) {
        // No random number or diversifier: Secure Connections' keys have none.
        let mut p = connection.to_le_bytes().to_vec();
        p.extend_from_slice(&[0; 10]);
        p.extend_from_slice(key);
        self.command(hci::LE_START_ENCRYPTION, &p);
    }

    fn send_smp(&mut self, connection: u16, pdu: &[u8]) {
        let mut frame = (pdu.len() as u16).to_le_bytes().to_vec();
        frame.extend_from_slice(&CID_SMP.to_le_bytes());
        frame.extend_from_slice(pdu);
        self.send_l2cap(connection, frame);
    }

    fn smp_outputs(&mut self, connection: u16, out: Vec<smp::Output>) {
        let Some(c) = self.connections.iter().find(|c| c.handle == connection) else {
            return;
        };
        let (peer, central) = (c.peer, c.central);
        for o in out {
            match o {
                smp::Output::Send(pdu) => self.send_smp(connection, &pdu),
                smp::Output::Ask(code) => self.events.push_back(Event::Confirm {
                    connection,
                    peer,
                    code,
                }),
                smp::Output::Show(passkey) => self.events.push_back(Event::Passkey {
                    connection,
                    peer,
                    passkey: Some(passkey),
                }),
                smp::Output::Type => self.events.push_back(Event::Passkey {
                    connection,
                    peer,
                    passkey: None,
                }),
                smp::Output::Done { key, compared } => {
                    if let Some(c) = self.connection(connection) {
                        c.paired = Some((key, compared));
                    }
                    // The central encrypts; the peripheral's controller
                    // asks for the key when it does.
                    if central {
                        self.start_encryption(connection, &key);
                    }
                }
                smp::Output::Keys(identity) => {
                    let Some(c) = self.connection(connection) else {
                        continue;
                    };
                    let Some((key, compared)) = c.paired.take() else {
                        continue;
                    };
                    let bond = match identity {
                        Some(id) => Bond {
                            address: Address(id.address),
                            kind: id.kind,
                            key,
                            compared,
                            irk: Some(id.irk),
                        },
                        None => Bond {
                            address: c.air,
                            kind: c.peer_kind,
                            key,
                            compared,
                            irk: None,
                        },
                    };
                    // Known by its identity from here on.
                    c.peer = bond.address;
                    self.remember(bond);
                    self.events.push_back(Event::Paired { connection, bond });
                }
                smp::Output::Failed(reason) => {
                    if let Some(c) = self.connection(connection) {
                        c.paired = None;
                    }
                    self.events.push_back(Event::PairingFailed {
                        connection,
                        peer,
                        reason,
                    })
                }
            }
        }
    }

    /// The next bytes for the controller.
    pub fn transmit(&mut self) -> Option<Vec<u8>> {
        self.out.pop_front()
    }

    pub fn event(&mut self) -> Option<Event> {
        self.events.pop_front()
    }

    /// When [`Host::poll`] next has something to do, if anything.
    pub fn next_deadline(&self) -> Option<u64> {
        let requests = self
            .connections
            .iter()
            .filter_map(|c| c.request.as_ref().map(|(_, at)| at + ATT_TIMEOUT_MS));
        let connecting = self.connecting.map(|(_, at)| at + CONNECT_TIMEOUT_MS);
        let pairings = self.connections.iter().filter_map(|c| {
            c.pairing
                .as_ref()
                .filter(|p| !p.over())
                .map(|p| p.at + smp::TIMEOUT_MS)
        });
        requests.chain(connecting).chain(pairings).min()
    }

    /// Time passed: gives up on a connection attempt or a request that
    /// took too long.
    pub fn poll(&mut self, now: u64) {
        self.now = now;
        if let Some((_, at)) = self.connecting
            && now >= at + CONNECT_TIMEOUT_MS
        {
            self.connecting = None;
            self.command(hci::LE_CREATE_CONNECTION_CANCEL, &[]);
        }
        let timed_out: Vec<u16> = self
            .connections
            .iter()
            .filter(|c| {
                c.request
                    .as_ref()
                    .is_some_and(|(_, at)| now >= at + ATT_TIMEOUT_MS)
            })
            .map(|c| c.handle)
            .collect();
        for handle in timed_out {
            self.disconnect(handle);
        }
        let handles: Vec<u16> = self.connections.iter().map(|c| c.handle).collect();
        for handle in handles {
            let out = self
                .connection(handle)
                .and_then(|c| c.pairing.as_mut())
                .map(|p| p.poll(now))
                .unwrap_or_default();
            self.smp_outputs(handle, out);
        }
    }

    fn command(&mut self, opcode: u16, parameters: &[u8]) {
        if self.command_pending {
            self.command_queue.push_back((opcode, parameters.to_vec()));
            return;
        }
        self.command_pending = true;
        self.out.push_back(
            Packet::Command {
                opcode,
                parameters: parameters.to_vec(),
            }
            .to_h4(),
        );
    }

    fn command_done(&mut self) {
        self.command_pending = false;
        if let Some((opcode, parameters)) = self.command_queue.pop_front() {
            self.command(opcode, &parameters);
        }
    }

    /// Starts scanning for devices; each one heard is an [`Event::Found`].
    pub fn start_scan(&mut self) {
        self.scan_wanted = true;
        if self.step == Step::Ready && !self.scanning {
            // Active scanning (asks for scan responses), every 30 ms, all
            // of it; own address public; every advertiser.
            self.command(
                hci::LE_SET_SCAN_PARAMETERS,
                &[0x01, 0x30, 0x00, 0x30, 0x00, 0x00, 0x00],
            );
            self.command(hci::LE_SET_SCAN_ENABLE, &[0x01, 0x00]);
        }
    }

    pub fn stop_scan(&mut self) {
        self.scan_wanted = false;
        if self.scanning {
            self.command(hci::LE_SET_SCAN_ENABLE, &[0x00, 0x00]);
        }
    }

    /// Advertises this device by name, so others find it and connect.
    pub fn advertise(&mut self, on: bool) {
        self.advertise_wanted = on;
        if self.step != Step::Ready || self.advertising == on {
            return;
        }
        if on {
            // ADV_IND every 100–150 ms, own address public, all channels,
            // anyone may scan and connect.
            self.command(
                hci::LE_SET_ADVERTISING_PARAMETERS,
                &[
                    0xa0, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0x07, 0x00,
                ],
            );
            let data = hci::advertising_data(&self.name);
            let mut parameters = alloc::vec![data.len() as u8];
            parameters.extend_from_slice(&data);
            parameters.resize(32, 0);
            self.command(hci::LE_SET_ADVERTISING_DATA, &parameters);
        }
        self.command(hci::LE_SET_ADVERTISE_ENABLE, &[u8::from(on)]);
    }

    /// Connects to a device heard while scanning (scanning stops for it),
    /// at the address it was last heard from.
    pub fn connect(&mut self, peer: Address) {
        if self.connecting.is_some() || self.connections.iter().any(|c| c.peer == peer) {
            return;
        }
        let peer = self
            .found
            .iter()
            .find(|f| f.address == peer)
            .map_or(peer, |f| f.air);
        if self.scanning {
            self.command(hci::LE_SET_SCAN_ENABLE, &[0x00, 0x00]);
        }
        self.connecting = Some((peer, self.now));
        let mut p = alloc::vec![0x30, 0x00, 0x30, 0x00, 0x00, 0x00];
        p.extend_from_slice(&peer.0);
        // Own address public; interval 30–50 ms, no latency, 720 ms
        // supervision timeout, no event length preference.
        p.extend_from_slice(&[0x00, 0x18, 0x00, 0x28, 0x00, 0x00, 0x00, 0x48, 0x00, 0, 0, 0, 0]);
        self.command(hci::LE_CREATE_CONNECTION, &p);
    }

    pub fn disconnect(&mut self, connection: u16) {
        if self.connections.iter().any(|c| c.handle == connection) {
            let mut p = connection.to_le_bytes().to_vec();
            p.push(hci::REASON_REMOTE_USER);
            self.command(hci::DISCONNECT, &p);
        }
    }

    pub fn connections(&self) -> impl Iterator<Item = (u16, Address)> + '_ {
        self.connections.iter().map(|c| (c.handle, c.peer))
    }

    fn connection(&mut self, handle: u16) -> Option<&mut Connection> {
        self.connections.iter_mut().find(|c| c.handle == handle)
    }

    /// Asks a peer for its services and characteristics: an
    /// [`Event::Discovered`] follows.
    pub fn discover(&mut self, connection: u16) {
        let Some(c) = self.connection(connection) else {
            return;
        };
        c.discovering = Some(Vec::new());
        self.request(
            connection,
            Request::Groups { start: 1 },
            att::read_by_group_type_request(1, 0xffff, gatt::PRIMARY_SERVICE),
        );
    }

    /// Reads a characteristic's value: an [`Event::Read`] follows.
    pub fn read(&mut self, connection: u16, handle: u16) {
        self.request(connection, Request::Read { handle }, att::read_request(handle));
    }

    /// Writes a characteristic's value: an [`Event::Written`] follows.
    pub fn write(&mut self, connection: u16, handle: u16, value: &[u8]) {
        self.request(
            connection,
            Request::Write { handle },
            att::write_request(handle, value),
        );
    }

    /// Writes a characteristic's value without a response (a command):
    /// nothing follows, and it does not wait behind other requests.
    pub fn write_command(&mut self, connection: u16, handle: u16, value: &[u8]) {
        self.send_att(connection, &att::write_command(handle, value));
    }

    /// Asks for notifications of a characteristic, through its client
    /// configuration descriptor (`configuration` of a found one).
    pub fn subscribe(&mut self, connection: u16, configuration: u16, on: bool) {
        self.write(connection, configuration, &[u8::from(on), 0]);
    }

    /// Changes one of this device's characteristics, telling every peer
    /// that subscribed.
    pub fn set_value(&mut self, handle: u16, value: &[u8]) {
        if let Some(a) = self.table.get_mut(handle) {
            a.value = value.to_vec();
        }
        let subscribed: Vec<u16> = self
            .connections
            .iter()
            .filter(|c| c.subscriptions.contains(&handle))
            .map(|c| c.handle)
            .collect();
        for connection in subscribed {
            let mtu = self.connection(connection).map_or(att::DEFAULT_MTU, |c| c.mtu);
            let cut = value.len().min(mtu - 3);
            self.send_att(connection, &att::notification(handle, &value[..cut]));
        }
    }

    fn request(&mut self, connection: u16, request: Request, pdu: Vec<u8>) {
        let now = self.now;
        let Some(c) = self.connection(connection) else {
            return;
        };
        if c.request.is_some() {
            c.queue.push_back((request, pdu));
            return;
        }
        c.request = Some((request, now));
        self.send_att(connection, &pdu);
    }

    fn next_request(&mut self, connection: u16) {
        let now = self.now;
        let Some(c) = self.connection(connection) else {
            return;
        };
        c.request = None;
        if let Some((request, pdu)) = c.queue.pop_front() {
            c.request = Some((request, now));
            self.send_att(connection, &pdu);
        }
    }

    fn send_att(&mut self, connection: u16, pdu: &[u8]) {
        let mut frame = (pdu.len() as u16).to_le_bytes().to_vec();
        frame.extend_from_slice(&CID_ATT.to_le_bytes());
        frame.extend_from_slice(pdu);
        self.send_l2cap(connection, frame);
    }

    fn send_l2cap(&mut self, connection: u16, frame: Vec<u8>) {
        let mut first = true;
        for chunk in frame.chunks(self.acl_len) {
            self.acl_queue.push_back((
                connection,
                Packet::Acl {
                    handle: connection,
                    continuing: !first,
                    data: chunk.to_vec(),
                }
                .to_h4(),
            ));
            first = false;
        }
        self.flush_acl();
    }

    fn flush_acl(&mut self) {
        while self.in_flight < self.acl_packets {
            let Some((_, bytes)) = self.acl_queue.pop_front() else {
                break;
            };
            self.in_flight += 1;
            self.out.push_back(bytes);
        }
    }

    /// Bytes from the controller, at time `now` (ms).
    pub fn receive(&mut self, bytes: &[u8], now: u64) {
        self.now = now;
        self.framer.push(bytes);
        while let Some(packet) = self.framer.packet() {
            match packet {
                Packet::Event { code, parameters } => self.on_event(code, &parameters),
                Packet::Acl {
                    handle,
                    continuing,
                    data,
                } => self.on_acl(handle, continuing, &data),
                Packet::Command { .. } => {}
            }
        }
    }

    fn on_event(&mut self, code: u8, p: &[u8]) {
        match code {
            hci::EVT_COMMAND_COMPLETE if p.len() >= 4 => {
                let opcode = u16::from_le_bytes([p[1], p[2]]);
                let status = p[3];
                self.on_command_complete(opcode, status, &p[4..]);
                self.command_done();
            }
            hci::EVT_COMMAND_STATUS if p.len() >= 4 => {
                let opcode = u16::from_le_bytes([p[2], p[3]]);
                if p[0] != hci::SUCCESS && opcode == hci::LE_CREATE_CONNECTION {
                    self.connecting = None;
                    self.resume_scan();
                }
                self.command_done();
            }
            hci::EVT_DISCONNECTION_COMPLETE if p.len() >= 4 => {
                let handle = u16::from_le_bytes([p[1], p[2]]);
                if let Some(i) = self.connections.iter().position(|c| c.handle == handle) {
                    let c = self.connections.remove(i);
                    self.acl_queue.retain(|(h, _)| *h != handle);
                    self.events.push_back(Event::Disconnected {
                        connection: handle,
                        peer: c.peer,
                    });
                    if !c.central && self.advertise_wanted {
                        self.advertising = false;
                        self.advertise(true);
                    }
                }
            }
            hci::EVT_NUMBER_OF_COMPLETED_PACKETS if !p.is_empty() => {
                let n = p[0] as usize;
                for i in 0..n {
                    if let Some(count) = p.get(1 + i * 4 + 2..1 + i * 4 + 4) {
                        let done = u16::from_le_bytes([count[0], count[1]]);
                        self.in_flight = self.in_flight.saturating_sub(done);
                    }
                }
                self.flush_acl();
            }
            hci::EVT_LE_META if !p.is_empty() => match p[0] {
                hci::LE_CONNECTION_COMPLETE if p.len() >= 19 => {
                    if p[1] != hci::SUCCESS {
                        self.connecting = None;
                        self.resume_scan();
                        return;
                    }
                    let handle = u16::from_le_bytes([p[2], p[3]]);
                    let central = p[4] == 0;
                    let air = Address(p[6..12].try_into().unwrap());
                    let peer = self.resolve(air);
                    let peer_kind = p[5];
                    self.connections.push(Connection {
                        handle,
                        peer,
                        air,
                        central,
                        mtu: att::DEFAULT_MTU,
                        rx: Vec::new(),
                        rx_len: 0,
                        request: None,
                        queue: VecDeque::new(),
                        discovering: None,
                        subscriptions: Vec::new(),
                        peer_kind,
                        encrypted: false,
                        pairing: None,
                        paired: None,
                    });
                    if central {
                        self.connecting = None;
                        self.resume_scan();
                    } else {
                        // The controller stopped advertising for this.
                        self.advertising = false;
                    }
                    self.events.push_back(Event::Connected {
                        connection: handle,
                        peer,
                        central,
                    });
                    if central {
                        // A device paired with before: the link private
                        // again at once, with the key kept.
                        if let Some(bond) = self.bonds.iter().find(|b| b.address == peer).copied() {
                            self.start_encryption(handle, &bond.key);
                        }
                        self.request(
                            handle,
                            Request::Mtu,
                            att::exchange_mtu_request(att::WANTED_MTU as u16),
                        );
                    }
                }
                hci::LE_ADVERTISING_REPORT if p.len() >= 2 => self.on_advertising_reports(&p[1..]),
                hci::LE_LONG_TERM_KEY_REQUEST if p.len() >= 13 => {
                    let handle = u16::from_le_bytes([p[1], p[2]]);
                    // Secure Connections' keys come with no random number
                    // or diversifier; a request with them is for a legacy key.
                    let plain = p[3..13].iter().all(|&b| b == 0);
                    let key = self
                        .connections
                        .iter()
                        .find(|c| c.handle == handle)
                        .and_then(|c| {
                            c.paired
                                .map(|(key, _)| key)
                                .or_else(|| self.bonds.iter().find(|b| b.address == c.peer).map(|b| b.key))
                        });
                    let mut reply = handle.to_le_bytes().to_vec();
                    match key.filter(|_| plain) {
                        Some(key) => {
                            reply.extend_from_slice(&key);
                            self.command(hci::LE_LONG_TERM_KEY_REQUEST_REPLY, &reply);
                        }
                        None => self.command(hci::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY, &reply),
                    }
                }
                _ => {}
            },
            hci::EVT_ENCRYPTION_CHANGE if p.len() >= 4 => {
                let handle = u16::from_le_bytes([p[1], p[2]]);
                let (status, on) = (p[0], p[3] != 0);
                let now = self.now;
                let Some(c) = self.connection(handle) else { return };
                let peer = c.peer;
                if status != hci::SUCCESS || !on {
                    c.encrypted = false;
                    let pairing = c.paired.take().is_some();
                    if pairing {
                        c.pairing = None;
                    }
                    self.events.push_back(if pairing {
                        Event::PairingFailed {
                            connection: handle,
                            peer,
                            reason: smp::UNSPECIFIED,
                        }
                    } else {
                        Event::EncryptionFailed {
                            connection: handle,
                            peer,
                            status,
                        }
                    });
                    return;
                }
                c.encrypted = true;
                // A pairing's key: the identities are handed over now, and
                // the bond kept once they are ([`smp::Output::Keys`]).
                let out = match (c.paired.is_some(), c.pairing.as_mut()) {
                    (true, Some(pairing)) => pairing.encrypted(now),
                    _ => Vec::new(),
                };
                self.smp_outputs(handle, out);
                let peer = self.connection(handle).map_or(peer, |c| c.peer);
                self.events.push_back(Event::Encrypted {
                    connection: handle,
                    peer,
                });
            }
            _ => {}
        }
    }

    fn resume_scan(&mut self) {
        if self.scan_wanted && !self.scanning {
            self.command(hci::LE_SET_SCAN_ENABLE, &[0x01, 0x00]);
        }
    }

    fn on_command_complete(&mut self, opcode: u16, status: u8, ret: &[u8]) {
        match (self.step, opcode) {
            (Step::Reset, hci::RESET) => {
                self.step = Step::Address;
                self.command(hci::READ_BD_ADDR, &[]);
            }
            (Step::Address, hci::READ_BD_ADDR) => {
                if ret.len() >= 6 {
                    self.address = Address(ret[..6].try_into().unwrap());
                }
                self.step = Step::EventMask;
                self.command(hci::SET_EVENT_MASK, &[0xff; 8]);
            }
            (Step::EventMask, hci::SET_EVENT_MASK) => {
                self.step = Step::LeEventMask;
                self.command(
                    hci::LE_SET_EVENT_MASK,
                    &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f],
                );
            }
            (Step::LeEventMask, hci::LE_SET_EVENT_MASK) => {
                self.step = Step::BufferSize;
                self.command(hci::LE_READ_BUFFER_SIZE, &[]);
            }
            (Step::BufferSize, hci::LE_READ_BUFFER_SIZE) => {
                if ret.len() >= 3 {
                    let len = u16::from_le_bytes([ret[0], ret[1]]) as usize;
                    if len > 0 && ret[2] > 0 {
                        self.acl_len = len;
                        self.acl_packets = u16::from(ret[2]);
                    }
                }
                self.step = Step::Ready;
                self.events.push_back(Event::Ready {
                    address: self.address,
                });
                if self.advertise_wanted {
                    self.advertise(true);
                }
                if self.scan_wanted {
                    self.start_scan();
                }
            }
            (Step::Ready, hci::LE_SET_SCAN_ENABLE) if status == hci::SUCCESS => {
                // What was asked: the queue holds at most one enable at a
                // time, so the wanted state is what it set.
                self.scanning = self.scan_wanted && self.connecting.is_none();
            }
            (Step::Ready, hci::LE_SET_ADVERTISE_ENABLE) if status == hci::SUCCESS => {
                self.advertising = self.advertise_wanted;
            }
            _ => {}
        }
    }

    fn on_advertising_reports(&mut self, mut p: &[u8]) {
        let count = p[0];
        p = &p[1..];
        for _ in 0..count {
            if p.len() < 9 {
                return;
            }
            let air = Address(p[2..8].try_into().unwrap());
            // A paired device that moved address is still the one known.
            let address = self.resolve(air);
            let len = p[8] as usize;
            if p.len() < 9 + len + 1 {
                return;
            }
            let data = &p[9..9 + len];
            let rssi = p[9 + len] as i8;
            p = &p[10 + len..];
            let name = hci::ad_name(data).map(String::from);
            let seen = self.now;
            let tell = match self.found.iter_mut().find(|f| f.address == address) {
                Some(f) => {
                    f.air = air;
                    f.rssi = rssi;
                    f.seen = seen;
                    let learnt = name.is_some() && f.name != name;
                    if learnt {
                        f.name = name.clone();
                        f.data = data.to_vec();
                    }
                    learnt
                }
                None => {
                    self.found.insert(
                        0,
                        Found {
                            address,
                            air,
                            name: name.clone(),
                            rssi,
                            seen,
                            data: data.to_vec(),
                        },
                    );
                    true
                }
            };
            if tell {
                self.events.push_back(Event::Found { address, name, rssi });
            }
        }
    }

    fn on_acl(&mut self, handle: u16, continuing: bool, data: &[u8]) {
        let Some(c) = self.connection(handle) else { return };
        if !continuing {
            if data.len() < 4 {
                return;
            }
            c.rx_len = 4 + u16::from_le_bytes([data[0], data[1]]) as usize;
            c.rx = data.to_vec();
        } else {
            c.rx.extend_from_slice(data);
        }
        if c.rx.len() < c.rx_len {
            return;
        }
        let frame = core::mem::take(&mut c.rx);
        let cid = u16::from_le_bytes([frame[2], frame[3]]);
        let payload = &frame[4..c.rx_len.min(frame.len())];
        match cid {
            CID_ATT => self.on_att(handle, payload),
            CID_SIGNALLING => self.on_signalling(handle, payload),
            CID_SMP => self.on_smp(handle, payload),
            _ => {}
        }
    }

    /// LE signalling: a connection parameter update request is accepted
    /// as it is; nothing else is answered.
    fn on_signalling(&mut self, connection: u16, p: &[u8]) {
        const CONNECTION_PARAMETER_UPDATE_REQUEST: u8 = 0x12;
        const CONNECTION_PARAMETER_UPDATE_RESPONSE: u8 = 0x13;
        if p.len() >= 4 && p[0] == CONNECTION_PARAMETER_UPDATE_REQUEST {
            let response = [CONNECTION_PARAMETER_UPDATE_RESPONSE, p[1], 2, 0, 0, 0];
            let mut frame = 6u16.to_le_bytes().to_vec();
            frame.extend_from_slice(&CID_SIGNALLING.to_le_bytes());
            frame.extend_from_slice(&response);
            self.send_l2cap(connection, frame);
        }
    }

    /// The security manager: a peer's pairing request answered (refused
    /// without [`Host::enable_pairing`]), a pairing under way carried on,
    /// and a bonded peer's request for security met with the key kept.
    fn on_smp(&mut self, connection: u16, p: &[u8]) {
        let now = self.now;
        let Some(&code) = p.first() else { return };
        let Some(c) = self.connections.iter().find(|c| c.handle == connection) else {
            return;
        };
        let (peer, central) = (c.peer, c.central);
        let busy = c.pairing.as_ref().is_some_and(|p| !p.over());
        match code {
            smp::PAIRING_REQUEST if !central && !busy => {
                let Some((own, peer_bytes)) = self.addresses(connection) else {
                    return;
                };
                let (io, irk) = (self.io, self.irk);
                let Some(random) = self.random.as_mut() else {
                    self.send_smp(connection, &[smp::PAIRING_FAILED, smp::NOT_SUPPORTED]);
                    return;
                };
                let (pairing, out) = smp::Pairing::answer(
                    io,
                    own,
                    peer_bytes,
                    irk,
                    p,
                    &mut |b: &mut [u8]| random.fill(b),
                    now,
                );
                if let Some(c) = self.connection(connection) {
                    c.pairing = Some(pairing);
                }
                self.smp_outputs(connection, out);
            }
            smp::SECURITY_REQUEST if central && !busy => {
                // Only a device paired with before: pairing a new one is
                // the person's to start.
                if let Some(bond) = self.bonds.iter().find(|b| b.address == peer).copied()
                    && !self.encrypted(connection)
                {
                    self.start_encryption(connection, &bond.key);
                }
            }
            _ if busy => {
                let out = self
                    .connection(connection)
                    .and_then(|c| c.pairing.as_mut())
                    .map(|pairing| pairing.receive(p, now))
                    .unwrap_or_default();
                self.smp_outputs(connection, out);
            }
            smp::PAIRING_FAILED => {}
            _ => self.send_smp(connection, &[smp::PAIRING_FAILED, smp::UNSPECIFIED]),
        }
    }

    fn on_att(&mut self, connection: u16, pdu: &[u8]) {
        let Some(&opcode) = pdu.first() else { return };
        match opcode {
            att::HANDLE_VALUE_NOTIFICATION if pdu.len() >= 3 => {
                self.events.push_back(Event::Notified {
                    connection,
                    handle: u16::from_le_bytes([pdu[1], pdu[2]]),
                    value: pdu[3..].to_vec(),
                });
            }
            att::ERROR_RESPONSE
            | att::EXCHANGE_MTU_RESPONSE
            | att::FIND_INFORMATION_RESPONSE
            | att::READ_BY_TYPE_RESPONSE
            | att::READ_RESPONSE
            | att::READ_BY_GROUP_TYPE_RESPONSE
            | att::WRITE_RESPONSE => self.on_response(connection, pdu),
            _ => {
                let mtu = self.connection(connection).map_or(att::DEFAULT_MTU, |c| c.mtu);
                let served = att::serve(&mut self.table, pdu, mtu);
                if opcode == att::EXCHANGE_MTU_REQUEST
                    && pdu.len() >= 3
                    && let Some(c) = self.connection(connection)
                {
                    c.mtu = (u16::from_le_bytes([pdu[1], pdu[2]]) as usize)
                        .clamp(att::DEFAULT_MTU, att::WANTED_MTU);
                }
                if let Some(response) = served.response {
                    self.send_att(connection, &response);
                }
                if let Some((handle, on)) = served.subscribed {
                    if let Some(c) = self.connection(connection) {
                        c.subscriptions.retain(|&h| h != handle);
                        if on {
                            c.subscriptions.push(handle);
                        }
                    }
                    self.events.push_back(Event::Subscribed {
                        connection,
                        handle,
                        on,
                    });
                }
                if let Some(handle) = served.written {
                    let value = self
                        .table
                        .get(handle)
                        .map(|a| a.value.clone())
                        .unwrap_or_default();
                    self.events.push_back(Event::Changed {
                        connection,
                        handle,
                        value,
                    });
                }
            }
        }
    }

    fn on_response(&mut self, connection: u16, pdu: &[u8]) {
        let Some(c) = self.connection(connection) else {
            return;
        };
        let Some((request, _)) = c.request.clone() else {
            return;
        };
        let opcode = pdu[0];
        let error = (opcode == att::ERROR_RESPONSE).then(|| pdu.get(4).copied().unwrap_or(0));
        match request {
            Request::Mtu => {
                if opcode == att::EXCHANGE_MTU_RESPONSE && pdu.len() >= 3 {
                    c.mtu = (u16::from_le_bytes([pdu[1], pdu[2]]) as usize)
                        .clamp(att::DEFAULT_MTU, att::WANTED_MTU);
                }
                self.next_request(connection);
            }
            Request::Groups { .. } => {
                let mut next = None;
                if opcode == att::READ_BY_GROUP_TYPE_RESPONSE && pdu.len() >= 2 {
                    let len = pdu[1] as usize;
                    let services = c.discovering.get_or_insert_with(Vec::new);
                    let mut last_end = 0;
                    for entry in pdu[2..].chunks_exact(len.max(6)) {
                        let handle = u16::from_le_bytes([entry[0], entry[1]]);
                        let end = u16::from_le_bytes([entry[2], entry[3]]);
                        if let Some(uuid) = Uuid::parse(&entry[4..]) {
                            services.push(Service {
                                uuid,
                                handle,
                                end,
                                characteristics: Vec::new(),
                            });
                        }
                        last_end = end;
                    }
                    if last_end < 0xffff {
                        next = Some(last_end + 1);
                    }
                }
                match next {
                    Some(start) => {
                        c.request = None;
                        self.request(
                            connection,
                            Request::Groups { start },
                            att::read_by_group_type_request(start, 0xffff, gatt::PRIMARY_SERVICE),
                        );
                    }
                    None => {
                        c.request = None;
                        self.discover_characteristics(connection, 0);
                    }
                }
            }
            Request::Characteristics { service, start: _ } => {
                let mut next_start = None;
                if opcode == att::READ_BY_TYPE_RESPONSE && pdu.len() >= 2 {
                    let len = pdu[1] as usize;
                    if let Some(services) = c.discovering.as_mut()
                        && let Some(s) = services.get_mut(service)
                    {
                        for entry in pdu[2..].chunks_exact(len.max(7)) {
                            let declaration = u16::from_le_bytes([entry[0], entry[1]]);
                            let properties = entry[2];
                            let handle = u16::from_le_bytes([entry[3], entry[4]]);
                            if let Some(uuid) = Uuid::parse(&entry[5..]) {
                                s.characteristics.push(Characteristic {
                                    uuid,
                                    properties,
                                    handle,
                                    configuration: None,
                                    value: Vec::new(),
                                });
                            }
                            if declaration < s.end {
                                next_start = Some(declaration + 1);
                            }
                        }
                        if let Some(start) = next_start
                            && start > s.end
                        {
                            next_start = None;
                        }
                    }
                }
                c.request = None;
                match next_start {
                    Some(start) => {
                        let end = c
                            .discovering
                            .as_ref()
                            .and_then(|s| s.get(service))
                            .map_or(0xffff, |s| s.end);
                        self.request(
                            connection,
                            Request::Characteristics { service, start },
                            att::read_by_type_request(start, end, gatt::CHARACTERISTIC),
                        );
                    }
                    None => self.discover_characteristics(connection, service + 1),
                }
            }
            Request::Read { handle } => {
                let event = match error {
                    None if opcode == att::READ_RESPONSE => Event::Read {
                        connection,
                        handle,
                        value: pdu[1..].to_vec(),
                    },
                    _ => Event::ReadFailed {
                        connection,
                        handle,
                        error: error.unwrap_or(att::ERR_REQUEST_NOT_SUPPORTED),
                    },
                };
                self.events.push_back(event);
                self.next_request(connection);
            }
            Request::Write { handle } => {
                self.events.push_back(Event::Written {
                    connection,
                    handle,
                    ok: error.is_none() && opcode == att::WRITE_RESPONSE,
                });
                self.next_request(connection);
            }
        }
    }

    /// Asks for the characteristics of the `index`th service found, or
    /// finishes the discovery.
    fn discover_characteristics(&mut self, connection: u16, index: usize) {
        let Some(c) = self.connection(connection) else {
            return;
        };
        let Some(services) = c.discovering.as_mut() else {
            return;
        };
        match services.get(index) {
            Some(s) if s.handle < s.end => {
                let (start, end) = (s.handle + 1, s.end);
                self.request(
                    connection,
                    Request::Characteristics {
                        service: index,
                        start,
                    },
                    att::read_by_type_request(start, end, gatt::CHARACTERISTIC),
                );
            }
            Some(_) => self.discover_characteristics(connection, index + 1),
            None => {
                let mut services = c.discovering.take().unwrap_or_default();
                // A characteristic that notifies has its client configuration
                // right after its value, as every table built here does and
                // nearly every device's.
                for s in &mut services {
                    let declarations: Vec<u16> = s.characteristics.iter().map(|ch| ch.handle - 1).collect();
                    for (i, ch) in s.characteristics.iter_mut().enumerate() {
                        let next = declarations.get(i + 1).copied().unwrap_or(s.end + 1);
                        if ch.properties & gatt::PROP_NOTIFY != 0 && ch.handle + 1 < next {
                            ch.configuration = Some(ch.handle + 1);
                        }
                    }
                }
                self.events.push_back(Event::Discovered { connection, services });
                self.next_request(connection);
            }
        }
    }
}