garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/p2p.rs

raw

//! The peer-to-peer service: this device's node of the DHT, its identity and
//! contacts, and the end-to-end encrypted sessions with them. Apps reach it
//! as the service `p2p`; text messages it keeps on disk, both ways, so they
//! are there when the Messages app opens, and calls' frames it passes on.
//!
//! The person's own, in the data vault (`data:/p2p`, see [`own`]; on the
//! system disk on a device without one):
//! - `identity`: the 32-byte secret seed (made on first start);
//! - `contacts/<key in hex>`: each contact's signed card;
//! - `book.vcf`: the address book, every entry a vCard (`Book`): each
//!   contact with a card, and people with no device;
//! - `messages/<key in hex>`: the conversation, records of direction (0 in,
//!   1 out, 2 out but gone as a text to their phone: `text_instead`),
//!   time (u64 ms since 1970), length (u16), text.
//!
//! Settings, on the system disk:
//! - `/settings/name`: the name on this device's card;
//! - `/settings/peers`: devices to join the DHT through, `ip:port` a line;
//! - `/settings/public-address`: where others reach this device, if known;
//! - `/settings/p2p-epoch`: how many times the service has started (u64),
//!   so what it stamps (presence, handshakes) only grows across restarts.
//!   Not secret, and on the system disk so a vault made later never sets
//!   it back: contacts would refuse its handshakes as replayed.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_contacts::{self as contacts, Entry};
use pinnacle_p2p::delivery::Delivery;
use pinnacle_p2p::identity::{Card, Identity, Key};
use pinnacle_p2p::{Addr, Event, Node, link};
use pinnacle_records::verbs;
use pinnacle_records::{Output, Record};
use pinnacle_rt::{Channel, Memory, Received, fs, net, println};
use pinnacle_ui::command;
use pinnacle_ui::p2p as protocol;
use pinnacle_ui::remote::{self, Frames};

const PORT: u16 = 7000;
const POLL_MS: u64 = 500;

fn hex(key: &Key) -> String {
    // The first 16 bytes: names on disk stay under the file system's 58.
    key[..16].iter().map(|b| alloc::format!("{b:02x}")).collect()
}

fn parse_addr(text: &str) -> Option<Addr> {
    let (ip, port) = text.trim().rsplit_once(':')?;
    Some(Addr {
        ip: net::parse_ipv4(ip)?,
        port: port.parse().ok()?,
    })
}

/// Milliseconds since 1970 from the board's clock, else since boot.
fn now_wall() -> u64 {
    match pinnacle_rt::clock() {
        0 => pinnacle_rt::time(),
        s => s * 1000 + pinnacle_rt::time() % 1000,
    }
}

fn identity() -> Identity {
    let seed = match fs::read(&own("identity")) {
        Some(seed) if seed.len() == 32 => seed.try_into().unwrap(),
        _ => {
            let mut seed = [0u8; 32];
            pinnacle_rt::random(&mut seed);
            let path = own("identity");
            fs::create_dir(path.rsplit_once('/').map_or("system:/", |(dir, _)| dir));
            fs::write(&path, &seed);
            seed
        }
    };
    Identity::from_seed(seed)
}

/// This start's epoch: one more than the last.
fn epoch() -> u64 {
    let path = "system:/settings/p2p-epoch";
    let last = fs::read(path)
        .and_then(|b| b.try_into().ok())
        .map_or(0, u64::from_le_bytes);
    fs::write(path, &(last + 1).to_le_bytes());
    last + 1
}

/// Where the person's own p2p data is: the identity, the contacts and
/// the messages. In the data vault once it is open (the kernel moved them
/// there); without one, on the system disk, where they always were.
fn own(what: &str) -> String {
    if fs::disk("data").is_some() {
        alloc::format!("data:/p2p/{what}")
    } else if what == "identity" {
        "system:/settings/identity".into()
    } else {
        alloc::format!("system:/{what}")
    }
}

/// The newest messages of the conversation with `contact` that fit one
/// message to an app, whole and oldest first: apps read conversations
/// through this service, not from its files, which they cannot reach.
fn newest(contact: &Key) -> Vec<u8> {
    let log = fs::read(&alloc::format!("{}/{}", own("messages"), hex(contact))).unwrap_or_default();
    let mut starts = Vec::new();
    let mut at = 0;
    while at + 11 <= log.len() {
        starts.push(at);
        at += 11 + usize::from(u16::from_le_bytes([log[at + 9], log[at + 10]]));
    }
    let end = at.min(log.len());
    let from = starts
        .into_iter()
        .find(|&s| end - s <= pinnacle_rt::abi::MAX_MESSAGE)
        .unwrap_or(end);
    log[from..end].to_vec()
}

/// Appends a message to the conversation with `contact`.
fn keep(contact: &Key, outgoing: bool, text: &[u8]) {
    let path = alloc::format!("{}/{}", own("messages"), hex(contact));
    let mut log = fs::read(&path).unwrap_or_default();
    log.push(u8::from(outgoing));
    log.extend_from_slice(&now_wall().to_le_bytes());
    let text = &text[..text.len().min(u16::MAX as usize)];
    log.extend_from_slice(&(text.len() as u16).to_le_bytes());
    log.extend_from_slice(text);
    fs::create_dir(&own("messages"));
    fs::write(&path, &log);
}

/// Marks the newest message sent to `contact` as `text` as gone by text
/// to their phone (direction 2), so the conversation says so.
fn mark_texted(contact: &Key, text: &[u8]) {
    let path = alloc::format!("{}/{}", own("messages"), hex(contact));
    let Some(mut log) = fs::read(&path) else {
        return;
    };
    let mut found = None;
    let mut at = 0;
    while at + 11 <= log.len() {
        let len = usize::from(u16::from_le_bytes([log[at + 9], log[at + 10]]));
        if log[at] == 1 && log.get(at + 11..at + 11 + len) == Some(text) {
            found = Some(at);
        }
        at += 11 + len;
    }
    if let Some(at) = found {
        log[at] = 2;
        fs::write(&path, &log);
    }
}

/// A text that had no answer from `contact`'s device in time
/// (`pinnacle_p2p::delivery`): sent to their phone number through the
/// phone service instead, as Calls calls it, and taken back from what
/// waits for a session, so it does not come twice. Stays waiting there
/// when they have no number or this device no modem.
fn text_instead(node: &mut Node, book: &Book, contact: &Key, text: &[u8]) {
    let entry = book.0.entries.iter().find(|e| e.key == Some(*contact));
    let name = entry.map_or("a contact", |e| e.name.as_str());
    let Some(number) = entry.and_then(|e| e.phones.first()) else {
        println!("p2p: {name} not reachable online, and has no number");
        return;
    };
    let Some(phone) = pinnacle_rt::connect(pinnacle_ui::phone::SERVICE) else {
        println!("p2p: {name} not reachable online, and no modem to text with");
        return;
    };
    let mut body = alloc::format!("{number}\n").into_bytes();
    body.extend_from_slice(text);
    if !phone.send(
        &pinnacle_ui::phone::message(pinnacle_ui::phone::SEND_TEXT, &body),
        Vec::new(),
    ) {
        return;
    }
    node.withdraw(contact, |p| p.first() == Some(&protocol::TEXT) && &p[1..] == text);
    mark_texted(contact, text);
    println!("p2p: {name} not reachable online; texting {number}");
}

/// [`protocol::FORGET`]: the conversation with `contact` gone from this
/// device, or one message of it (whether it was sent, and its time).
fn forget(contact: &Key, message: Option<(bool, u64)>) {
    let path = alloc::format!("{}/{}", own("messages"), hex(contact));
    match message {
        None => {
            fs::remove(&path);
        }
        Some((outgoing, at)) => {
            let log = fs::read(&path).unwrap_or_default();
            if let Some(rest) = protocol::without_record(&log, outgoing, at) {
                fs::write(&path, &rest);
            }
        }
    }
}

/// The address book (`pinnacle_contacts::Book`), held whole: every entry
/// in one file, `book.vcf`, read once at start and written whole at each
/// change (one file rather than one each: a folder lists only its first
/// 16 KiB of names, some 490 of them). A contact's card is kept in
/// `contacts/` alone, and joined to its entry when the book is asked for.
struct Book(contacts::Book);

fn random(bytes: &mut [u8]) {
    pinnacle_rt::random(bytes);
}

impl Book {
    /// The book on disk, with an entry for every contact `node` has but
    /// the person's own devices, which are not people to write to.
    fn load(node: &Node) -> Book {
        let text = fs::read_string(&own("book.vcf")).unwrap_or_default();
        let mut book = Book(contacts::Book::from_kept(&text, &mut random));
        let own = protocol::own_devices();
        let cards: Vec<Card> = node
            .contacts()
            .filter(|c| !own.contains(&c.key))
            .copied()
            .collect();
        for card in cards {
            book.add_card(&card);
        }
        book
    }

    /// An entry for a contact whose card came, if it has none yet.
    fn add_card(&mut self, card: &Card) {
        if self.0.add_card(card.key, card.name(), &mut random) {
            self.save();
        }
    }

    /// Writes the book whole: the journal makes it all or nothing.
    fn save(&self) -> bool {
        fs::write(&own("book.vcf"), self.0.to_kept().as_bytes())
    }

    fn name_of(&self, key: &Key) -> Option<&str> {
        self.0.name_of(key)
    }

    /// [`protocol::PUT_ENTRY`]: keeps `entry` (`contacts::Book::put`), and
    /// a card in it that holds as a contact. On disk once [`Book::save`]
    /// runs, once for a whole request.
    fn put(&mut self, node: &mut Node, id: &str, mut entry: Entry) -> Option<String> {
        let card = entry.card.take().and_then(|c| Card::from_bytes(&c));
        let id = self.0.put(id, entry, &mut random)?;
        let key = self.0.entries.iter().find(|e| e.id == id).and_then(|e| e.key);
        if let Some(card) = card
            && Some(card.key) == key
            && !node.contacts().any(|c| c.key == card.key)
        {
            fs::create_dir(&own("contacts"));
            fs::write(
                &alloc::format!("{}/{}", own("contacts"), hex(&card.key)),
                &card.to_bytes(),
            );
            node.add_contact(card);
        }
        Some(id)
    }

    /// [`protocol::REMOVE_ENTRY`]: the entry goes, and the contact's card
    /// with it. The conversation stays on disk, as a message is never
    /// thrown away unasked.
    fn remove(&mut self, node: &mut Node, id: &str) {
        let Some(entry) = self.0.remove(id) else {
            return;
        };
        self.save();
        if let Some(key) = entry.key {
            fs::remove(&alloc::format!("{}/{}", own("contacts"), hex(&key)));
            node.remove_contact(&key);
        }
    }

    /// [`protocol::BOOK`]'s answer from entry `from`: each entry's vCard
    /// with its contact's card.
    fn page(&self, node: &Node, from: usize) -> Vec<u8> {
        let all: Vec<(String, String)> = self
            .0
            .entries
            .iter()
            .map(|e| {
                let card = e
                    .key
                    .and_then(|k| node.contacts().find(|c| c.key == k))
                    .map(|c| c.to_bytes().to_vec());
                (e.id.clone(), Entry { card, ..e.clone() }.to_vcard())
            })
            .collect();
        protocol::book_page(&all, from)
    }
}

/// What the p2p service can be asked by name (`pinnacle_records::verbs`):
/// the terminal's `p2p …` commands and the agent's tools.
fn description() -> verbs::Description {
    use verbs::{Effect, Param, Type, Verb};
    let param = |name: &str, kind, about: &str| Param {
        name: name.into(),
        kind,
        required: true,
        about: about.into(),
    };
    let verb = |name: &str, about: &str, params, effect| Verb {
        name: name.into(),
        about: about.into(),
        params,
        effect,
        inverse: None,
        untrusted: false,
    };
    verbs::Description {
        service: "p2p".into(),
        about: "Your contacts, and the messages with them".into(),
        verbs: alloc::vec![
            verb("contacts", "Your contacts' names", Vec::new(), Effect::Reads),
            verb(
                "history",
                "The newest messages with a contact",
                alloc::vec![param("contact", Type::Contact, "Whose")],
                Effect::Reads,
            ),
            // A message sent cannot be taken back.
            verb(
                "send",
                "Send a contact a text message",
                alloc::vec![
                    param("contact", Type::Contact, "To whom"),
                    param("text", Type::Text, "What it says"),
                ],
                Effect::Out,
            ),
        ],
    }
}

/// Runs a described verb, its arguments already checked.
fn run_verb(node: &mut Node, book: &Book, verb: &str, args: &pinnacle_json::Value) -> verbs::Result {
    use pinnacle_json::Value;
    let shown = |c: &Card| String::from(book.name_of(&c.key).unwrap_or(c.name()));
    let contact = || {
        let name = args.get("contact").as_str().unwrap_or("");
        node.contacts()
            .find(|c| shown(c).eq_ignore_ascii_case(name) || c.name().eq_ignore_ascii_case(name))
            .map(|c| (c.key, shown(c)))
    };
    match verb {
        "contacts" => verbs::Result::ok(Value::Array(
            node.contacts().map(|c| Value::from(shown(c))).collect(),
        )),
        "history" => {
            let Some((key, name)) = contact() else {
                return verbs::Result::error("no such contact");
            };
            let log = newest(&key);
            let mut lines = Vec::new();
            let mut at = 0;
            while at + 11 <= log.len() {
                let len = usize::from(u16::from_le_bytes([log[at + 9], log[at + 10]]));
                let text = String::from_utf8_lossy(log.get(at + 11..at + 11 + len).unwrap_or(&[]));
                let who = if log[at] == 1 { "You" } else { name.as_str() };
                lines.push(Value::from(alloc::format!("{who}: {text}")));
                at += 11 + len;
            }
            verbs::Result::ok(Value::Array(lines))
        }
        "send" => {
            let Some((key, name)) = contact() else {
                return verbs::Result::error("no such contact");
            };
            let text = args.get("text").as_str().unwrap_or("");
            keep(&key, true, text.as_bytes());
            let mut payload = alloc::vec![protocol::TEXT];
            payload.extend_from_slice(text.as_bytes());
            node.send(&key, payload, pinnacle_rt::time());
            verbs::Result::ok(alloc::format!("Sent to {name}").into())
        }
        _ => verbs::Result::error("no such verb"),
    }
}

/// A channel carried over a stream to a contact, a message a frame: this
/// device using a service on the contact's (`protocol::REMOTE`), or the
/// contact using one here, which its person offered it (`protocol::OFFERED`).
struct Bridge {
    contact: Key,
    stream: u32,
    channel: Channel,
    frames: Frames,
}

/// A frame on a bridge's stream: one message, no handles.
const MESSAGE: u8 = 0x20;
/// The most bridges at once, both ways.
const MAX_BRIDGES: usize = 32;

#[derive(Default)]
struct Bridges {
    all: Vec<Bridge>,
}

impl Bridges {
    /// `protocol::REMOTE`: the contact's key and the service's name, and
    /// the caller's channel.
    fn open(&mut self, node: &mut Node, request: &[u8], handles: Vec<pinnacle_rt::Handle>, now: u64) {
        if request.len() <= 32 {
            return;
        }
        let contact: Key = request[..32].try_into().unwrap();
        let name = String::from_utf8_lossy(&request[32..]).into_owned();
        if self.bridge(node, contact, &protocol::verbs_tag(&name), handles, now) {
            println!("p2p: using {name} on {}", &hex(&contact)[..16]);
        }
    }

    /// `protocol::SYNC`: an own device's key, and the sync service's
    /// channel. Only to a device that is the person's own.
    fn open_sync(&mut self, node: &mut Node, request: &[u8], handles: Vec<pinnacle_rt::Handle>, now: u64) {
        let Ok(device) = <Key>::try_from(request) else {
            return;
        };
        if protocol::own_devices().contains(&device) {
            self.bridge(node, device, protocol::SYNC_TAG, handles, now);
        }
    }

    /// A stream tagged `tag` to `contact`, carrying the channel in `handles`.
    fn bridge(
        &mut self,
        node: &mut Node,
        contact: Key,
        tag: &str,
        mut handles: Vec<pinnacle_rt::Handle>,
        now: u64,
    ) -> bool {
        if handles.len() != 1 || self.all.len() >= MAX_BRIDGES {
            return false;
        }
        let Some(stream) = node.open_stream(&contact, tag, now) else {
            return false;
        };
        self.all.push(Bridge {
            contact,
            stream,
            channel: Channel(handles.remove(0)),
            frames: Frames::default(),
        });
        true
    }

    fn find(&self, contact: Key, stream: u32) -> Option<usize> {
        self.all
            .iter()
            .position(|b| b.contact == contact && b.stream == stream)
    }

    /// A stream event: true when it was a bridge's.
    fn event(&mut self, node: &mut Node, event: &Event, now: u64) -> bool {
        match event {
            Event::StreamOpened {
                contact,
                stream,
                service,
            } if service == protocol::SYNC_TAG => {
                // Only between two devices that are both the person's own:
                // each has the other in its list.
                let own = protocol::own_devices().contains(contact);
                let local = (own && self.all.len() < MAX_BRIDGES)
                    .then(|| pinnacle_rt::connect(protocol::SYNC_SERVICE))
                    .flatten();
                match local {
                    Some(channel) => {
                        // The sync service hears first whom it is with.
                        channel.send(&[&[protocol::SYNC_FROM][..], contact].concat(), Vec::new());
                        self.all.push(Bridge {
                            contact: *contact,
                            stream: *stream,
                            channel,
                            frames: Frames::default(),
                        });
                    }
                    None => {
                        println!("p2p: {} may not sync here", &hex(contact)[..16]);
                        node.stream_finish(contact, *stream, now);
                    }
                }
                true
            }
            Event::StreamOpened {
                contact,
                stream,
                service,
            } => {
                let Some(name) = service.strip_prefix("verbs:") else {
                    return false;
                };
                // Only what the person offered this contact, and never a
                // service the kernel keeps from installed apps.
                let offered = protocol::offered().contains(contact);
                let local = (offered && !name.starts_with("system-") && self.all.len() < MAX_BRIDGES)
                    .then(|| pinnacle_rt::connect(name))
                    .flatten();
                match local {
                    Some(channel) => {
                        println!("p2p: {} uses {name} here", &hex(contact)[..16]);
                        self.all.push(Bridge {
                            contact: *contact,
                            stream: *stream,
                            channel,
                            frames: Frames::default(),
                        });
                    }
                    None => {
                        println!("p2p: {} may not use {name} here", &hex(contact)[..16]);
                        node.stream_finish(contact, *stream, now);
                    }
                }
                true
            }
            Event::StreamData {
                contact,
                stream,
                data,
            } => {
                let Some(i) = self.find(*contact, *stream) else {
                    return false;
                };
                let b = &mut self.all[i];
                b.frames.push(data);
                while let Some((kind, body)) = b.frames.take() {
                    if kind == MESSAGE && body.len() <= pinnacle_rt::abi::MAX_MESSAGE {
                        b.channel.send(&body, Vec::new());
                    }
                }
                if b.frames.broken {
                    let b = self.all.remove(i);
                    node.stream_finish(&b.contact, b.stream, now);
                }
                true
            }
            Event::StreamFinished { contact, stream } | Event::StreamReset { contact, stream } => {
                let Some(i) = self.find(*contact, *stream) else {
                    return false;
                };
                // Its channel closes with it: the program sees the far end go.
                let b = self.all.remove(i);
                if matches!(event, Event::StreamFinished { .. }) {
                    node.stream_finish(&b.contact, b.stream, now);
                }
                true
            }
            _ => false,
        }
    }

    /// A message on bridge `i`'s channel, for the far end.
    fn message(&mut self, node: &mut Node, i: usize, bytes: &[u8], now: u64) {
        let b = &self.all[i];
        node.stream_write(&b.contact, b.stream, &remote::frame(MESSAGE, bytes), now);
    }

    /// Bridge `i`'s program let go of it: the stream ends.
    fn closed(&mut self, node: &mut Node, i: usize, now: u64) {
        let b = self.all.remove(i);
        node.stream_finish(&b.contact, b.stream, now);
    }
}

/// How long a link code holds, and how often its records are stored again
/// and looked for.
const LINK_MS: u64 = 600_000;
const LINK_STORE_MS: u64 = 30_000;
const LINK_LOOK_MS: u64 = 3000;
/// How long a typed code is looked for.
const LINK_ENTER_MS: u64 = 60_000;

/// Linking one of the person's devices (`pinnacle_p2p::link`): this one
/// showing a code, or given one. The person's app (Settings) holds the
/// other end of `channel`.
struct Linking {
    code: link::Code,
    showing: bool,
    channel: Channel,
    until: u64,
    stored: Option<u64>,
    looked: Option<u64>,
}

impl Linking {
    /// `protocol::LINK_SHOW`: a new code, its card stored at the offer.
    fn show(node: &mut Node, channel: Channel, now: u64) -> Linking {
        let mut random = [0u8; 8];
        pinnacle_rt::random(&mut random);
        let code = link::Code::new(random);
        channel.send(
            &[&[protocol::LINK_CODE][..], code.text().as_bytes()].concat(),
            Vec::new(),
        );
        println!("p2p: showing a link code");
        let mut l = Linking {
            code,
            showing: true,
            channel,
            until: now + LINK_MS,
            stored: None,
            looked: None,
        };
        l.tick(node, now);
        l
    }

    /// `protocol::LINK_ENTER`: the code as typed; None when it is not one.
    fn enter(node: &mut Node, typed: &[u8], channel: Channel, now: u64) -> Option<Linking> {
        let Some(code) = link::Code::parse(&String::from_utf8_lossy(typed)) else {
            channel.send(&[protocol::LINK_FAILED], Vec::new());
            return None;
        };
        println!("p2p: looking for the device showing the code");
        let mut l = Linking {
            code,
            showing: false,
            channel,
            until: now + LINK_ENTER_MS,
            stored: None,
            looked: None,
        };
        l.tick(node, now);
        Some(l)
    }

    /// Stores this device's record again and looks for the other's, when
    /// due; false once it is over.
    fn tick(&mut self, node: &mut Node, now: u64) -> bool {
        if now >= self.until {
            if !self.showing {
                self.channel.send(&[protocol::LINK_FAILED], Vec::new());
            }
            println!("p2p: the link code ran out");
            return false;
        }
        if self.showing && self.stored.is_none_or(|t| now - t >= LINK_STORE_MS) {
            self.stored = Some(now);
            let mut nonce = [0u8; 12];
            pinnacle_rt::random(&mut nonce);
            let offer = self.code.offer();
            let record = self.code.seal(&offer, node.card(), nonce);
            node.put_link(offer, record, now);
        }
        if self.looked.is_none_or(|t| now - t >= LINK_LOOK_MS) {
            self.looked = Some(now);
            let place = if self.showing {
                self.code.answer()
            } else {
                self.code.offer()
            };
            node.find_link(place, now);
        }
        true
    }

    /// A link record found: the other device's card, if it is the one
    /// this linking looks for. The one given the code answers with its own.
    fn found(&mut self, node: &mut Node, place: &[u8; 32], record: &[u8], now: u64) -> Option<Card> {
        let wanted = if self.showing {
            self.code.answer()
        } else {
            self.code.offer()
        };
        if *place != wanted {
            return None;
        }
        let card = self.code.open(place, record)?;
        if card.key == node.card().key {
            return None;
        }
        if !self.showing {
            let mut nonce = [0u8; 12];
            pinnacle_rt::random(&mut nonce);
            let answer = self.code.answer();
            let record = self.code.seal(&answer, node.card(), nonce);
            node.put_link(answer, record, now);
        }
        self.channel
            .send(&[&[protocol::LINKED][..], &card.to_bytes()].concat(), Vec::new());
        Some(card)
    }
}

/// Adds `card` as a contact, on disk, and in the book unless it is one of
/// the person's own devices.
fn add_card(node: &mut Node, book: &mut Book, card: Card) {
    fs::create_dir(&own("contacts"));
    fs::write(
        &alloc::format!("{}/{}", own("contacts"), hex(&card.key)),
        &card.to_bytes(),
    );
    node.add_contact(card);
    if !protocol::own_devices().contains(&card.key) {
        book.add_card(&card);
    }
}

/// `protocol::RELOAD`: the contacts and the book as the disk has them
/// now, after the sync service changed them. A card gone from the disk is
/// a contact no more.
fn reload(node: &mut Node) -> Book {
    let mut on_disk = Vec::new();
    for entry in fs::list(&own("contacts")).unwrap_or_default() {
        if let Some(card) =
            fs::read(&alloc::format!("{}/{entry}", own("contacts"))).and_then(|b| Card::from_bytes(&b))
        {
            on_disk.push(card.key);
            node.add_contact(card);
        }
    }
    let gone: Vec<Key> = node
        .contacts()
        .map(|c| c.key)
        .filter(|k| !on_disk.contains(k))
        .collect();
    for key in gone {
        node.remove_contact(&key);
    }
    println!(
        "p2p: read the contacts again, {} of them",
        node.contacts().count()
    );
    Book::load(node)
}

/// How long a command for a contact's device may wait for that device to
/// take it, before the terminal is told it could not be reached.
const REACH_MS: u64 = 30_000;
/// A command run here for a contact is not read further while this much
/// of its output waits to be acknowledged: it waits for the network.
const BACKLOG: usize = 1 << 20;
/// The most commands contacts run here at once.
const MAX_INCOMING: usize = 8;

/// A command this device asked a contact's to run: the terminal's
/// channels, and the stream it goes over.
struct Outgoing {
    contact: Key,
    name: String,
    stream: u32,
    frames: Frames,
    input: Option<Channel>,
    out: Channel,
    err: Channel,
    watch: Channel,
    control: Channel,
    started: u64,
    reached: bool,
    exited: bool,
}

impl Outgoing {
    /// Ends it in the terminal with `why`, when no exit code came.
    fn fail(&mut self, why: &str) {
        if !self.exited {
            self.err.send(alloc::format!("{why}\n").as_bytes(), Vec::new());
            self.watch.send(&1u64.to_le_bytes(), Vec::new());
            self.exited = true;
        }
    }
}

/// A command a contact runs on this device.
struct Incoming {
    contact: Key,
    stream: u32,
    frames: Frames,
    run: Option<command::Run>,
}

/// Which channel of the remote commands a message came on.
#[derive(Clone, Copy)]
enum Slot {
    /// Outgoing `i`'s stdin (from the terminal), or its control channel.
    Input(usize),
    Control(usize),
    /// Incoming `i`'s stdout, stderr or exit code.
    Output(usize, usize),
}

/// Commands run on contacts' devices, and contacts' commands run here
/// (`pinnacle_ui::remote`).
#[derive(Default)]
struct Remote {
    outgoing: Vec<Outgoing>,
    incoming: Vec<Incoming>,
}

impl Remote {
    /// The terminal's [`protocol::EXEC`]: `request` after its first byte,
    /// and the five channels.
    fn exec(&mut self, node: &mut Node, request: &[u8], handles: Vec<pinnacle_rt::Handle>, now: u64) {
        if request.len() < 32 || handles.len() != 5 {
            return;
        }
        let contact: Key = request[..32].try_into().unwrap();
        let line = String::from_utf8_lossy(&request[32..]).into_owned();
        let mut channels = handles.into_iter().map(Channel);
        let (input, out, err, watch, control) = (
            channels.next().unwrap(),
            channels.next().unwrap(),
            channels.next().unwrap(),
            channels.next().unwrap(),
            channels.next().unwrap(),
        );
        let name = node
            .contacts()
            .find(|c| c.key == contact)
            .map(|c| String::from(c.name()));
        let (Some(name), Some(stream)) = (name, node.open_stream(&contact, remote::SERVICE, now)) else {
            err.send(b"Not a contact\n", Vec::new());
            watch.send(&1u64.to_le_bytes(), Vec::new());
            return;
        };
        println!("p2p: running {line} on {name}");
        node.stream_write(
            &contact,
            stream,
            &remote::frame(remote::RUN, line.as_bytes()),
            now,
        );
        self.outgoing.push(Outgoing {
            contact,
            name,
            stream,
            frames: Frames::default(),
            input: Some(input),
            out,
            err,
            watch,
            control,
            started: now,
            reached: false,
            exited: false,
        });
    }

    /// The channels to listen on, and whose each is.
    fn channels<'a>(&'a self, node: &mut Node) -> Vec<(&'a Channel, Slot)> {
        let mut out = Vec::new();
        for (i, o) in self.outgoing.iter().enumerate() {
            if let Some(input) = &o.input {
                out.push((input, Slot::Input(i)));
            }
            out.push((&o.control, Slot::Control(i)));
        }
        for (i, inc) in self.incoming.iter().enumerate() {
            let Some(run) = &inc.run else { continue };
            // Output waits while the network is behind.
            let behind = node.stream_backlog(&inc.contact, inc.stream) > BACKLOG;
            for (s, channel) in run.streams.iter().enumerate() {
                if let Some(c) = channel
                    && !(behind && s < 2)
                {
                    out.push((c, Slot::Output(i, s)));
                }
            }
        }
        out
    }

    fn message(
        &mut self,
        node: &mut Node,
        slot: Slot,
        bytes: &[u8],
        mut handles: Vec<pinnacle_rt::Handle>,
        now: u64,
    ) {
        match slot {
            Slot::Input(i) => {
                let o = &self.outgoing[i];
                node.stream_write(&o.contact, o.stream, &remote::frame(remote::STDIN, bytes), now);
            }
            Slot::Control(i) => {
                let o = &self.outgoing[i];
                node.stream_write(&o.contact, o.stream, &remote::frame(remote::STOP, &[]), now);
            }
            Slot::Output(i, s) => {
                let inc = &self.incoming[i];
                let frame = match (s, Output::of(bytes)) {
                    (2, _) => remote::frame(remote::EXIT, bytes.get(..8).unwrap_or(&[0; 8])),
                    (0, Output::Record(Record::Image { width, height })) => {
                        let size = width as usize * height as usize * 4;
                        let memory = (!handles.is_empty() && size + 8 <= remote::MAX_FRAME)
                            .then(|| Memory::map(handles.remove(0)))
                            .flatten()
                            .filter(|m| m.size >= size);
                        match memory {
                            Some(mut memory) => {
                                let mut body = width.to_le_bytes().to_vec();
                                body.extend_from_slice(&height.to_le_bytes());
                                body.extend_from_slice(&memory.bytes()[..size]);
                                memory.unmap();
                                remote::frame(remote::IMAGE, &body)
                            }
                            None => remote::frame(remote::OUT, b"(an image too large to send)\n"),
                        }
                    }
                    (0, _) => remote::frame(remote::OUT, bytes),
                    _ => remote::frame(remote::ERR, bytes),
                };
                node.stream_write(&inc.contact, inc.stream, &frame, now);
            }
        }
    }

    fn closed(&mut self, node: &mut Node, slot: Slot, now: u64) {
        match slot {
            Slot::Input(i) => self.outgoing[i].input = None,
            // The terminal stopped it, or closed: the stream goes.
            Slot::Control(i) => {
                let o = self.outgoing.remove(i);
                node.stream_reset(&o.contact, o.stream, now);
            }
            Slot::Output(i, s) => {
                let inc = &mut self.incoming[i];
                let run = inc.run.as_mut().unwrap();
                run.streams[s] = None;
                if run.streams.iter().all(Option::is_none) {
                    node.stream_finish(&inc.contact, inc.stream, now);
                    self.incoming.remove(i);
                }
            }
        }
    }

    /// A stream event: true when it was one of these commands'.
    fn event(
        &mut self,
        node: &mut Node,
        event: &Event,
        me: &str,
        display: &mut Option<Channel>,
        now: u64,
    ) -> bool {
        match *event {
            Event::StreamOpened {
                contact,
                stream,
                ref service,
            } => {
                let allowed = pinnacle_ui::p2p::allowed().contains(&contact);
                let why = if service != remote::SERVICE {
                    Some(alloc::format!("{me} offers no “{service}” to others"))
                } else if !allowed {
                    Some(alloc::format!(
                        "{me} does not let you run commands on it: its person can allow you in Settings, Remote access"
                    ))
                } else if self.incoming.len() >= MAX_INCOMING {
                    Some(alloc::format!(
                        "{me} runs as many commands for others as it takes"
                    ))
                } else {
                    None
                };
                match why {
                    Some(why) => {
                        println!("p2p: {} may not run commands here", &hex(&contact)[..16]);
                        node.stream_write(
                            &contact,
                            stream,
                            &remote::frame(remote::REFUSED, why.as_bytes()),
                            now,
                        );
                        node.stream_finish(&contact, stream, now);
                    }
                    None => self.incoming.push(Incoming {
                        contact,
                        stream,
                        frames: Frames::default(),
                        run: None,
                    }),
                }
                true
            }
            Event::StreamData {
                contact,
                stream,
                ref data,
            } => {
                if let Some(i) = self
                    .outgoing
                    .iter()
                    .position(|o| o.contact == contact && o.stream == stream)
                {
                    self.outgoing[i].frames.push(data);
                    self.answers(i);
                } else if let Some(i) = self
                    .incoming
                    .iter()
                    .position(|o| o.contact == contact && o.stream == stream)
                {
                    self.incoming[i].frames.push(data);
                    self.requests(node, i, display, now);
                }
                true
            }
            Event::StreamFinished { contact, stream } | Event::StreamReset { contact, stream } => {
                let reset = matches!(event, Event::StreamReset { .. });
                if let Some(i) = self
                    .outgoing
                    .iter()
                    .position(|o| o.contact == contact && o.stream == stream)
                {
                    let mut o = self.outgoing.remove(i);
                    let why = alloc::format!("The connection to {} ended", o.name);
                    o.fail(&why);
                    if !reset {
                        node.stream_finish(&contact, stream, now);
                    }
                } else if let Some(i) = self
                    .incoming
                    .iter()
                    .position(|o| o.contact == contact && o.stream == stream)
                    && reset
                {
                    // The other side went: what it ran here ends.
                    if let Some(run) = &self.incoming[i].run {
                        run.kill();
                    }
                    self.incoming.remove(i);
                }
                true
            }
            _ => false,
        }
    }

    /// What came back for outgoing `i`, to its terminal.
    fn answers(&mut self, i: usize) {
        let o = &mut self.outgoing[i];
        o.reached = true;
        while let Some((kind, body)) = o.frames.take() {
            match kind {
                remote::OUT => {
                    o.out.send(&body, Vec::new());
                }
                remote::ERR => {
                    o.err.send(&body, Vec::new());
                }
                remote::IMAGE if body.len() >= 8 => {
                    let width = u32::from_le_bytes(body[..4].try_into().unwrap());
                    let height = u32::from_le_bytes(body[4..8].try_into().unwrap());
                    let pixels = &body[8..];
                    let record = Record::Image { width, height }.encode();
                    match (Memory::new(pixels.len()), record) {
                        (Some(mut memory), Some(record))
                            if pixels.len() == width as usize * height as usize * 4 =>
                        {
                            memory.bytes()[..pixels.len()].copy_from_slice(pixels);
                            let Memory { handle, address, .. } = memory;
                            o.out.send(&record, alloc::vec![handle]);
                            pinnacle_rt::unmap(address);
                        }
                        _ => {
                            o.err.send(b"(an image that did not come)\n", Vec::new());
                        }
                    }
                }
                remote::EXIT if body.len() == 8 => {
                    o.watch.send(&body, Vec::new());
                    o.exited = true;
                }
                remote::REFUSED => {
                    let why = String::from_utf8_lossy(&body).into_owned();
                    o.fail(&why);
                }
                _ => {}
            }
        }
    }

    /// What the contact asked of incoming `i`.
    fn requests(&mut self, node: &mut Node, i: usize, display: &mut Option<Channel>, now: u64) {
        let inc = &mut self.incoming[i];
        while let Some((kind, body)) = inc.frames.take() {
            match kind {
                remote::RUN if inc.run.is_none() => {
                    let line = String::from_utf8_lossy(&body).into_owned();
                    let who = node
                        .contacts()
                        .find(|c| c.key == inc.contact)
                        .map_or_else(|| String::from("A contact"), |c| String::from(c.name()));
                    println!("p2p: {who} runs {line} here");
                    match command::start(&line) {
                        Ok(run) => {
                            inc.run = Some(run);
                            // The person sees what others run on their device.
                            if display.is_none() {
                                *display = pinnacle_rt::connect("display");
                            }
                            if let Some(display) = display {
                                let text = alloc::format!("runs “{line}” on this device");
                                pinnacle_ui::notify(display, "settings", &who, &text);
                            }
                        }
                        Err(why) => {
                            let (contact, stream) = (inc.contact, inc.stream);
                            node.stream_write(
                                &contact,
                                stream,
                                &remote::frame(remote::ERR, why.as_bytes()),
                                now,
                            );
                            node.stream_write(
                                &contact,
                                stream,
                                &remote::frame(remote::EXIT, &1u64.to_le_bytes()),
                                now,
                            );
                            node.stream_finish(&contact, stream, now);
                            self.incoming.remove(i);
                            return;
                        }
                    }
                }
                remote::STDIN => {
                    if let Some(run) = &inc.run {
                        run.input.send(&body, Vec::new());
                    }
                }
                remote::STOP => {
                    if let Some(run) = &inc.run {
                        run.kill();
                    }
                }
                _ => {}
            }
        }
    }

    /// Commands for devices that were not reached in time end.
    fn tick(&mut self, node: &mut Node, now: u64) {
        let mut i = 0;
        while i < self.outgoing.len() {
            let o = &mut self.outgoing[i];
            if !o.reached && node.stream_backlog(&o.contact, o.stream) == 0 {
                // The command line was acknowledged: the device has it.
                o.reached = true;
            }
            if !o.reached && now - o.started > REACH_MS {
                let why = alloc::format!("{} could not be reached", o.name);
                o.fail(&why);
                node.stream_reset(&o.contact, o.stream, now);
                self.outgoing.remove(i);
            } else {
                i += 1;
            }
        }
    }
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let name = fs::read_string("system:/settings/name").unwrap_or_else(|| "Pinnacle".into());
    let mut seed = [0u8; 32];
    pinnacle_rt::random(&mut seed);
    let mut node = Node::new(identity(), name.trim(), seed);
    node.set_epoch(epoch());
    for entry in fs::list(&own("contacts")).unwrap_or_default() {
        if let Some(card) =
            fs::read(&alloc::format!("{}/{entry}", own("contacts"))).and_then(|b| Card::from_bytes(&b))
        {
            node.add_contact(card);
        }
    }
    let mut book = Book::load(&node);
    if let Some(addr) = fs::read_string("system:/settings/public-address")
        .as_deref()
        .and_then(parse_addr)
    {
        node.set_public_address(addr);
    }
    let service = pinnacle_rt::register("p2p").expect("could not register p2p");
    // Commands on contacts' devices: a service apps cannot reach.
    let exec = pinnacle_rt::register(protocol::EXEC_SERVICE).expect("could not register system-p2p");
    let Some(mut address) = net::wait_configured(10_000) else {
        println!("p2p: no network");
        return 1;
    };
    let (socket, port) = net::udp_bind(PORT).expect("could not bind the p2p port");
    // Where a contact behind the same NAT reaches this device.
    node.set_local_address(Addr { ip: address, port });
    for peer in fs::read_string("system:/settings/peers")
        .unwrap_or_default()
        .lines()
        .filter_map(parse_addr)
    {
        node.bootstrap(peer, pinnacle_rt::time());
    }
    println!(
        "p2p: {} on port {port}, {} contacts, key {}",
        name.trim(),
        node.contacts().count(),
        core::str::from_utf8(&pinnacle_p2p::identity::fingerprint(&node.card().key)).unwrap_or("")
    );

    // Each app connected, whether it is the Calls app, and a verb call it
    // has sent part of.
    let mut clients: Vec<(Channel, bool, verbs::Pieces)> = Vec::new();
    // A ring that came while no Calls app was there to take it, and its
    // payload (a voice call's says so).
    let mut waiting_ring: Option<(Key, Vec<u8>)> = None;
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    let mut next_poll = pinnacle_rt::time();
    let mut announced = 0;
    // The display server, for notifications: reached when the first is due.
    let mut display: Option<Channel> = None;
    // Connections to `system-p2p`, until their request comes.
    let mut askers: Vec<Channel> = Vec::new();
    let mut remote = Remote::default();
    let mut bridges = Bridges::default();
    let mut linking: Option<Linking> = None;
    // Texts sent that the contact's device has not said arrived.
    let mut delivery = Delivery::default();
    loop {
        let now = pinnacle_rt::time();
        if now >= next_poll {
            // A new address (another network, a new lease): contacts hear
            // from it at once, and the DHT is told where this device went.
            if let Some((ip, ..)) = net::info()
                && ip != address
            {
                address = ip;
                println!("p2p: the network changed");
                node.set_local_address(Addr { ip, port });
                node.network_changed(now);
            }
            node.poll(now);
            remote.tick(&mut node, now);
            if linking.as_mut().is_some_and(|l| !l.tick(&mut node, now)) {
                linking = None;
            }
            for (contact, text) in delivery.due(now) {
                text_instead(&mut node, &book, &contact, &text);
            }
            next_poll = now + POLL_MS;
        }
        while let Some((to, data)) = node.transmit() {
            net::send_to(&socket, to.ip, to.port, &data);
        }
        while let Some(event) = node.event() {
            match event {
                Event::Received { from, payload } => {
                    if payload.first() == Some(&protocol::DELIVERED) {
                        delivery.arrived(&from);
                        continue;
                    }
                    if payload.first() == Some(&protocol::TEXT) {
                        // The sender hears at once that it arrived: without
                        // this it texts the number instead.
                        node.send(&from, alloc::vec![protocol::DELIVERED], now);
                        keep(&from, false, &payload[1..]);
                        // Messages shows it itself when it is in front; the
                        // display server leaves the banner out then.
                        let name = node.contacts().find(|c| c.key == from).map_or_else(
                            || String::from("Someone"),
                            |c| String::from(book.name_of(&c.key).unwrap_or(c.name())),
                        );
                        let text = String::from_utf8_lossy(&payload[1..]);
                        if display.is_none() {
                            display = pinnacle_rt::connect("display");
                        }
                        if let Some(display) = &display {
                            pinnacle_ui::notify(display, "messages", &name, &text);
                        }
                    }
                    let message = protocol::received(&from, &payload);
                    let ring = payload.get(..2) == Some(&[protocol::CALL, protocol::call::RING]);
                    if ring {
                        // The caller hears at once that the ring arrived:
                        // without this it calls the number instead.
                        node.send(&from, alloc::vec![protocol::CALL, protocol::call::RINGING], now);
                    }
                    // A ring taken back before Calls came is not shown.
                    if payload.get(..2) == Some(&[protocol::CALL, protocol::call::HANG_UP])
                        && waiting_ring.as_ref().is_some_and(|(k, _)| *k == from)
                    {
                        waiting_ring = None;
                    }
                    if ring && !clients.iter().any(|(_, calls, _)| *calls) {
                        waiting_ring = Some((from, payload.clone()));
                        pinnacle_rt::spawn("calls", 1, Vec::new());
                    }
                    clients.retain(|(c, _, _)| c.send(&message, Vec::new()));
                }
                Event::Connected { contact } => println!("p2p: connected to {}", &hex(&contact)[..16]),
                Event::LinkFound { place, record } => {
                    let card = linking
                        .as_mut()
                        .and_then(|l| l.found(&mut node, &place, &record, now));
                    if let Some(card) = card {
                        // Own first: the book leaves it out.
                        protocol::set_own(&card.key, true);
                        add_card(&mut node, &mut book, card);
                        println!("p2p: linked with {}", card.name());
                        linking = None;
                    }
                }
                Event::Unreachable { contact } => {
                    println!("p2p: {} not found", &hex(&contact)[..16]);
                    // Texts waiting for it go to its number now.
                    delivery.unreachable(&contact);
                    // Calls then calls the contact's number.
                    let mut m = alloc::vec![protocol::UNREACHABLE];
                    m.extend_from_slice(&contact);
                    for (c, calls, _) in &clients {
                        if *calls {
                            c.send(&m, Vec::new());
                        }
                    }
                }
                event => {
                    if !bridges.event(&mut node, &event, now) {
                        remote.event(&mut node, &event, name.trim(), &mut display, now);
                    }
                }
            }
        }
        if node.known_nodes() != announced {
            announced = node.known_nodes();
            println!("p2p: {announced} nodes known");
        }

        // The socket, the two services, the apps, the requests waiting, the
        // remote commands' channels, then the bridges'.
        let mut channels: Vec<&Channel> = alloc::vec![&socket, &service, &exec];
        channels.extend(clients.iter().map(|(c, _, _)| c));
        channels.extend(askers.iter());
        let slots = remote.channels(&mut node);
        let first_slot = channels.len();
        channels.extend(slots.iter().map(|(c, _)| *c));
        let slots: Vec<Slot> = slots.into_iter().map(|(_, s)| s).collect();
        let first_bridge = channels.len();
        channels.extend(bridges.all.iter().map(|b| &b.channel));
        let first_asker = 3 + clients.len();
        let got = pinnacle_rt::receive(&channels, &mut buffer, Some(next_poll));
        drop(channels);
        let now = pinnacle_rt::time();
        match got {
            Received::Message { index, len, .. } if index >= first_bridge => {
                bridges.message(&mut node, index - first_bridge, &buffer[..len], now);
            }
            Received::Closed { index } if index >= first_bridge => {
                bridges.closed(&mut node, index - first_bridge, now);
            }
            Received::Message { index, len, handles } if index >= first_slot => {
                let bytes = buffer[..len].to_vec();
                remote.message(&mut node, slots[index - first_slot], &bytes, handles, now);
            }
            Received::Closed { index } if index >= first_slot => {
                remote.closed(&mut node, slots[index - first_slot], now);
            }
            Received::Message {
                index, len, handles, ..
            } if index >= first_asker => {
                let asker = askers.remove(index - first_asker);
                match buffer.first() {
                    Some(&protocol::EXEC) => remote.exec(&mut node, &buffer[1..len], handles, now),
                    Some(&protocol::REMOTE) => bridges.open(&mut node, &buffer[1..len], handles, now),
                    Some(&protocol::SYNC) => bridges.open_sync(&mut node, &buffer[1..len], handles, now),
                    Some(&protocol::LINK_SHOW | &protocol::LINK_ENTER)
                        if handles.len() == 1 && fs::disk("data").is_some() =>
                    {
                        let channel = Channel(handles.into_iter().next().unwrap());
                        linking = if buffer[0] == protocol::LINK_SHOW {
                            Some(Linking::show(&mut node, channel, now))
                        } else {
                            Linking::enter(&mut node, &buffer[1..len], channel, now)
                        };
                    }
                    Some(&protocol::RELOAD) => book = reload(&mut node),
                    _ => {}
                }
                drop(asker);
            }
            Received::Closed { index } if index >= first_asker => {
                askers.remove(index - first_asker);
            }
            Received::Message {
                index: 2,
                mut handles,
                ..
            } if !handles.is_empty() => {
                askers.push(Channel(handles.remove(0)));
            }
            Received::Message { index: 0, len, .. } => {
                if let Some((ip, port, data)) = net::datagram(&buffer[..len]) {
                    node.receive(Addr { ip, port }, data, pinnacle_rt::time());
                }
            }
            Received::Message {
                index: 1,
                mut handles,
                ..
            } if !handles.is_empty() => {
                clients.push((Channel(handles.remove(0)), false, verbs::Pieces::default()));
            }
            Received::Message { index, len, .. } if index >= 3 => {
                let request = &buffer[..len];
                let client = &mut clients[index - 3];
                match pinnacle_ui::verbs::Request::read(&mut client.2, request) {
                    Some(pinnacle_ui::verbs::Request::Describe) => {
                        pinnacle_ui::verbs::describe_to(&client.0, &description());
                        continue;
                    }
                    Some(pinnacle_ui::verbs::Request::Call { verb, args }) => {
                        let channel = &clients[index - 3].0;
                        pinnacle_ui::verbs::serve_call(
                            channel,
                            &description(),
                            &verb,
                            &args,
                            |verb, args| run_verb(&mut node, &book, verb, args),
                        );
                        continue;
                    }
                    None if matches!(request.first(), Some(&(verbs::CALL | verbs::DESCRIBE))) => continue,
                    None => {}
                }
                match request.first().copied() {
                    Some(protocol::SEND) if len > 33 => {
                        let to: Key = request[1..33].try_into().unwrap();
                        let payload = request[33..].to_vec();
                        if payload.first() == Some(&protocol::TEXT) {
                            keep(&to, true, &payload[1..]);
                            delivery.sent(to, payload[1..].to_vec(), pinnacle_rt::time());
                        }
                        node.send(&to, payload, pinnacle_rt::time());
                    }
                    Some(protocol::CARD) => {
                        clients[index - 3].0.send(&node.card().to_bytes(), Vec::new());
                    }
                    Some(protocol::CONTACTS) => {
                        let cards: Vec<u8> = node
                            .contacts()
                            .flat_map(|c| {
                                let mut bytes = c.to_bytes();
                                if let Some(name) = book.name_of(&c.key) {
                                    bytes[64..96].copy_from_slice(&protocol::name_slot(name));
                                }
                                bytes
                            })
                            .collect();
                        clients[index - 3].0.send(&cards, Vec::new());
                    }
                    Some(protocol::BOOK) if len == 5 => {
                        let from = u32::from_le_bytes(request[1..5].try_into().unwrap()) as usize;
                        clients[index - 3].0.send(&book.page(&node, from), Vec::new());
                    }
                    Some(protocol::PUT_ENTRY) if len > 1 + protocol::ID_LEN => {
                        let id = core::str::from_utf8(&request[1..1 + protocol::ID_LEN])
                            .ok()
                            .filter(|id| id.bytes().all(|b| b.is_ascii_hexdigit()))
                            .unwrap_or("");
                        let vcards = String::from_utf8_lossy(&request[1 + protocol::ID_LEN..]);
                        let mut entries = contacts::parse(&vcards);
                        if !id.is_empty() {
                            entries.truncate(1);
                        }
                        let mut answer = Vec::new();
                        for entry in entries {
                            let kept = book.put(&mut node, id, entry);
                            answer.extend_from_slice(kept.as_deref().unwrap_or("").as_bytes());
                        }
                        if !answer.is_empty() && !book.save() {
                            answer.clear();
                        }
                        clients[index - 3].0.send(&answer, Vec::new());
                    }
                    Some(protocol::REMOVE_ENTRY) if len == 1 + protocol::ID_LEN => {
                        if let Ok(id) = core::str::from_utf8(&request[1..]) {
                            book.remove(&mut node, id);
                        }
                    }
                    Some(protocol::HISTORY) if len == 33 => {
                        let contact: Key = request[1..33].try_into().unwrap();
                        clients[index - 3].0.send(&newest(&contact), Vec::new());
                    }
                    Some(protocol::FORGET) if len == 33 || len == 42 => {
                        let contact: Key = request[1..33].try_into().unwrap();
                        let at = |b: &[u8]| u64::from_le_bytes(b.try_into().unwrap());
                        let message = (len == 42).then(|| (request[33] == 1, at(&request[34..42])));
                        forget(&contact, message);
                    }
                    Some(protocol::RING_PENDING) => {
                        clients[index - 3].1 = true;
                        if let Some((from, payload)) = waiting_ring.take() {
                            let ring = protocol::received(&from, &payload);
                            clients[index - 3].0.send(&ring, Vec::new());
                        }
                    }
                    Some(protocol::ADD_CONTACT) => {
                        if let Some(card) = Card::from_bytes(&request[1..]) {
                            add_card(&mut node, &mut book, card);
                        }
                    }
                    _ => {}
                }
            }
            Received::Closed { index } if index >= 3 => {
                clients.remove(index - 3);
            }
            _ => {}
        }
    }
}