garage44.eu/jeroen/pinnacle

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

.. /rt/src/lib.rs

raw

//! What every Pinnacle program is built on: the system calls, a heap,
//! channels and shared memory as types, `println!`, and the entry point.
//!
//! A program defines `#[unsafe(no_mangle)] fn main(argument: u64) -> u64`;
//! its return value is the exit code.

#![no_std]

extern crate alloc;

pub mod heap;
pub mod output;
pub mod sys;
pub mod thread;

use alloc::string::String;
use alloc::vec::Vec;
pub use pinnacle_abi as abi;
use pinnacle_abi::{CLOSED, ERROR, MAX_MESSAGE_HANDLES, TIMEOUT, call};
pub use pinnacle_tz as tz;
pub use pinnacle_venus as venus;

unsafe extern "Rust" {
    fn main(argument: u64) -> u64;
}

#[unsafe(no_mangle)]
extern "C" fn _start(argument: u64) -> ! {
    // What the core's own crypto instructions can do, which the kernel
    // reads for programs (EL0 cannot).
    pinnacle_crypto::hw::enable(sys::call_result(call::CPU_FEATURES, [0; 7]).0, false);
    // SAFETY: the program defines `main`.
    let code = unsafe { main(argument) };
    exit(code)
}

#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {
    println!("panic in task {}: {info}", pid());
    exit(101)
}

/// Ends the program, all its threads.
pub fn exit(code: u64) -> ! {
    sys::call1(call::EXIT_PROCESS, code);
    unreachable!("exit returned")
}

pub fn yield_now() {
    sys::call0(call::YIELD);
}

pub fn pid() -> u64 {
    sys::call0(call::PID)
}

/// Milliseconds since boot.
pub fn time() -> u64 {
    sys::call0(call::TIME)
}

pub fn sleep(ms: u64) {
    sys::call1(call::SLEEP_UNTIL, time() + ms);
}

pub fn write(bytes: &[u8]) {
    sys::call2(call::WRITE, bytes.as_ptr() as u64, bytes.len() as u64);
}

/// Formats into a buffer and writes it in one call, so lines from different
/// programs do not interleave.
#[macro_export]
macro_rules! println {
    ($($arg:tt)*) => {{
        let mut line = alloc::string::String::new();
        let _ = core::fmt::Write::write_fmt(&mut line, format_args!($($arg)*));
        line.push('\n');
        $crate::write(line.as_bytes());
    }};
}

/// A handle the program owns: closed when dropped, unless given away.
#[derive(Debug, PartialEq, Eq)]
pub struct Handle(u64);

impl Handle {
    /// # Safety
    /// `raw` is a handle the program owns and nothing else will close.
    pub unsafe fn from_raw(raw: u64) -> Self {
        Self(raw)
    }

    pub fn raw(&self) -> u64 {
        self.0
    }

    /// Gives the handle up without closing it (it is being sent).
    pub fn into_raw(self) -> u64 {
        let raw = self.0;
        core::mem::forget(self);
        raw
    }
}

impl Drop for Handle {
    fn drop(&mut self) {
        sys::call1(call::CLOSE, self.0);
    }
}

/// One end of a channel.
#[derive(Debug)]
pub struct Channel(pub Handle);

/// What [`receive`] found.
#[derive(Debug)]
pub enum Received {
    /// A message of `len` bytes on channel `index`, with these handles.
    Message {
        index: usize,
        len: usize,
        handles: Vec<Handle>,
    },
    /// Channel `index`'s peer is gone.
    Closed {
        index: usize,
    },
    Timeout,
}

impl Channel {
    /// A new channel's two ends.
    pub fn pair() -> (Channel, Channel) {
        let (a, b, _) = sys::call_result(call::CHANNEL, [0; 7]);
        // SAFETY: the kernel just gave us both.
        unsafe { (Channel(Handle::from_raw(a)), Channel(Handle::from_raw(b))) }
    }

    /// Sends `bytes` and `handles`, which leave this program. False when the
    /// peer is gone.
    pub fn send(&self, bytes: &[u8], handles: Vec<Handle>) -> bool {
        let raw: Vec<u64> = handles.into_iter().map(Handle::into_raw).collect();
        let args = [
            self.0.raw(),
            bytes.as_ptr() as u64,
            bytes.len() as u64,
            raw.as_ptr() as u64,
            raw.len() as u64,
            0,
            0,
        ];
        sys::call_result(call::SEND, args).0 != ERROR
    }

    /// Waits for a message on this channel alone.
    pub fn receive(&self, buffer: &mut [u8]) -> Received {
        receive(&[self], buffer, None)
    }
}

/// Waits for a message on any of `channels`, until `deadline` (ms since
/// boot) if one is given.
pub fn receive(channels: &[&Channel], buffer: &mut [u8], deadline: Option<u64>) -> Received {
    let raw: Vec<u64> = channels.iter().map(|c| c.0.raw()).collect();
    let mut handles = [0u64; MAX_MESSAGE_HANDLES];
    let args = [
        raw.as_ptr() as u64,
        raw.len() as u64,
        buffer.as_mut_ptr() as u64,
        buffer.len() as u64,
        handles.as_mut_ptr() as u64,
        handles.len() as u64,
        deadline.unwrap_or(0).max(u64::from(deadline.is_some())),
    ];
    let (index, len, count) = sys::call_result(call::RECEIVE, args);
    match (index, len) {
        (TIMEOUT, _) => Received::Timeout,
        (ERROR, _) => panic!("receive failed: a buffer too small, or not a channel"),
        (index, CLOSED) => Received::Closed {
            index: index as usize,
        },
        (index, len) => Received::Message {
            index: index as usize,
            len: len as usize,
            // SAFETY: the kernel just gave us these.
            handles: handles[..count as usize]
                .iter()
                .map(|&h| unsafe { Handle::from_raw(h) })
                .collect(),
        },
    }
}

/// Shared memory, mapped.
pub struct Memory {
    pub handle: Handle,
    pub address: usize,
    pub size: usize,
}

impl Memory {
    pub fn new(size: usize) -> Option<Memory> {
        let handle = sys::call1(call::MEMORY, size as u64);
        // SAFETY: the kernel just gave it.
        (handle != ERROR).then(|| Memory::map(unsafe { Handle::from_raw(handle) }))?
    }

    /// Unmaps it and closes its handle: its pages go back once no other
    /// program maps it or holds a handle to it. False if it was not mapped.
    pub fn unmap(self) -> bool {
        unmap(self.address)
    }

    /// Maps memory another program sent.
    pub fn map(handle: Handle) -> Option<Memory> {
        let (address, size, _) = sys::call_result(call::MAP, [handle.raw(), 0, 0, 0, 0, 0, 0]);
        (address != ERROR).then_some(Memory {
            handle,
            address: address as usize,
            size: size as usize,
        })
    }

    pub fn bytes(&mut self) -> &mut [u8] {
        // SAFETY: mapped for this program, `size` bytes.
        unsafe { core::slice::from_raw_parts_mut(self.address as *mut u8, self.size) }
    }

    pub fn pixels(&mut self) -> &mut [u32] {
        // SAFETY: as in `bytes`; page aligned, so aligned for u32.
        unsafe { core::slice::from_raw_parts_mut(self.address as *mut u32, self.size / 4) }
    }
}

/// Unmaps the shared memory mapped at `address` (see [`Memory::map`]).
pub fn unmap(address: usize) -> bool {
    sys::call1(call::UNMAP, address as u64) != ERROR
}

/// Offers the service `name`; connections arrive on the returned channel as
/// empty messages carrying each new channel's server end.
pub fn register(name: &str) -> Option<Channel> {
    let (ours, kept) = Channel::pair();
    let args = [name.as_ptr() as u64, name.len() as u64, ours.0.raw(), 0, 0, 0, 0];
    (sys::call_result(call::REGISTER, args).0 != ERROR).then(|| {
        // The peer stays open, unused: were it closed, `ours` would read as
        // closed once its connections are taken.
        core::mem::forget(kept);
        ours
    })
}

/// A channel to the service `name`.
pub fn connect(name: &str) -> Option<Channel> {
    let handle = sys::call2(call::CONNECT, name.as_ptr() as u64, name.len() as u64);
    // SAFETY: the kernel just gave it.
    (handle != ERROR).then(|| Channel(unsafe { Handle::from_raw(handle) }))
}

/// Starts program `name` with `argument` and `handles`. Returns its task id.
pub fn spawn(name: &str, argument: u64, handles: Vec<Handle>) -> Option<u64> {
    spawn_process(name, argument, handles).map(|(id, _)| id)
}

/// As [`spawn`], keeping what can end it.
pub fn spawn_process(name: &str, argument: u64, handles: Vec<Handle>) -> Option<(u64, Process)> {
    let raw: Vec<u64> = handles.into_iter().map(Handle::into_raw).collect();
    let args = [
        name.as_ptr() as u64,
        name.len() as u64,
        argument,
        raw.as_ptr() as u64,
        raw.len() as u64,
        0,
        0,
    ];
    let (id, handle, _) = sys::call_result(call::SPAWN, args);
    // SAFETY: the kernel just gave it (0: the program ended already).
    (id != ERROR).then(|| {
        (
            id,
            Process((handle != 0).then(|| unsafe { Handle::from_raw(handle) })),
        )
    })
}

/// As [`spawn_process`], with a channel its exit code arrives on as it ends
/// (eight bytes), after which the channel closes.
pub fn spawn_watched(name: &str, argument: u64, handles: Vec<Handle>) -> Option<(u64, Process, Channel)> {
    spawn_flagged(name, argument, handles, abi::SPAWN_WATCH)
}

/// As [`spawn_watched`], the program sealed (`abi::SPAWN_SEALED`): it
/// reaches only what `handles` reach.
pub fn spawn_sealed(name: &str, argument: u64, handles: Vec<Handle>) -> Option<(u64, Process, Channel)> {
    spawn_flagged(name, argument, handles, abi::SPAWN_WATCH | abi::SPAWN_SEALED)
}

fn spawn_flagged(
    name: &str,
    argument: u64,
    handles: Vec<Handle>,
    flags: u64,
) -> Option<(u64, Process, Channel)> {
    let raw: Vec<u64> = handles.into_iter().map(Handle::into_raw).collect();
    let args = [
        name.as_ptr() as u64,
        name.len() as u64,
        argument,
        raw.as_ptr() as u64,
        raw.len() as u64,
        flags,
        0,
    ];
    let (id, handle, watch) = sys::call_result(call::SPAWN, args);
    // SAFETY: the kernel just gave them (a process handle of 0: the program
    // ended already, its code waiting on the channel).
    (id != ERROR).then(|| unsafe {
        (
            id,
            Process((handle != 0).then(|| Handle::from_raw(handle))),
            Channel(Handle::from_raw(watch)),
        )
    })
}

/// A program this one started: what can end it.
pub struct Process(Option<Handle>);

impl Process {
    /// Ends it, every thread of it. False when it had ended already.
    pub fn kill(&self) -> bool {
        self.0
            .as_ref()
            .is_some_and(|h| sys::call1(call::KILL, h.raw()) != ERROR)
    }
}

/// The screen (privileged programs only): its pixels, width and height,
/// changed to `size` first when one is given and the screen can have it.
pub fn framebuffer(size: Option<(u32, u32)>) -> Option<(Memory, u32, u32)> {
    let (w, h) = size.unwrap_or((0, 0));
    let (handle, width, height) = sys::call_result(call::FRAMEBUFFER, [w.into(), h.into(), 0, 0, 0, 0, 0]);
    // SAFETY: the kernel just gave it.
    let memory = (handle != ERROR).then(|| Memory::map(unsafe { Handle::from_raw(handle) }))??;
    Some((memory, width as u32, height as u32))
}

/// The input devices' events (privileged programs only).
pub fn input() -> Option<Channel> {
    let handle = sys::call0(call::INPUT);
    // SAFETY: the kernel just gave it.
    (handle != ERROR).then(|| Channel(unsafe { Handle::from_raw(handle) }))
}

/// The time of day, seconds since 1970 (UTC); 0 when the board has no clock
/// and the network has not set it.
pub fn clock() -> u64 {
    sys::call0(call::CLOCK)
}

/// Where the time of day comes from: none, the board's clock, the network.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClockSource {
    None,
    Board,
    Network,
}

/// The time of day in milliseconds since 1970, and where it comes from.
pub fn clock_ms() -> (u64, ClockSource) {
    let (seconds, source, ms) = sys::call_result(call::CLOCK, [0; 7]);
    let source = match source {
        1 => ClockSource::Board,
        2 => ClockSource::Network,
        _ => ClockSource::None,
    };
    (seconds * 1000 + ms, source)
}

/// Sets the time of day, `ms` since 1970, as the network said (the `time`
/// service; not an installed app). Whether it was.
pub fn set_clock(ms: u64) -> bool {
    sys::call2(call::CLOCK, 1, ms) != ERROR
}

/// The names of the programs there are.
/// One device the kernel found.
pub struct Device {
    /// What it is for (`storage`, `network`…), `None` with no driver.
    pub class: Option<alloc::string::String>,
    pub driver: Option<alloc::string::String>,
    /// The device tree node: `virtio_mmio@a003800`.
    pub name: alloc::string::String,
    /// What it is compatible with, most specific first.
    pub compatible: alloc::string::String,
    /// The closed firmware its driver handed it, `Intel, <file>`; `None`
    /// when it runs none (or has no driver).
    pub firmware: Option<alloc::string::String>,
}

/// The hardware the kernel found, and which driver took each.
pub fn devices() -> Vec<Device> {
    let mut buffer = alloc::vec![0u8; 16384];
    let len = sys::call2(call::DEVICES, buffer.as_mut_ptr() as u64, buffer.len() as u64);
    if len == ERROR {
        return Vec::new();
    }
    buffer.truncate(len as usize);
    let some = |s: &str| (s != "-").then(|| alloc::string::String::from(s));
    core::str::from_utf8(&buffer)
        .unwrap_or("")
        .lines()
        .filter_map(|line| {
            let mut parts = line.split('\t');
            Some(Device {
                class: some(parts.next()?),
                driver: some(parts.next()?),
                name: parts.next()?.into(),
                compatible: parts.next()?.into(),
                firmware: parts.next().and_then(some),
            })
        })
        .collect()
}

pub fn programs() -> Vec<alloc::string::String> {
    let mut buffer = alloc::vec![0u8; 4096];
    let len = sys::call2(call::PROGRAMS, buffer.as_mut_ptr() as u64, buffer.len() as u64);
    if len == ERROR {
        return Vec::new();
    }
    buffer.truncate(len as usize);
    core::str::from_utf8(&buffer)
        .unwrap_or("")
        .lines()
        .map(alloc::string::String::from)
        .collect()
}

/// A program that runs, as [`processes`] says it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Running {
    /// Its number, never another program's: what [`kill_id`] takes.
    pub id: u64,
    pub name: String,
    pub threads: u64,
    /// The memory it asked for and the shared memory it maps, in bytes.
    pub memory: u64,
    /// When it started, ms since boot.
    pub started: u64,
    /// `display` (the privileged one), `system`, `app` or `sealed`.
    pub kind: String,
}

/// What `processes(op)` writes, as text; empty when refused.
fn processes_text(op: u64) -> String {
    let mut buffer = alloc::vec![0u8; 64 * 1024];
    let (len, ..) = sys::call_result(
        call::PROCESSES,
        [op, buffer.as_mut_ptr() as u64, buffer.len() as u64, 0, 0, 0, 0],
    );
    if len == ERROR {
        return String::new();
    }
    buffer.truncate(len as usize);
    String::from_utf8_lossy(&buffer).into_owned()
}

/// The programs that run, oldest first; none for a confined or sealed
/// program, which may not ask.
pub fn processes() -> Vec<Running> {
    processes_text(0)
        .lines()
        .filter_map(|line| {
            let mut parts = line.split('|');
            Some(Running {
                id: parts.next()?.parse().ok()?,
                name: parts.next()?.into(),
                threads: parts.next()?.parse().ok()?,
                memory: parts.next()?.parse().ok()?,
                started: parts.next()?.parse().ok()?,
                kind: parts.next()?.into(),
            })
        })
        .collect()
}

/// The names services registered.
pub fn services() -> Vec<String> {
    processes_text(1).lines().map(String::from).collect()
}

/// Ends the program numbered `id`; false when there is none, or it may not
/// be ended (the display server, the caller).
pub fn kill_id(id: u64) -> bool {
    sys::call_result(call::KILL_ID, [id, 0, 0, 0, 0, 0, 0]).0 != ERROR
}

/// What the kernel and the programs wrote to the serial port, its last
/// 64 KiB.
pub fn log() -> String {
    let mut buffer = alloc::vec![0u8; 64 * 1024];
    let len = sys::call2(call::LOG, buffer.as_mut_ptr() as u64, buffer.len() as u64);
    if len == ERROR {
        return String::new();
    }
    buffer.truncate(len as usize);
    String::from_utf8_lossy(&buffer).into_owned()
}

/// The built-in screen's brightness, 0 to 100: None when it has none to
/// set (no driver for its graphics or firmware that sets it; QEMU), or for
/// a confined program.
pub fn brightness() -> Option<u8> {
    let v = sys::call2(call::BRIGHTNESS, 0, 0);
    (v != ERROR).then_some(v as u8)
}

/// Sets the screen's brightness to `percent` (never below 5, which the
/// kernel keeps to) and returns it as it is then; None as [`brightness`].
pub fn set_brightness(percent: u8) -> Option<u8> {
    let v = sys::call2(call::BRIGHTNESS, 1, u64::from(percent));
    (v != ERROR).then_some(v as u8)
}

/// A battery, as [`power`] reads it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Battery {
    /// `charging`, `discharging`, `full` or `absent`.
    pub state: String,
    pub percent: Option<u8>,
    /// To empty, discharging; to full, charging.
    pub minutes: Option<u32>,
    /// The rest, as the kernel wrote it (`remaining`, `full`, `design`,
    /// `unit`, `cycles`, `model`, `maker`).
    pub fields: Vec<(String, String)>,
}

/// The machine's power: none of it on a machine without a battery,
/// charger or lid, or for a confined program.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Power {
    /// The charger plugged in.
    pub ac: Option<bool>,
    pub lid_open: Option<bool>,
    pub batteries: Vec<Battery>,
}

/// The battery, charger and lid, asked of the firmware now.
pub fn power() -> Power {
    let mut buffer = alloc::vec![0u8; 4096];
    let len = sys::call2(call::POWER, buffer.as_mut_ptr() as u64, buffer.len() as u64);
    if len == ERROR {
        return Power::default();
    }
    buffer.truncate(len as usize);
    parse_power(&String::from_utf8_lossy(&buffer))
}

/// What [`power`] reads, from the kernel's lines.
pub fn parse_power(text: &str) -> Power {
    let mut power = Power::default();
    for line in text.lines() {
        if let Some(v) = line.strip_prefix("ac=") {
            power.ac = Some(v == "1");
        } else if let Some(v) = line.strip_prefix("lid=") {
            power.lid_open = Some(v == "open");
        } else if line.starts_with("battery=") {
            let mut b = Battery::default();
            for part in line.split('|').skip(1) {
                let Some((k, v)) = part.split_once('=') else {
                    continue;
                };
                match k {
                    "state" => b.state = v.into(),
                    "percent" => b.percent = v.parse().ok(),
                    "minutes" => b.minutes = v.parse().ok(),
                    _ => b.fields.push((k.into(), v.into())),
                }
            }
            power.batteries.push(b);
        }
    }
    power
}

/// Cores running, bytes of RAM, bytes free.
pub fn info() -> (u64, u64, u64) {
    sys::call_result(call::INFO, [0; 7])
}

/// The system that runs: its version, its board and the slot it runs from
/// (`a`, `b`, or `boot` for the boot kernel's own), `key=value` lines.
pub fn system() -> String {
    let mut buffer = [0u8; 256];
    let (n, ..) = sys::call_result(
        call::SYSTEM,
        [0, buffer.as_mut_ptr() as u64, buffer.len() as u64, 0, 0, 0, 0],
    );
    match buffer.get(..n as usize) {
        Some(bytes) if n != ERROR => String::from_utf8_lossy(bytes).into_owned(),
        _ => String::new(),
    }
}

/// Restarts the device, its disks' writes done; refused (returns) for an
/// installed app.
pub fn restart() {
    sys::call_result(call::SYSTEM, [1, 0, 0, 0, 0, 0, 0]);
}

/// Putting Pinnacle on one of the device's own disks (`call::INSTALL`).
pub mod install {
    use super::sys::call_result;
    use super::{ERROR, call};
    use alloc::string::String;
    use alloc::vec::Vec;

    /// A disk, as the kernel lists it.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct Disk {
        pub name: String,
        pub model: String,
        pub bytes: u64,
        pub removable: bool,
        /// `pinnacle`, `other` (another system's), `unknown` or `empty`.
        pub holds: String,
        /// Whether Pinnacle can be installed on it now.
        pub installable: bool,
    }

    /// How an installation goes.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub enum State {
        Idle,
        Running(String),
        Done(String),
        Failed(String),
    }

    fn text(op: u64) -> String {
        let mut buffer = alloc::vec![0u8; 4096];
        let (n, ..) = call_result(
            call::INSTALL,
            [op, buffer.as_mut_ptr() as u64, buffer.len() as u64, 0, 0, 0, 0],
        );
        match buffer.get(..n as usize) {
            Some(bytes) if n != ERROR => String::from_utf8_lossy(bytes).into_owned(),
            _ => String::new(),
        }
    }

    /// Every disk the kernel found.
    pub fn disks() -> Vec<Disk> {
        text(0)
            .lines()
            .filter_map(|line| {
                let f: Vec<&str> = line.split('|').collect();
                (f.len() == 6).then(|| Disk {
                    name: f[0].into(),
                    model: f[1].into(),
                    bytes: f[2].parse().unwrap_or(0),
                    removable: f[3] == "1",
                    holds: f[4].into(),
                    installable: f[5] == "1",
                })
            })
            .collect()
    }

    /// Starts installing on the disk named `disk`: everything on it is lost.
    pub fn start(disk: &str) -> bool {
        let (r, ..) = call_result(
            call::INSTALL,
            [1, 0, 0, disk.as_ptr() as u64, disk.len() as u64, 0, 0],
        );
        r != ERROR
    }

    /// How the installation goes.
    pub fn state() -> State {
        let t = text(2);
        let (kind, what) = t.split_once('|').unwrap_or((&t, ""));
        match kind {
            "running" => State::Running(what.into()),
            "done" => State::Done(what.into()),
            "failed" => State::Failed(what.into()),
            _ => State::Idle,
        }
    }
}

/// Files: whole-file reads and writes. Paths are "label:/path"; without a
/// label they are on the system disk.
pub mod fs {
    use super::sys::call_result;
    use alloc::string::String;
    use alloc::vec::Vec;
    use pinnacle_abi::{ERROR, call};

    fn path_call(number: u64, path: &str, data: *const u8, size: usize) -> u64 {
        call_result(
            number,
            [
                path.as_ptr() as u64,
                path.len() as u64,
                data as u64,
                size as u64,
                0,
                0,
                0,
            ],
        )
        .0
    }

    pub fn read(path: &str) -> Option<Vec<u8>> {
        let mut buffer = alloc::vec![0u8; 64 * 1024];
        loop {
            let size = path_call(call::READ_FILE, path, buffer.as_mut_ptr(), buffer.len());
            if size == ERROR {
                return None;
            }
            if size as usize <= buffer.len() {
                buffer.truncate(size as usize);
                return Some(buffer);
            }
            // Too large to copy at once: [`read_at`] reads it a range at a time.
            if size as usize > crate::abi::MAX_COPY {
                return None;
            }
            buffer = alloc::vec![0u8; size as usize];
        }
    }

    pub fn read_string(path: &str) -> Option<String> {
        String::from_utf8(read(path)?).ok()
    }

    pub fn write(path: &str, data: &[u8]) -> bool {
        path_call(call::WRITE_FILE, path, data.as_ptr(), data.len()) != ERROR
    }

    /// The names in a directory, directories ending in `/`.
    pub fn list(path: &str) -> Option<Vec<String>> {
        let mut buffer = alloc::vec![0u8; 16 * 1024];
        let len = path_call(call::LIST, path, buffer.as_mut_ptr(), buffer.len());
        if len == ERROR {
            return None;
        }
        buffer.truncate(len as usize);
        Some(
            String::from_utf8_lossy(&buffer)
                .lines()
                .map(String::from)
                .collect(),
        )
    }

    pub fn exists(path: &str) -> bool {
        path_call(call::READ_FILE, path, core::ptr::null(), 0) != ERROR || list(path).is_some()
    }

    /// Removes a file, or a directory and everything in it.
    /// The disk labelled `label`: bytes for files in all, and of them free.
    pub fn disk(label: &str) -> Option<(u64, u64)> {
        let args = [label.as_ptr() as u64, label.len() as u64, 0, 0, 0, 0, 0];
        let (total, free, _) = call_result(call::DISK, args);
        (total != ERROR).then_some((total, free))
    }

    /// What [`stat`] says of a path.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Stat {
        pub directory: bool,
        pub size: u64,
        pub modified: u64,
    }

    /// Up to `len` bytes of a file from `offset`: fewer at its end.
    pub fn read_at(path: &str, offset: u64, len: usize) -> Option<Vec<u8>> {
        let mut buffer = alloc::vec![0u8; len.min(crate::abi::MAX_COPY)];
        let args = [
            path.as_ptr() as u64,
            path.len() as u64,
            offset,
            buffer.as_mut_ptr() as u64,
            buffer.len() as u64,
            0,
            0,
        ];
        let read = call_result(call::READ_AT, args).0;
        (read != ERROR).then(|| {
            buffer.truncate(read as usize);
            buffer
        })
    }

    /// Writes `data` into a file from `offset`, creating and growing it.
    pub fn write_at(path: &str, offset: u64, data: &[u8]) -> bool {
        let args = [
            path.as_ptr() as u64,
            path.len() as u64,
            offset,
            data.as_ptr() as u64,
            data.len() as u64,
            0,
            0,
        ];
        call_result(call::WRITE_AT, args).0 != ERROR
    }

    /// What is at a path: a file or a directory, its size, and when it last
    /// changed (seconds since 1970; 0 without a clock).
    pub fn stat(path: &str) -> Option<Stat> {
        let args = [path.as_ptr() as u64, path.len() as u64, 0, 0, 0, 0, 0];
        let (size, kind, modified) = call_result(call::STAT, args);
        (size != ERROR).then_some(Stat {
            directory: kind == 2,
            size,
            modified,
        })
    }

    pub fn remove(path: &str) -> bool {
        path_call(call::REMOVE, path, core::ptr::null(), 0) != ERROR
    }

    pub fn create_dir(path: &str) -> bool {
        path_call(call::CREATE_DIR, path, core::ptr::null(), 0) != ERROR
    }

    /// A handle to one file (`pinnacle_abi::file` has the rights): what a
    /// person gives a program instead of a path, and what an append-only
    /// log is written through.
    pub struct File(pub crate::Handle);

    pub use pinnacle_abi::file::{APPEND, READ, WRITE};

    impl File {
        /// The file at `path`, with `rights`, if the caller may have them.
        pub fn open(path: &str, rights: u64) -> Option<File> {
            let args = [path.as_ptr() as u64, path.len() as u64, rights, 0, 0, 0, 0];
            let h = call_result(call::OPEN_FILE, args).0;
            // SAFETY: the kernel just gave it.
            (h != ERROR).then(|| File(unsafe { crate::Handle::from_raw(h) }))
        }

        fn op(&self, op: u64, offset: u64, buffer: u64, len: u64) -> u64 {
            call_result(call::FILE, [self.0.raw(), op, offset, buffer, len, 0, 0]).0
        }

        /// Up to `len` bytes from `offset`: fewer at its end.
        pub fn read_at(&self, offset: u64, len: usize) -> Option<Vec<u8>> {
            let mut buffer = alloc::vec![0u8; len.min(crate::abi::MAX_COPY)];
            let read = self.op(
                pinnacle_abi::file::OP_READ,
                offset,
                buffer.as_mut_ptr() as u64,
                buffer.len() as u64,
            );
            (read != ERROR).then(|| {
                buffer.truncate(read as usize);
                buffer
            })
        }

        /// The whole file, a range at a time.
        pub fn read(&self) -> Option<Vec<u8>> {
            let size = self.stat()?.size;
            let mut out = Vec::with_capacity(size as usize);
            while (out.len() as u64) < size {
                let piece = self.read_at(out.len() as u64, crate::abi::MAX_COPY)?;
                if piece.is_empty() {
                    break;
                }
                out.extend_from_slice(&piece);
            }
            Some(out)
        }

        pub fn write_at(&self, offset: u64, data: &[u8]) -> bool {
            let op = pinnacle_abi::file::OP_WRITE;
            self.op(op, offset, data.as_ptr() as u64, data.len() as u64) != ERROR
        }

        /// Makes the file `data`, whole.
        pub fn replace(&self, data: &[u8]) -> bool {
            let op = pinnacle_abi::file::OP_REPLACE;
            self.op(op, 0, data.as_ptr() as u64, data.len() as u64) != ERROR
        }

        /// Adds `data` at the end, at once; the offset it went to.
        pub fn append(&self, data: &[u8]) -> Option<u64> {
            let op = pinnacle_abi::file::OP_APPEND;
            let at = self.op(op, 0, data.as_ptr() as u64, data.len() as u64);
            (at != ERROR).then_some(at)
        }

        pub fn stat(&self) -> Option<Stat> {
            let args = [self.0.raw(), pinnacle_abi::file::OP_STAT, 0, 0, 0, 0, 0];
            let (size, kind, modified) = call_result(call::FILE, args);
            (size != ERROR).then_some(Stat {
                directory: kind == 2,
                size,
                modified,
            })
        }

        /// A second handle to the file with fewer rights, to give on.
        pub fn narrow(&self, rights: u64) -> Option<File> {
            let h = self.op(pinnacle_abi::file::OP_NARROW, rights, 0, 0);
            // SAFETY: the kernel just gave it.
            (h != ERROR).then(|| File(unsafe { crate::Handle::from_raw(h) }))
        }

        pub fn rights(&self) -> u64 {
            self.op(pinnacle_abi::file::OP_RIGHTS, 0, 0, 0)
        }
    }

    /// `key=value` lines, as in an app's manifest.
    pub fn field<'a>(text: &'a str, key: &str) -> Option<&'a str> {
        text.lines()
            .find_map(|line| line.strip_prefix(key)?.strip_prefix('='))
    }
}

/// The network: TCP connections and UDP sockets as channels, names,
/// and an HTTP client.
pub mod net {
    use super::{Channel, Handle, Received, sys};
    use alloc::string::String;
    use alloc::vec::Vec;
    use pinnacle_abi::{ERROR, call};

    pub type Ipv4 = [u8; 4];
    pub use pinnacle_net::{IpAddr, Ipv6, parse_ip, parse_ipv4, parse_ipv6};

    /// The IPv6 address, router and name server, once a router has given
    /// an address (the router or name server `None` when it named none).
    pub fn info6() -> Option<(Ipv6, Option<Ipv6>, Option<Ipv6>)> {
        let mut info = [0u8; 48];
        let n = sys::call2(call::NET_INFO6, info.as_mut_ptr() as u64, info.len() as u64);
        let known = |at: usize| -> Option<Ipv6> {
            let ip: Ipv6 = info[at..at + 16].try_into().unwrap();
            (ip != [0; 16]).then_some(ip)
        };
        (n == 48).then(|| (known(0).unwrap_or_default(), known(16), known(32)))
    }

    /// The address, router and name server, once DHCP has given them.
    pub fn info() -> Option<(Ipv4, Ipv4, Ipv4)> {
        let (ip, router, dns) = sys::call_result(call::NET_INFO, [0; 7]);
        (ip != ERROR).then(|| {
            (
                (ip as u32).to_be_bytes(),
                (router as u32).to_be_bytes(),
                (dns as u32).to_be_bytes(),
            )
        })
    }

    /// Where the network is: one of `pinnacle_abi::net`'s states.
    pub fn state() -> u64 {
        sys::call1(call::NET_SWITCH, 0)
    }

    /// Switches the network on or off; where it is then, or `None` for an
    /// installed app, which may not.
    pub fn switch(on: bool) -> Option<u64> {
        let state = sys::call1(call::NET_SWITCH, if on { 1 } else { 2 });
        (state != ERROR).then_some(state)
    }

    /// Waits up to `ms` for the network to be configured.
    pub fn wait_configured(ms: u64) -> Option<Ipv4> {
        let until = super::time() + ms;
        loop {
            if let Some((ip, ..)) = info() {
                return Some(ip);
            }
            if super::time() >= until {
                return None;
            }
            super::sleep(50);
        }
    }

    /// A TCP connection, over IPv4 or IPv6: send bytes on it, receive what
    /// arrives; it closes when the connection ends.
    pub fn connect(ip: impl Into<IpAddr>, port: u16) -> Option<Channel> {
        let h = match ip.into() {
            IpAddr::V4(ip) => sys::call2(
                call::CONNECT_TCP,
                u64::from(u32::from_be_bytes(ip)),
                u64::from(port),
            ),
            IpAddr::V6(ip) => {
                let high = u64::from_be_bytes(ip[..8].try_into().unwrap());
                let low = u64::from_be_bytes(ip[8..].try_into().unwrap());
                sys::call_result(call::CONNECT_TCP6, [high, low, u64::from(port), 0, 0, 0, 0]).0
            }
        };
        // SAFETY: the kernel just gave it.
        (h != ERROR).then(|| Channel(unsafe { Handle::from_raw(h) }))
    }

    /// Listens on TCP `port`: each connection accepted arrives on the
    /// channel as a message carrying the connection's channel. None for a
    /// port taken, or without the right to the network.
    pub fn listen(port: u16) -> Option<Channel> {
        let h = sys::call1(call::LISTEN_TCP, u64::from(port));
        // SAFETY: the kernel just gave it.
        (h != ERROR).then(|| Channel(unsafe { Handle::from_raw(h) }))
    }

    /// A UDP socket and the port it got.
    pub fn udp_bind(port: u16) -> Option<(Channel, u16)> {
        let (h, port, _) = sys::call_result(call::UDP_BIND, [u64::from(port), 0, 0, 0, 0, 0, 0]);
        // SAFETY: the kernel just gave it.
        (h != ERROR).then(|| (Channel(unsafe { Handle::from_raw(h) }), port as u16))
    }

    /// Sends a datagram on a UDP socket's channel.
    pub fn send_to(socket: &Channel, to: Ipv4, port: u16, data: &[u8]) -> bool {
        let mut m = Vec::with_capacity(6 + data.len());
        m.extend_from_slice(&to);
        m.extend_from_slice(&port.to_be_bytes());
        m.extend_from_slice(data);
        socket.send(&m, Vec::new())
    }

    /// A datagram's sender, port and data, from a UDP socket's message.
    pub fn datagram(message: &[u8]) -> Option<(Ipv4, u16, &[u8])> {
        let ip = message.get(..4)?.try_into().ok()?;
        let port = u16::from_be_bytes(message.get(4..6)?.try_into().ok()?);
        Some((ip, port, &message[6..]))
    }

    /// A name's address ("10.0.2.2", "2001:db8::1" or "example.org"):
    /// IPv4 while the network has it, else IPv6 (`pinnacle_net::Event::Resolved`).
    pub fn resolve(name: &str) -> Option<IpAddr> {
        let h = sys::call2(call::RESOLVE, name.as_ptr() as u64, name.len() as u64);
        if h == ERROR {
            return None;
        }
        // SAFETY: the kernel just gave it.
        let channel = Channel(unsafe { Handle::from_raw(h) });
        let mut buffer = [0u8; 16];
        match super::receive(&[&channel], &mut buffer, Some(super::time() + 5000)) {
            Received::Message { len: 4, .. } => Some(IpAddr::V4(buffer[..4].try_into().unwrap())),
            Received::Message { len: 16, .. } => Some(IpAddr::V6(buffer)),
            _ => None,
        }
    }

    pub use pinnacle_net::http::{Events, Head};

    #[derive(Debug)]
    pub enum HttpError {
        BadUrl,
        NoAddress,
        NoConnection,
        TimedOut,
        BadResponse,
        Status(u16),
        /// Moved elsewhere (a 3xx with a Location), followed by [`http_get`].
        Moved(String),
        TooManyRedirects,
        /// No roots to check a TLS server against.
        NoRoots,
        /// The TLS handshake or a record failed.
        Tls(pinnacle_tls::client::Error),
        /// The reader of the body said to stop.
        Stopped,
        /// The server broke HTTP/2, or reset the request.
        Http2(pinnacle_net::http2::Error),
    }

    /// The body of `url` ("http://host[:port]/path" or "https://…"), by
    /// GET, waiting up to `timeout` ms for each piece (redirects followed,
    /// up to five). Over https the server's certificates are checked against
    /// the roots on the system disk (`/certificates/roots.pem`, Mozilla's)
    /// at this device's time.
    pub fn http_get(url: &str, timeout: u64) -> Result<Vec<u8>, HttpError> {
        // Redirects followed, a few: a relative one against where it came from.
        let mut url = String::from(url);
        for _ in 0..5 {
            let mut body = Vec::new();
            let head = request("GET", &url, &[], &[], timeout, |piece| {
                body.extend_from_slice(piece);
                true
            })?;
            match head.status {
                200 => return Ok(body),
                301..=308 => {
                    let to = head.header("location").ok_or(HttpError::BadResponse)?.trim();
                    if to.starts_with("http://") || to.starts_with("https://") {
                        url = String::from(to);
                    } else if to.starts_with('/') {
                        let scheme_end = url.find("://").map_or(0, |i| i + 3);
                        let origin_end = url[scheme_end..].find('/').map_or(url.len(), |i| scheme_end + i);
                        url = alloc::format!("{}{to}", &url[..origin_end]);
                    } else {
                        return Err(HttpError::Moved(String::from(to)));
                    }
                }
                status => return Err(HttpError::Status(status)),
            }
        }
        Err(HttpError::TooManyRedirects)
    }

    /// One request of any method, with headers and a body, no redirect
    /// followed: over HTTP/2 when an https server chooses it (ALPN), else
    /// HTTP/1.1. The body of the answer goes to `body` a piece at a
    /// time as it arrives (server-sent events as they are sent), whatever
    /// the status; `body` returning false ends the request with
    /// [`HttpError::Stopped`]. `timeout` is the longest wait for a piece.
    /// Returns the status and headers.
    pub fn request(
        method: &str,
        url: &str,
        headers: &[(&str, &str)],
        payload: &[u8],
        timeout: u64,
        body: impl FnMut(&[u8]) -> bool,
    ) -> Result<Head, HttpError> {
        exchange(method, url, headers, payload, timeout, true, body).map(|(head, _)| head)
    }

    /// The time of day an https server gives (its `Date` header), seconds
    /// since 1970, for a device whose clock is not set yet: its
    /// certificates are checked against the roots at no time in particular,
    /// and the date believed only if every one of them is valid then. A
    /// server cannot give a date outside its certificates' life; one whose
    /// key was stolen could within it, as with any connection of TLS.
    pub fn date(url: &str, timeout: u64) -> Result<u64, HttpError> {
        let (head, window) = exchange("GET", url, &[], &[], timeout, false, |_| true)?;
        let date = head.header("date").and_then(pinnacle_net::http::date);
        match (date, window) {
            (Some(date), Some((from, until))) if (from..=until).contains(&date) && date > 0 => {
                Ok(date as u64)
            }
            _ => Err(HttpError::BadResponse),
        }
    }

    /// Why a key exchange for Network Time Security gave no keys.
    #[derive(Debug)]
    pub enum NtsError {
        /// The connection, or TLS over it.
        Connection(HttpError),
        /// The server's answer.
        Refused(pinnacle_net::nts::KeRefused),
    }

    /// A key exchange for Network Time Security (RFC 8915,
    /// `pinnacle_net::nts`) with `host` at `port`: the two keys, the
    /// cookies and the NTP server to ask, and the span in which the
    /// server's certificates are all valid. They are checked at no time in
    /// particular, as for [`date`], since the clock is what is to be set: a
    /// time its NTP server gives is to be believed only within that span.
    pub fn nts_keys(
        host: &str,
        port: u16,
        timeout: u64,
    ) -> Result<(pinnacle_net::nts::Keys, pinnacle_net::nts::Agreed, (i64, i64)), NtsError> {
        use pinnacle_net::nts;
        let fail = NtsError::Connection;
        let ip = resolve(host).ok_or(fail(HttpError::NoAddress))?;
        let channel = connect(ip, port).ok_or(fail(HttpError::NoConnection))?;
        let mut connection =
            Connection::open(channel, Some(host), timeout, false, &[nts::ALPN]).map_err(fail)?;
        let tls = connection.tls.as_ref().unwrap();
        if tls.protocol() != Some(nts::ALPN) {
            return Err(NtsError::Refused(nts::KeRefused::Unsupported));
        }
        let window = tls.window().ok_or(fail(HttpError::BadResponse))?;
        let export = |context: &[u8]| -> [u8; 32] {
            let key = tls.export(nts::EXPORTER, context, 32).unwrap();
            key[..].try_into().unwrap()
        };
        let keys = nts::Keys {
            c2s: export(&nts::C2S),
            s2c: export(&nts::S2C),
        };
        connection.send(&nts::ke_request());
        let mut answer = Vec::new();
        loop {
            let Some(bytes) = connection.receive(timeout).map_err(fail)? else {
                return Err(NtsError::Refused(nts::KeRefused::Malformed));
            };
            answer.extend_from_slice(&bytes);
            if let Some(agreed) = nts::ke_response(&answer).map_err(NtsError::Refused)? {
                return Ok((keys, agreed, window));
            }
        }
    }

    /// [`request`], `timed` as [`Connection::open`] has it; with the span
    /// the server's certificates are valid in when untimed.
    fn exchange(
        method: &str,
        url: &str,
        headers: &[(&str, &str)],
        payload: &[u8],
        timeout: u64,
        timed: bool,
        mut body: impl FnMut(&[u8]) -> bool,
    ) -> Result<(Head, Option<(i64, i64)>), HttpError> {
        let (secure, rest) = match url.strip_prefix("https://") {
            Some(rest) => (true, rest),
            None => (false, url.strip_prefix("http://").ok_or(HttpError::BadUrl)?),
        };
        let (authority, path) = match rest.find('/') {
            Some(i) => (&rest[..i], &rest[i..]),
            None => (rest, "/"),
        };
        // A name, an IPv4 address, or an IPv6 one in brackets
        // ("[2001:db8::1]:8080"), each with a port or not.
        let (host, port) = match authority.rsplit_once(':').filter(|(_, p)| !p.contains(']')) {
            Some((h, p)) => (h, p.parse().map_err(|_| HttpError::BadUrl)?),
            None => (authority, if secure { 443 } else { 80 }),
        };
        if host.is_empty() {
            return Err(HttpError::BadUrl);
        }
        let ip = resolve(host.trim_start_matches('[').trim_end_matches(']')).ok_or(HttpError::NoAddress)?;
        let channel = connect(ip, port).ok_or(HttpError::NoConnection)?;
        let alpn = ["h2", "http/1.1"];
        let mut connection = Connection::open(channel, secure.then_some(host), timeout, timed, &alpn)?;
        if connection.tls.as_ref().and_then(|c| c.protocol()) == Some("h2") {
            let default = if secure { 443 } else { 80 };
            let authority = match port == default {
                true => String::from(host),
                false => alloc::format!("{host}:{port}"),
            };
            let window = connection.tls.as_ref().and_then(|c| c.window());
            let head = request2(
                &mut connection,
                method,
                &authority,
                path,
                headers,
                payload,
                timeout,
                body,
            )?;
            return Ok((head, window));
        }
        let wire = pinnacle_net::http::Request {
            method,
            host,
            path,
            headers,
            body: payload,
        }
        .encode();
        connection.send(&wire);
        let mut response = pinnacle_net::http::Response::new();
        while !response.done() {
            match connection.receive(timeout)? {
                Some(bytes) => response.receive(&bytes).map_err(|_| HttpError::BadResponse)?,
                None => response.close().map_err(|_| HttpError::BadResponse)?,
            }
            let piece = response.take_body();
            if !piece.is_empty() && !body(&piece) {
                return Err(HttpError::Stopped);
            }
        }
        let window = connection.tls.as_ref().and_then(|c| c.window());
        Ok((response.head().cloned().ok_or(HttpError::BadResponse)?, window))
    }

    /// [`request`] over HTTP/2: one stream on a connection of its own.
    #[allow(clippy::too_many_arguments)]
    fn request2(
        connection: &mut Connection,
        method: &str,
        authority: &str,
        path: &str,
        headers: &[(&str, &str)],
        payload: &[u8],
        timeout: u64,
        mut body: impl FnMut(&[u8]) -> bool,
    ) -> Result<Head, HttpError> {
        let mut h2 = pinnacle_net::http2::Connection::new();
        let stream = h2.request(method, "https", authority, path, headers, payload);
        connection.send(&h2.take_output());
        while !h2.done(stream) {
            match connection.receive(timeout)? {
                Some(bytes) => {
                    let got = h2.receive(&bytes);
                    // SETTINGS acknowledged, windows given back, or the
                    // GOAWAY that says why it ended.
                    connection.send(&h2.take_output());
                    got.map_err(HttpError::Http2)?;
                }
                None => h2.close(),
            }
            let piece = h2.take_body(stream);
            if !piece.is_empty() && !body(&piece) {
                return Err(HttpError::Stopped);
            }
        }
        h2.result(stream).map_err(HttpError::Http2)?;
        h2.head(stream).cloned().ok_or(HttpError::BadResponse)
    }

    /// A TCP connection, plain or under TLS.
    struct Connection {
        channel: Channel,
        tls: Option<pinnacle_tls::client::Client>,
        buffer: Vec<u8>,
    }

    impl Connection {
        /// Over TLS to `host` when given one: the handshake done before it
        /// returns.
        /// `timed` false: its certificates checked at no time in particular
        /// ([`Verify::Untimed`](pinnacle_tls::client::Verify::Untimed)), for
        /// [`date`] and [`nts_keys`]. `alpn`: the protocols offered.
        fn open(
            channel: Channel,
            host: Option<&str>,
            timeout: u64,
            timed: bool,
            alpn: &[&str],
        ) -> Result<Connection, HttpError> {
            let mut connection = Connection {
                channel,
                tls: None,
                buffer: alloc::vec![0u8; pinnacle_abi::MAX_MESSAGE],
            };
            let Some(host) = host else {
                return Ok(connection);
            };
            use pinnacle_tls::client::{Client, Config, Verify};
            let roots = super::fs::read_string(ROOTS).ok_or(HttpError::NoRoots)?;
            let roots = pinnacle_tls::pem::certificates(&roots);
            let config = Config {
                host: host.into(),
                verify: if timed {
                    Verify::Roots {
                        roots,
                        now: super::clock() as i64,
                    }
                } else {
                    Verify::Untimed { roots }
                },
                min_rsa_bits: 2048,
                alpn: alpn.iter().map(|&p| p.into()).collect(),
            };
            let mut random = [0u8; 96];
            super::random(&mut random);
            connection.tls = Some(Client::new(
                config,
                random[..32].try_into().unwrap(),
                random[32..64].try_into().unwrap(),
                random[64..].try_into().unwrap(),
            ));
            loop {
                connection.flush();
                let client = connection.tls.as_mut().unwrap();
                if client.connected() {
                    return Ok(connection);
                }
                match super::receive(
                    &[&connection.channel],
                    &mut connection.buffer,
                    Some(super::time() + timeout),
                ) {
                    Received::Message { len, .. } => client
                        .receive(&connection.buffer[..len])
                        .map_err(HttpError::Tls)?,
                    Received::Closed { .. } => return Err(HttpError::NoConnection),
                    Received::Timeout => return Err(HttpError::TimedOut),
                }
            }
        }

        /// What TLS has to send, sent.
        fn flush(&mut self) {
            if let Some(client) = &mut self.tls {
                for chunk in client.take_output().chunks(pinnacle_abi::MAX_MESSAGE) {
                    self.channel.send(chunk, Vec::new());
                }
            }
        }

        fn send(&mut self, bytes: &[u8]) {
            match &mut self.tls {
                Some(client) => {
                    client.write(bytes);
                    self.flush();
                }
                None => {
                    for chunk in bytes.chunks(pinnacle_abi::MAX_MESSAGE) {
                        self.channel.send(chunk, Vec::new());
                    }
                }
            }
        }

        /// The next bytes that arrive, or None once the server closed.
        fn receive(&mut self, timeout: u64) -> Result<Option<Vec<u8>>, HttpError> {
            loop {
                if self.tls.as_ref().is_some_and(|c| c.closed()) {
                    return Ok(None);
                }
                match super::receive(&[&self.channel], &mut self.buffer, Some(super::time() + timeout)) {
                    Received::Message { len, .. } => {
                        let Some(client) = &mut self.tls else {
                            return Ok(Some(self.buffer[..len].to_vec()));
                        };
                        client.receive(&self.buffer[..len]).map_err(HttpError::Tls)?;
                        self.flush();
                        let plain = self.tls.as_mut().unwrap().read();
                        if !plain.is_empty() {
                            return Ok(Some(plain));
                        }
                    }
                    // Some servers close without saying so first.
                    Received::Closed { .. } => return Ok(None),
                    Received::Timeout => return Err(HttpError::TimedOut),
                }
            }
        }
    }

    /// Where the roots a TLS server's chain must reach are.
    pub const ROOTS: &str = "system:/certificates/roots.pem";
}

/// Sends a rectangle of the screen's framebuffer to the screen, where the
/// display needs telling (the display server, after drawing).
pub fn flush_screen(x: i32, y: i32, width: i32, height: i32) {
    sys::call_result(
        call::FLUSH_SCREEN,
        [x as u64, y as u64, width as u64, height as u64, 0, 0, 0],
    );
}

/// The port to the device's Bluetooth controller (HCI over H4) as a
/// channel: for the `bt` service. None without a controller.
pub fn bluetooth_port() -> Option<Channel> {
    let h = sys::call0(call::BLUETOOTH_PORT);
    // SAFETY: the kernel just gave it.
    (h != ERROR).then(|| Channel(unsafe { Handle::from_raw(h) }))
}

/// The port to the device's cellular modem (AT commands) as a channel:
/// for the `phone` service. None without a modem.
pub fn modem_port() -> Option<Channel> {
    let h = sys::call0(call::MODEM_PORT);
    // SAFETY: the kernel just gave it.
    (h != ERROR).then(|| Channel(unsafe { Handle::from_raw(h) }))
}

/// The port to the device's Wi-Fi radio (AT commands) as a channel: for
/// the `wifi` service. None without a radio.
pub fn wifi_port() -> Option<Channel> {
    let h = sys::call0(call::WIFI_PORT);
    // SAFETY: the kernel just gave it.
    (h != ERROR).then(|| Channel(unsafe { Handle::from_raw(h) }))
}

/// Random bytes from the kernel, for keys.
pub fn random(out: &mut [u8]) {
    for chunk in out.chunks_mut(4096) {
        sys::call2(call::RANDOM, chunk.as_mut_ptr() as u64, chunk.len() as u64);
    }
}
/// The 3D GPU: a context of the program's own, whose Venus runs its Vulkan
/// on the host's ([`pinnacle_venus`] speaks Vulkan over it).
pub mod gpu {
    use super::{Channel, Handle, Memory, Received, sys};
    use alloc::vec::Vec;
    use pinnacle_abi::{ERROR, call, gpu};

    /// A context on the 3D GPU: closing it ends it.
    pub struct Context {
        channel: Channel,
    }

    impl Context {
        /// None without a 3D GPU, or for an app not granted one.
        pub fn open() -> Option<Context> {
            let h = sys::call0(call::GPU);
            // SAFETY: the kernel just gave it.
            (h != ERROR).then(|| Context {
                channel: Channel(unsafe { Handle::from_raw(h) }),
            })
        }

        /// Sends a command stream (whole commands, at most
        /// [`MAX_MESSAGE`](pinnacle_abi::MAX_MESSAGE) - 4 bytes).
        pub fn submit(&self, stream: &[u8]) -> bool {
            let mut message = Vec::with_capacity(4 + stream.len());
            message.extend_from_slice(&gpu::SUBMIT.to_le_bytes());
            message.extend_from_slice(stream);
            self.channel.send(&message, Vec::new())
        }

        /// Memory the host shares, mapped: `blob_id` 0 for memory of
        /// Venus's own, else a `VkDeviceMemory`'s id. Returns the resource
        /// Venus names it by, and the memory.
        pub fn blob(&self, blob_id: u64, size: u64) -> Option<(u32, Memory)> {
            let mut message = Vec::with_capacity(20);
            message.extend_from_slice(&gpu::BLOB.to_le_bytes());
            message.extend_from_slice(&blob_id.to_le_bytes());
            message.extend_from_slice(&size.to_le_bytes());
            if !self.channel.send(&message, Vec::new()) {
                return None;
            }
            let mut reply = [0u8; 12];
            let Received::Message {
                len: 12, mut handles, ..
            } = self.channel.receive(&mut reply)
            else {
                return None;
            };
            let word = |at: usize| u32::from_le_bytes(reply[at..at + 4].try_into().unwrap());
            if word(0) != gpu::BLOB || word(4) != 0 {
                return None;
            }
            Some((word(8), Memory::map(handles.pop()?)?))
        }
    }

    impl pinnacle_venus::Host for Context {
        type Memory = Memory;

        fn submit(&mut self, stream: &[u8]) -> bool {
            Context::submit(self, stream)
        }

        fn blob(&mut self, blob_id: u64, size: u64) -> Option<(u32, Memory)> {
            Context::blob(self, blob_id, size)
        }

        fn address(memory: &Memory) -> usize {
            memory.address
        }

        fn free(&mut self, memory: Memory) {
            memory.unmap();
        }

        fn now_ms(&self) -> u64 {
            super::time()
        }
    }
}

/// Sound: playing and recording through the kernel's mixer, as channels.
pub mod audio {
    use super::{Channel, Handle, Received, sys};
    use alloc::vec::Vec;
    use pinnacle_abi::{ERROR, call};

    /// Milliseconds a player keeps queued at the kernel at most: `write`
    /// waits once more than this is waiting.
    const HIGH_MS: u32 = 300;

    /// A playback stream: interleaved 16-bit samples at its rate.
    pub struct Player {
        channel: Channel,
        rate: u32,
        channels: u32,
        /// Frames waiting at the kernel, as last reported and sent since.
        queued: u32,
    }

    impl Player {
        /// None without a sound device, or for a rate the device's 48 000 Hz
        /// is not a multiple of (8000, 12000, 16000, 24000 and 48000 are).
        pub fn open(rate: u32, channels: u32) -> Option<Player> {
            let h = sys::call2(call::AUDIO_PLAY, u64::from(rate), u64::from(channels));
            (h != ERROR).then(|| Player {
                // SAFETY: the kernel just gave it.
                channel: Channel(unsafe { Handle::from_raw(h) }),
                rate,
                channels,
                queued: 0,
            })
        }

        /// The channel the kernel's reports arrive on: an app waiting on
        /// several channels at once passes what arrives to [`Player::report`].
        pub fn channel(&self) -> &Channel {
            &self.channel
        }

        pub fn rate(&self) -> u32 {
            self.rate
        }

        pub fn channels(&self) -> u32 {
            self.channels
        }

        /// Queues `samples` (interleaved), waiting while more than 300 ms is
        /// queued already.
        pub fn write(&mut self, samples: &[i16]) {
            let channels = self.channels as usize;
            let per_message = pinnacle_abi::MAX_MESSAGE / 2 / channels * channels;
            for chunk in samples.chunks(per_message) {
                let mut bytes = Vec::with_capacity(chunk.len() * 2);
                for s in chunk {
                    bytes.extend_from_slice(&s.to_le_bytes());
                }
                if !self.channel.send(&bytes, Vec::new()) {
                    return;
                }
                self.queued += (chunk.len() / channels) as u32;
                while self.queued > self.rate / 1000 * HIGH_MS {
                    if !self.take_report(None) {
                        return;
                    }
                }
            }
        }

        /// A message that arrived on the channel: how many frames are left.
        pub fn report(&mut self, message: &[u8]) {
            if let Some(b) = message.get(..4) {
                self.queued = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
            }
        }

        /// Waits for the kernel's next report, until `deadline` (ms since
        /// boot). False when the stream is gone or the deadline passed.
        fn take_report(&mut self, deadline: Option<u64>) -> bool {
            let mut b = [0u8; 8];
            match super::receive(&[&self.channel], &mut b, deadline) {
                Received::Message { len, .. } => {
                    self.report(&b[..len]);
                    true
                }
                _ => false,
            }
        }

        /// Waits until everything queued has gone to the device, and the
        /// device's own 80 ms after it: safe to close then.
        pub fn drain(&mut self) {
            let until = super::time() + u64::from(self.queued) * 1000 / u64::from(self.rate) + 1000;
            while self.queued > 0 {
                if !self.take_report(Some(until)) {
                    break;
                }
            }
            super::sleep(100);
        }
    }

    /// A capture stream: each 10 ms period arrives as a message of
    /// interleaved 16-bit samples at its rate.
    pub struct Recorder {
        channel: Channel,
        rate: u32,
        channels: u32,
    }

    impl Recorder {
        /// None without a device that records, or for a rate it cannot give.
        pub fn open(rate: u32, channels: u32) -> Option<Recorder> {
            let h = sys::call2(call::AUDIO_RECORD, u64::from(rate), u64::from(channels));
            (h != ERROR).then(|| Recorder {
                // SAFETY: the kernel just gave it.
                channel: Channel(unsafe { Handle::from_raw(h) }),
                rate,
                channels,
            })
        }

        pub fn channel(&self) -> &Channel {
            &self.channel
        }

        pub fn rate(&self) -> u32 {
            self.rate
        }

        pub fn channels(&self) -> u32 {
            self.channels
        }

        /// The samples in a message from the channel.
        pub fn samples(message: &[u8]) -> Vec<i16> {
            message
                .as_chunks::<2>()
                .0
                .iter()
                .map(|b| i16::from_le_bytes(*b))
                .collect()
        }

        /// Waits for the next period's samples; None once the stream is gone.
        pub fn read(&self) -> Option<Vec<i16>> {
            let mut b = [0u8; pinnacle_abi::MAX_MESSAGE];
            match self.channel.receive(&mut b) {
                Received::Message { len, .. } => Some(Self::samples(&b[..len])),
                _ => None,
            }
        }
    }

    /// Sets the volume (percent) when one is given, and returns the one
    /// before. None without a sound device.
    pub fn volume(percent: Option<u8>) -> Option<u8> {
        let v = sys::call1(call::AUDIO_VOLUME, percent.map_or(u64::MAX, u64::from));
        (v != ERROR).then_some(v as u8)
    }
}

/// The disk of the person's own data, kept in a vault (the display server
/// only): whether it waits for a passphrase, and opening or making it.
pub mod vault {
    use super::sys;
    use pinnacle_abi::{ERROR, call};

    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    pub enum State {
        /// None waits: open already, or no such disk.
        None,
        /// A blank disk, for a new vault and its first passphrase.
        Blank,
        Locked,
    }

    pub fn state() -> State {
        match sys::call_result(call::VAULT, [0; 7]).0 {
            1 => State::Blank,
            2 => State::Locked,
            _ => State::None,
        }
    }

    fn request(op: u64, passphrase: &str) -> bool {
        let args = [
            op,
            passphrase.as_ptr() as u64,
            passphrase.len() as u64,
            0,
            0,
            0,
            0,
        ];
        sys::call_result(call::VAULT, args).0 != ERROR
    }

    /// Opens the vault; false for a wrong passphrase.
    pub fn open(passphrase: &str) -> bool {
        request(1, passphrase)
    }

    /// Makes the blank disk a vault opened by `passphrase`.
    pub fn create(passphrase: &str) -> bool {
        request(2, passphrase)
    }

    /// Whether `password` opens the open vault: the lock screen's check.
    pub fn check(password: &str) -> bool {
        request(3, password)
    }

    /// Seals the open vault under `new`, given `old`.
    pub fn change(old: &str, new: &str) -> bool {
        let args = [
            4,
            old.as_ptr() as u64,
            old.len() as u64,
            new.as_ptr() as u64,
            new.len() as u64,
            0,
            0,
        ];
        sys::call_result(call::VAULT, args).0 != ERROR
    }
}

/// What the person chose for this device and every app may read: the time
/// zone and the keyboard's layout, files in `system:/locale` that Settings
/// writes; and the zones themselves, `system:/zoneinfo` (`zoneinfo/`).
pub mod locale {
    use alloc::string::String;
    pub use pinnacle_tz::{DateTime, Local, Zone};

    /// The zone's name (`Europe/Amsterdam`).
    pub const ZONE: &str = "system:/locale/zone";
    /// The keyboard's layout (`us`, `us-intl`, `nl`).
    pub const KEYBOARD: &str = "system:/locale/keyboard";
    /// The zones, and their list (`zones`).
    pub const ZONEINFO: &str = "system:/zoneinfo";

    /// The zone chosen, by name; None for UTC, or one never chosen.
    pub fn zone_name() -> Option<String> {
        let name = super::fs::read_string(ZONE)?;
        let name = name.trim();
        pinnacle_tz::valid_name(name).then(|| name.into())
    }

    /// The zone `name`, read from `system:/zoneinfo`.
    pub fn zone_named(name: &str) -> Option<Zone> {
        if !pinnacle_tz::valid_name(name) {
            return None;
        }
        Zone::parse(&super::fs::read(&alloc::format!("{ZONEINFO}/{name}"))?)
    }

    /// The zone chosen; UTC when none is, or its file is missing.
    pub fn zone() -> Zone {
        zone_name().and_then(|n| zone_named(&n)).unwrap_or_else(Zone::utc)
    }

    /// The local date and time now in `zone`, and what the zone says of
    /// it; None while the device does not know the time of day.
    pub fn now_in(zone: &Zone) -> Option<(DateTime, Local)> {
        match super::clock() {
            0 => None,
            seconds => Some(zone.civil(seconds as i64)),
        }
    }

    /// "14:05": the local time in the zone chosen (read afresh), or the
    /// time since boot while the time of day is not known.
    pub fn time_text() -> String {
        let (hour, minute) = match now_in(&zone()) {
            Some((t, _)) => (u64::from(t.hour), u64::from(t.minute)),
            None => {
                let s = super::time() / 1000;
                (s / 3600 % 24, s / 60 % 60)
            }
        };
        alloc::format!("{hour:02}:{minute:02}")
    }

    /// The keyboard layout chosen, `us` when none is.
    pub fn keyboard() -> String {
        super::fs::read_string(KEYBOARD)
            .map(|s| String::from(s.trim()))
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "us".into())
    }
}