garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/bt.rs

raw

//! The Bluetooth service: this device's host stack (`pinnacle_bt`) over
//! the kernel's port to the controller, offered to apps as the service `bt`
//! (`pinnacle_ui::bluetooth` has the messages). It advertises this device
//! by name, and serves this device's contact card over GATT, so two
//! Pinnacles side by side can become contacts with no network: a card a
//! peer writes to it is added as a contact through the p2p service.
//!
//! It pairs (LE Secure Connections, `pinnacle_bt::smp`): an app asks it to
//! pair with a connected device, the number to compare goes to the apps
//! (and, asked by a device nearby while no app listens, to a notification
//! that opens Bluetooth), and each device paired with is kept in the data
//! vault (`data:/bt/bonds`: its address, key, identity key and name), so
//! its link is encrypted again on every connection without asking, and a
//! phone or watch that moves to a new private address is still known. This
//! device's own identity key, handed to each device it pairs with, is made
//! once and kept beside them (`data:/bt/identity`).
//!
//! A keyboard pairs by a passkey this device shows and its person types on
//! it. A paired keyboard, connected and its link encrypted, is asked for
//! its boot reports (HID over GATT, `pinnacle_bt::hogp`), and its keys go
//! to the display server as a USB keyboard's do, on the channel the display
//! server gave this service when it started it (handle 1, with argument 1):
//! no other program can type that way. It stays connected while the person
//! types, whether the Bluetooth app is open or not.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_bt::gatt::{self, Characteristic, Service, Uuid};
use pinnacle_bt::hogp::{self, BootKeyboard};
use pinnacle_bt::{Address, Bond, Event, Host, smp};
use pinnacle_hid::Keyboard;
use pinnacle_rt::abi::InputEvent;
use pinnacle_rt::{Channel, Handle, Received, fs, println};
use pinnacle_ui::bluetooth as protocol;
use pinnacle_ui::p2p;

/// A controller that does not answer the reset within this long is reset
/// again: on QEMU the other end of the port may connect after we spoke.
const READY_RETRY_MS: u64 = 2000;

fn services(card: &[u8]) -> Vec<Service> {
    alloc::vec![
        Service::new(
            Uuid::Short(gatt::DEVICE_INFORMATION),
            alloc::vec![
                Characteristic::new(Uuid::Short(gatt::MANUFACTURER_NAME), gatt::PROP_READ, b"Pinnacle"),
                Characteristic::new(Uuid::Short(gatt::MODEL_NUMBER), gatt::PROP_READ, b"Pinnacle 0.1"),
            ],
        ),
        Service::new(
            Uuid::Long(gatt::PINNACLE_SERVICE),
            alloc::vec![Characteristic::new(
                Uuid::Long(gatt::PINNACLE_CARD),
                gatt::PROP_READ | gatt::PROP_WRITE,
                card,
            )],
        ),
    ]
}

/// Where Bluetooth keeps `what` (the paired devices, this device's
/// identity): in the vault, once there is one.
fn kept(what: &str) -> String {
    if fs::disk("data").is_some() {
        alloc::format!("data:/bt/{what}")
    } else {
        alloc::format!("system:/bt-{what}")
    }
}

/// This device's identity resolving key, made once and kept: devices
/// paired with know it by it, so it must not change between starts.
fn identity() -> [u8; 16] {
    let path = kept("identity");
    if let Some(irk) = fs::read(&path).and_then(|b| <[u8; 16]>::try_from(b.as_slice()).ok()) {
        return irk;
    }
    let mut irk = [0u8; 16];
    pinnacle_rt::random(&mut irk);
    fs::create_dir(path.rsplit_once('/').map_or("system:/", |(dir, _)| dir));
    fs::write(&path, &irk);
    irk
}

/// The paired devices kept: each a bond, a name length and the name.
fn load_bonds() -> Vec<(Bond, String)> {
    let b = fs::read(&kept("bonds")).unwrap_or_default();
    let mut out = Vec::new();
    let mut at = 0;
    while let Some((bond, size)) = b.get(at..).and_then(Bond::from_bytes) {
        let len = b.get(at + size).copied().unwrap_or(0) as usize;
        let Some(name) = b.get(at + size + 1..at + size + 1 + len) else {
            break;
        };
        out.push((bond, String::from_utf8_lossy(name).into_owned()));
        at += size + 1 + len;
    }
    out
}

fn save_bonds(bonds: &[(Bond, String)]) {
    let mut b = Vec::new();
    for (bond, name) in bonds {
        b.extend_from_slice(&bond.to_bytes());
        let name = &name.as_bytes()[..name.len().min(255)];
        b.push(name.len() as u8);
        b.extend_from_slice(name);
    }
    let path = kept("bonds");
    fs::create_dir(path.rsplit_once('/').map_or("system:/", |(dir, _)| dir));
    fs::write(&path, &b);
}

fn bonds_bytes(bonds: &[(Bond, String)]) -> Vec<u8> {
    let mut b = alloc::vec![bonds.len().min(255) as u8];
    for (bond, name) in bonds.iter().take(255) {
        b.extend(protocol::paired_bytes(&protocol::Paired {
            address: bond.address,
            compared: bond.compared,
            name: (!name.is_empty()).then(|| name.clone()),
        }));
    }
    b
}

/// A host for this device: its name, its services, pairing on (fresh
/// secrets from the kernel, a screen with yes and no, its identity), the
/// bonds kept.
fn new_host(name: &str, card: &[u8], irk: [u8; 16], bonds: &[(Bond, String)]) -> Host {
    let mut host = Host::new(name, services(card));
    let mut seed = [0u8; 32];
    pinnacle_rt::random(&mut seed);
    host.enable_pairing(seed, smp::DISPLAY_YES_NO);
    host.set_identity(irk);
    for (bond, _) in bonds {
        host.remember(*bond);
    }
    host.advertise(true);
    host
}

/// The devices heard, for [`protocol::DEVICES_ARE`]: paired ones by their
/// identity, whatever address they moved to.
fn devices_bytes(host: &Host) -> Vec<u8> {
    let found = host.found();
    let mut b = alloc::vec![found.len().min(255) as u8];
    for f in found.iter().take(255) {
        b.extend(protocol::device_bytes(f.address, f.rssi, f.name.as_deref()));
    }
    b
}

fn said(clients: &[Channel], kind: u8, body: &[u8]) {
    let m = protocol::message(kind, body);
    for c in clients {
        c.send(&m, Vec::new());
    }
}

fn connection_bytes(connection: u16, address: &pinnacle_bt::Address) -> Vec<u8> {
    let mut b = connection.to_le_bytes().to_vec();
    b.extend_from_slice(&address.0);
    b
}

/// KEYBOARD's body: the keyboard on `connection` types into this device,
/// or (`on` false) stopped.
fn keyboard_bytes(connection: u16, address: &pinnacle_bt::Address, on: bool) -> Vec<u8> {
    let mut b = connection_bytes(connection, address);
    b.push(u8::from(on));
    b
}

/// The name a device nearby gave in its advertising, if it gave one.
fn found_name(host: &Host, address: Address) -> Option<String> {
    host.found()
        .iter()
        .find(|f| f.address == address)
        .and_then(|f| f.name.clone())
}

/// A pairing asked by a device nearby with no app open: a notification,
/// whose tap opens Bluetooth. The display server is connected to the
/// first time.
fn notify(display: &mut Option<Channel>, who: &str, text: &str) {
    if display.is_none() {
        *display = pinnacle_rt::connect("display");
    }
    if let Some(display) = display {
        pinnacle_ui::notify(display, "bluetooth", who, text);
    }
}

/// A keyboard typing into this device: its connection, who, the handle
/// its reports come by, and its keys held.
struct Typing {
    connection: u16,
    peer: Address,
    input: u16,
    keys: Keyboard,
}

/// Keyboards among the devices connected: those found by their services,
/// and those typing.
#[derive(Default)]
struct Keyboards {
    found: Vec<(u16, BootKeyboard)>,
    typing: Vec<Typing>,
}

impl Keyboards {
    /// Starts a keyboard found on `connection` typing, once its link is
    /// encrypted with the key of a pairing: never one that is not paired.
    fn start(&mut self, host: &mut Host, connection: u16, clients: &[Channel]) {
        if self.typing.iter().any(|t| t.connection == connection) || !host.encrypted(connection) {
            return;
        }
        let Some(&(_, keyboard)) = self.found.iter().find(|(c, _)| *c == connection) else {
            return;
        };
        let Some(peer) = host
            .connections()
            .find(|(c, _)| *c == connection)
            .map(|(_, peer)| peer)
        else {
            return;
        };
        if !host.bonds().iter().any(|b| b.address == peer) {
            return;
        }
        hogp::start(host, connection, &keyboard);
        self.typing.push(Typing {
            connection,
            peer,
            input: keyboard.input,
            keys: Keyboard::default(),
        });
        println!("bt: keys from {} go to the app in front", peer.text());
        let b = keyboard_bytes(connection, &peer, true);
        said(clients, protocol::KEYBOARD, &b);
    }

    /// A report from a keyboard typing: its keys, to the display server.
    fn report(&mut self, host: &Host, connection: u16, handle: u16, value: &[u8], out: Option<&Channel>) {
        if !host.encrypted(connection) {
            return;
        }
        if let Some(t) = self
            .typing
            .iter_mut()
            .find(|t| t.connection == connection && t.input == handle)
        {
            send_keys(out, t.keys.report(value));
        }
    }

    /// A connection went: whatever its keyboard held is let go.
    fn gone(&mut self, connection: u16, clients: &[Channel], out: Option<&Channel>) {
        self.found.retain(|(c, _)| *c != connection);
        if let Some(i) = self.typing.iter().position(|t| t.connection == connection) {
            let mut t = self.typing.remove(i);
            send_keys(out, t.keys.release_all());
            let b = keyboard_bytes(connection, &t.peer, false);
            said(clients, protocol::KEYBOARD, &b);
        }
    }

    fn typing(&self, connection: u16) -> bool {
        self.typing.iter().any(|t| t.connection == connection)
    }
}

/// Keys to the display server, as a keyboard's own.
fn send_keys(out: Option<&Channel>, keys: Vec<pinnacle_hid::Key>) {
    let Some(out) = out else { return };
    for key in keys {
        let event = InputEvent {
            kind: InputEvent::KEY,
            code: key.code,
            value: i32::from(key.down),
            ..InputEvent::default()
        };
        out.send(&event.to_bytes(), Vec::new());
    }
}

#[unsafe(no_mangle)]
fn main(argument: u64) -> u64 {
    let Some(port) = pinnacle_rt::bluetooth_port() else {
        println!("bt: no controller");
        return 1;
    };
    // Where a keyboard's keys go: the display server's channel, given at
    // start.
    // SAFETY: argument 1 says the display server gave it, as handle 1.
    let keys_out = (argument == 1).then(|| Channel(unsafe { Handle::from_raw(1) }));
    let mut keyboards = Keyboards::default();
    let name = fs::read_string("system:/settings/name")
        .map(|n| n.trim().into())
        .filter(|n: &String| !n.is_empty())
        .unwrap_or_else(|| "Pinnacle".into());
    // This device's card, from the p2p service, for the card characteristic.
    let p2p = p2p::Client::connect(3000);
    let mut pending = Vec::new();
    let card = p2p.as_ref().map(|c| c.card(&mut pending)).unwrap_or_default();
    let mut bonds = load_bonds();
    let irk = identity();
    let mut host = new_host(&name, &card, irk, &bonds);
    // A pairing asked by a device nearby, waiting on the person: told to
    // every app that connects until it is answered.
    let mut asking: Option<(u8, Vec<u8>)> = None;
    let mut display: Option<Channel> = None;
    let card_handle = host.table().value_handle(
        Uuid::Long(gatt::PINNACLE_SERVICE),
        Uuid::Long(gatt::PINNACLE_CARD),
    );
    let service = pinnacle_rt::register("bt").expect("could not register bt");
    let mut clients: Vec<Channel> = Vec::new();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    let mut started = pinnacle_rt::time();
    let mut announced = false;
    loop {
        while let Some(bytes) = host.transmit() {
            port.send(&bytes, Vec::new());
        }
        let now = pinnacle_rt::time();
        let retry = (!host.ready()).then_some(started + READY_RETRY_MS);
        let deadline = host.next_deadline().into_iter().chain(retry).min();
        let mut channels: Vec<&Channel> = alloc::vec![&service, &port];
        channels.extend(clients.iter());
        let received = pinnacle_rt::receive(&channels, &mut buffer, deadline);
        drop(channels);
        match received {
            Received::Timeout => {
                let now = pinnacle_rt::time();
                host.poll(now);
                if !host.ready() && now >= started + READY_RETRY_MS {
                    // Ask again: the first reset may have gone nowhere.
                    host = new_host(&name, &card, irk, &bonds);
                    started = now;
                }
            }
            Received::Message {
                index: 0,
                mut handles,
                ..
            } if !handles.is_empty() => {
                let client = Channel(handles.remove(0));
                if let Some((kind, ask)) = &asking {
                    client.send(&protocol::message(*kind, ask), Vec::new());
                }
                clients.push(client);
            }
            Received::Message { index: 1, len, .. } => host.receive(&buffer[..len], now),
            Received::Closed { index: 1 } => {
                println!("bt: the controller's port closed");
                return 1;
            }
            Received::Message { index, len, .. } if index >= 2 => {
                let body = &buffer[1..len];
                let u16_at = |at: usize| body.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]]));
                match (buffer[0], u16_at(0)) {
                    (protocol::SCAN, _) => host.start_scan(),
                    (protocol::STOP, _) => host.stop_scan(),
                    (protocol::CONNECT, _) => {
                        if let Some(a) = body.get(..6) {
                            let address = pinnacle_bt::Address(a.try_into().unwrap());
                            // A keyboard typing is connected already.
                            let connected = host
                                .connections()
                                .find(|(_, peer)| *peer == address)
                                .map(|(c, _)| c);
                            match connected {
                                Some(c) => {
                                    let mut b = connection_bytes(c, &address);
                                    b.push(1);
                                    let client = &clients[index - 2];
                                    client.send(&protocol::message(protocol::CONNECTED, &b), Vec::new());
                                    if host.encrypted(c) {
                                        let b = connection_bytes(c, &address);
                                        client.send(&protocol::message(protocol::ENCRYPTED, &b), Vec::new());
                                    }
                                    if keyboards.typing(c) {
                                        let b = keyboard_bytes(c, &address, true);
                                        client.send(&protocol::message(protocol::KEYBOARD, &b), Vec::new());
                                    }
                                }
                                None => host.connect(address),
                            }
                        }
                    }
                    // A keyboard typing stays connected when the app is
                    // done with it; Forget drops it.
                    (protocol::DISCONNECT, Some(c)) if keyboards.typing(c) => {}
                    (protocol::DISCONNECT, Some(c)) => host.disconnect(c),
                    (protocol::DISCOVER, Some(c)) => host.discover(c),
                    (protocol::READ, Some(c)) => {
                        if let Some(h) = u16_at(2) {
                            host.read(c, h);
                        }
                    }
                    (protocol::WRITE, Some(c)) => {
                        if let Some(h) = u16_at(2) {
                            host.write(c, h, &body[4..]);
                        }
                    }
                    (protocol::SUBSCRIBE, Some(c)) => {
                        if let (Some(h), Some(&on)) = (u16_at(2), body.get(4)) {
                            host.subscribe(c, h, on != 0);
                        }
                    }
                    (protocol::DEVICES, _) => {
                        clients[index - 2].send(
                            &protocol::message(protocol::DEVICES_ARE, &devices_bytes(&host)),
                            Vec::new(),
                        );
                    }
                    (protocol::PAIR, Some(c)) => host.pair(c),
                    (protocol::CONFIRM, Some(c)) => {
                        asking = None;
                        host.confirm(c, body.get(2) == Some(&1));
                    }
                    (protocol::FORGET, _) => {
                        if let Some(a) = body.get(..6) {
                            let address = Address(a.try_into().unwrap());
                            host.forget(address);
                            bonds.retain(|(b, _)| b.address != address);
                            save_bonds(&bonds);
                            println!("bt: forgot {}", address.text());
                            said(&clients, protocol::BONDS_ARE, &bonds_bytes(&bonds));
                        }
                    }
                    (protocol::BONDS, _) => {
                        clients[index - 2].send(
                            &protocol::message(protocol::BONDS_ARE, &bonds_bytes(&bonds)),
                            Vec::new(),
                        );
                    }
                    (protocol::STATE, _) => {
                        let mut b = alloc::vec![u8::from(host.ready())];
                        b.extend_from_slice(&host.address().0);
                        b.extend_from_slice(name.as_bytes());
                        clients[index - 2].send(&protocol::message(protocol::STATE_IS, &b), Vec::new());
                    }
                    _ => {}
                }
            }
            Received::Closed { index } if index >= 2 => {
                clients.remove(index - 2);
            }
            _ => {}
        }
        while let Some(event) = host.event() {
            match event {
                Event::Ready { address } => {
                    if !announced {
                        println!("bt: ready, {} as {name}", address.text());
                        announced = true;
                    }
                    let mut b = alloc::vec![1u8];
                    b.extend_from_slice(&address.0);
                    b.extend_from_slice(name.as_bytes());
                    said(&clients, protocol::STATE_IS, &b);
                }
                Event::Found { address, name, rssi } => {
                    if let Some(name) = &name {
                        println!("bt: found {name} ({})", address.text());
                    }
                    said(
                        &clients,
                        protocol::DEVICE,
                        &protocol::device_bytes(address, rssi, name.as_deref()),
                    );
                }
                Event::Connected {
                    connection,
                    peer,
                    central,
                } => {
                    println!("bt: connected to {}", peer.text());
                    let mut b = connection_bytes(connection, &peer);
                    b.push(u8::from(central));
                    said(&clients, protocol::CONNECTED, &b);
                }
                Event::Disconnected { connection, peer } => {
                    if asking
                        .as_ref()
                        .is_some_and(|(_, a)| a[..2] == connection.to_le_bytes())
                    {
                        asking = None;
                    }
                    keyboards.gone(connection, &clients, keys_out.as_ref());
                    said(
                        &clients,
                        protocol::DISCONNECTED,
                        &connection_bytes(connection, &peer),
                    );
                }
                Event::Discovered { connection, services } => {
                    let mut b = connection.to_le_bytes().to_vec();
                    b.extend(protocol::services_bytes(&services));
                    said(&clients, protocol::SERVICES, &b);
                    if let Some(keyboard) = hogp::boot_keyboard(&services) {
                        keyboards.found.retain(|(c, _)| *c != connection);
                        keyboards.found.push((connection, keyboard));
                        keyboards.start(&mut host, connection, &clients);
                    }
                }
                Event::Read {
                    connection,
                    handle,
                    value,
                } => {
                    let mut b = connection.to_le_bytes().to_vec();
                    b.extend_from_slice(&handle.to_le_bytes());
                    b.push(0);
                    b.extend_from_slice(&value);
                    said(&clients, protocol::VALUE, &b);
                }
                Event::ReadFailed {
                    connection,
                    handle,
                    error,
                } => {
                    let mut b = connection.to_le_bytes().to_vec();
                    b.extend_from_slice(&handle.to_le_bytes());
                    b.push(error.max(1));
                    said(&clients, protocol::VALUE, &b);
                }
                Event::Written {
                    connection,
                    handle,
                    ok,
                } => {
                    let mut b = connection.to_le_bytes().to_vec();
                    b.extend_from_slice(&handle.to_le_bytes());
                    b.push(u8::from(ok));
                    said(&clients, protocol::WRITTEN, &b);
                }
                // What is typed goes to the app in front, and to no app
                // listening here.
                Event::Notified {
                    connection,
                    handle,
                    value,
                } if keyboards.typing(connection) => {
                    keyboards.report(&host, connection, handle, &value, keys_out.as_ref());
                }
                Event::Notified {
                    connection,
                    handle,
                    value,
                } => {
                    let mut b = connection.to_le_bytes().to_vec();
                    b.extend_from_slice(&handle.to_le_bytes());
                    b.extend_from_slice(&value);
                    said(&clients, protocol::NOTIFIED, &b);
                }
                Event::Changed { handle, value, .. } if Some(handle) == card_handle => {
                    // A peer handed us their card: a contact, through p2p.
                    if value.len() == p2p::CARD_SIZE
                        && let Some(p2p) = &p2p
                    {
                        p2p.add_contact(&value);
                        println!("bt: a contact card received over Bluetooth");
                    }
                    // Our own card stays what it was.
                    host.set_value(handle, &card);
                }
                Event::Confirm {
                    connection,
                    peer,
                    code,
                } => {
                    let mut b = connection_bytes(connection, &peer);
                    if let Some(code) = code {
                        b.extend_from_slice(&code.to_le_bytes());
                    }
                    println!("bt: pairing with {} asks the person", peer.text());
                    said(&clients, protocol::ASK, &b);
                    if clients.is_empty() {
                        let who = found_name(&host, peer).unwrap_or_else(|| peer.text());
                        let text = match code {
                            Some(code) => alloc::format!("Pair if it shows {code:06}"),
                            None => String::from("Wants to pair"),
                        };
                        notify(&mut display, &who, &text);
                    }
                    asking = Some((protocol::ASK, b));
                }
                Event::Passkey {
                    connection,
                    peer,
                    passkey: Some(passkey),
                } => {
                    let who = found_name(&host, peer).unwrap_or_else(|| peer.text());
                    println!("bt: pairing with {who}: type {passkey:06} on it");
                    let mut b = connection_bytes(connection, &peer);
                    b.extend_from_slice(&passkey.to_le_bytes());
                    said(&clients, protocol::PASSKEY, &b);
                    if clients.is_empty() {
                        let text = alloc::format!("Type {passkey:06} on it, then Enter");
                        notify(&mut display, &who, &text);
                    }
                    asking = Some((protocol::PASSKEY, b));
                }
                // This device shows; it is never the one to type (it pairs
                // as a display with buttons), so a peer asking that is refused.
                Event::Passkey { connection, .. } => host.confirm(connection, false),
                Event::Paired { connection, bond } => {
                    asking = None;
                    let name = found_name(&host, bond.address).unwrap_or_default();
                    println!(
                        "bt: paired with {}",
                        if name.is_empty() {
                            bond.address.text()
                        } else {
                            name.clone()
                        }
                    );
                    bonds.retain(|(b, _)| b.address != bond.address);
                    bonds.push((bond, name));
                    save_bonds(&bonds);
                    let mut b = connection_bytes(connection, &bond.address);
                    b.push(u8::from(bond.compared));
                    said(&clients, protocol::PAIRED, &b);
                    said(&clients, protocol::BONDS_ARE, &bonds_bytes(&bonds));
                    // A device paired from a private address is listed by
                    // its identity from now on.
                    said(&clients, protocol::DEVICES_ARE, &devices_bytes(&host));
                    // A keyboard types from now on.
                    keyboards.start(&mut host, connection, &clients);
                }
                Event::PairingFailed {
                    connection,
                    peer,
                    reason,
                } => {
                    asking = None;
                    println!(
                        "bt: pairing with {} failed: {}",
                        peer.text(),
                        smp::reason_text(reason)
                    );
                    let mut b = connection_bytes(connection, &peer);
                    b.push(reason);
                    said(&clients, protocol::PAIR_FAILED, &b);
                }
                Event::Encrypted { connection, peer } => {
                    println!("bt: the link to {} is encrypted", peer.text());
                    said(
                        &clients,
                        protocol::ENCRYPTED,
                        &connection_bytes(connection, &peer),
                    );
                    // A paired keyboard connected again types at once.
                    keyboards.start(&mut host, connection, &clients);
                }
                Event::EncryptionFailed { connection, peer, .. } => {
                    println!("bt: {} refused the key kept", peer.text());
                    said(
                        &clients,
                        protocol::KEY_REFUSED,
                        &connection_bytes(connection, &peer),
                    );
                }
                Event::Changed { .. } | Event::Subscribed { .. } => {}
            }
        }
    }
}