garage44.eu/jeroen/pinnacle

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

.. /ui/src/updates.rs

raw

//! Updates, as Settings and the updates service (`programs/src/bin/updates.rs`)
//! share them: the person's choice (`/settings/updates`), what the last look
//! found (`/settings/updates-last`), and the service's messages.
//!
//! The choice is one of three: not looking at all, looking and telling (the
//! default: a notification names what the Store can update), or looking and
//! installing by itself what asks for no more than the version installed
//! may do. An update that asks for more is only told, and installed from the
//! Store, where its rights show before the tap.

use alloc::string::String;
use alloc::vec::Vec;

use pinnacle_pkg::system::{self, Record, Slot};
use pinnacle_rt::{Channel, fs};

/// The service, `system-` so that no installed app reaches it.
pub const SERVICE: &str = "system-updates";

/// Settings โ†’ service: look now (no body); answered with [`LOOKED`] once
/// the look is over.
pub const LOOK: u8 = 1;
/// Settings โ†’ service: the choice changed (no body); the service looks
/// again soon, or stops looking.
pub const CHANGED: u8 = 2;
/// Service โ†’ Settings: a look is over (no body); `last()` says what it found.
pub const LOOKED: u8 = 0x81;

const CHOICE: &str = "system:/settings/updates";
const LAST: &str = "system:/settings/updates-last";

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Choice {
    /// Nothing is looked for.
    Off,
    /// Looked for, and told in a notification.
    Tell,
    /// Looked for, and installed by itself when it asks for no more rights.
    Install,
}

impl Choice {
    pub fn read() -> Choice {
        match fs::read_string(CHOICE).as_deref().map(str::trim) {
            Some("off") => Choice::Off,
            Some("install") => Choice::Install,
            _ => Choice::Tell,
        }
    }

    pub fn write(self) {
        let word = match self {
            Choice::Off => "off",
            Choice::Tell => "tell",
            Choice::Install => "install",
        };
        fs::create_dir("system:/settings");
        fs::write(CHOICE, word.as_bytes());
    }
}

/// What the last look found: when (`HH:MM`), and a line saying what.
pub fn last() -> Option<(String, String)> {
    let text = fs::read_string(LAST)?;
    let (at, what) = text.split_once('\n')?;
    Some((at.into(), what.trim().into()))
}

/// Kept by the service after each look.
pub fn set_last(at: &str, what: &str) {
    fs::write(LAST, alloc::format!("{at}\n{what}\n").as_bytes());
}

/// A connection to the service, if it runs.
pub fn connect() -> Option<Channel> {
    pinnacle_rt::connect(SERVICE)
}

/// Asks the service to look now and waits up to `wait` ms for the look to
/// end. Whether it ended.
pub fn look_now(wait: u64) -> bool {
    let Some(service) = connect() else {
        return false;
    };
    service.send(&[LOOK], Vec::new());
    let mut buffer = [0u8; 16];
    let deadline = pinnacle_rt::time() + wait;
    loop {
        match pinnacle_rt::receive(&[&service], &mut buffer, Some(deadline)) {
            pinnacle_rt::Received::Message { len, .. } if len > 0 && buffer[0] == LOOKED => return true,
            pinnacle_rt::Received::Message { .. } => continue,
            _ => return false,
        }
    }
}

/// Tells the service the choice changed.
pub fn changed() {
    if let Some(service) = connect() {
        service.send(&[CHANGED], Vec::new());
    }
}

// The system: which runs, a newer one from the package sources, and the
// boot record (`pinnacle_pkg::system`).

/// The system that runs.
pub struct Running {
    pub version: String,
    pub board: String,
    /// None: the boot kernel's own.
    pub slot: Option<Slot>,
}

impl Running {
    pub fn now() -> Running {
        let text = pinnacle_rt::system();
        let field = |key: &str| String::from(fs::field(&text, key).unwrap_or("").trim());
        Running {
            version: field("version"),
            board: field("board"),
            slot: Slot::parse(&field("slot")),
        }
    }
}

const SYSTEM_KEYS: &str = "system:/settings/system-keys";
/// The slot whose files are in their places, and its version: `a 412`.
const APPLIED: &str = "system:/system/applied";

fn record_path() -> String {
    alloc::format!("system:{}", system::RECORD)
}

pub fn record() -> Record {
    Record::parse(&fs::read_string(&record_path()).unwrap_or_default())
}

pub fn write_record(record: &Record) -> bool {
    fs::create_dir("system:/system");
    fs::write(&record_path(), record.text().as_bytes())
}

/// What a slot's package says, signed by a key the system trusts for
/// systems: its manifest and its list of files.
fn slot_package(slot: Slot) -> Option<(String, String)> {
    let package = fs::read(&alloc::format!("system:{}/package", slot.folder()))?;
    let keys = fs::read_string(SYSTEM_KEYS).unwrap_or_default();
    let entries = pinnacle_pkg::open(&package, &pinnacle_pkg::parse_keys(&keys)).ok()?;
    let entry = |want: &str| {
        entries
            .iter()
            .find(|(n, _)| *n == want)
            .and_then(|(_, d)| core::str::from_utf8(d).ok())
            .map(String::from)
    };
    Some((entry("manifest")?, entry("files")?))
}

/// The version of the system kept in `slot`, if one is.
pub fn slot_version(slot: Slot) -> Option<String> {
    let (manifest, _) = slot_package(slot)?;
    Some(fs::field(&manifest, "version")?.trim().into())
}

/// At the display server's start, once its first screen shows: the system
/// tried has started well, and runs from now on. Its version, when it was
/// being tried.
pub fn confirm_start() -> Option<String> {
    let running = Running::now();
    let after = record().started(running.slot?)?;
    write_record(&after).then_some(running.version)
}

/// A newer system than the one running, from a package source: its source
/// (`<source>system/<board>/`), version and size.
pub struct SystemOffer {
    pub source: String,
    pub version: String,
    pub size: u64,
}

/// The newest system a package source offers for this board, if it is
/// newer than the one running.
pub fn system_offer(running: &Running) -> Option<SystemOffer> {
    let mut best: Option<SystemOffer> = None;
    for source in crate::store::sources() {
        let at = alloc::format!("{source}system/{}/", running.board);
        let Ok(body) = pinnacle_rt::net::http_get(&alloc::format!("{at}catalog"), 8000) else {
            continue;
        };
        let text = String::from_utf8_lossy(&body);
        for line in text.lines() {
            let mut f = line.split('|');
            if f.next() != Some("system") {
                continue;
            }
            let (Some(version), Some(size)) = (f.nth(1), f.next().and_then(|s| s.parse().ok())) else {
                continue;
            };
            let newest = best
                .as_ref()
                .map_or(running.version.as_str(), |b| b.version.as_str());
            if system::newer(version, newest) {
                best = Some(SystemOffer {
                    source: at.clone(),
                    version: version.into(),
                    size,
                });
            }
        }
    }
    best
}

/// The newer system the last look found and did not fetch, kept for
/// Settings' Install.
const OFFERED: &str = "system:/settings/updates-offered";

/// The version the last look found to install, if it is still newer than
/// the system that runs and is not waiting for the next start.
pub fn offered() -> Option<String> {
    let version = String::from(fs::read_string(OFFERED)?.trim());
    let newer = system::newer(&version, &Running::now().version);
    let failed = failed_version().is_some_and(|v| v == version);
    (newer && !failed && waiting().is_none_or(|(_, v)| v != version)).then_some(version)
}

pub fn set_offered(version: Option<&str>) {
    match version {
        Some(v) => fs::write(OFFERED, v.as_bytes()),
        None => fs::remove(OFFERED),
    };
}

/// The version of the system whose try did not start, while it is kept.
pub fn failed_version() -> Option<String> {
    slot_version(record().failed?)
}

/// The system waiting for the next start: its slot and version.
pub fn waiting() -> Option<(Slot, String)> {
    let record = record();
    let slot = record.next.filter(|_| !record.tried)?;
    Some((slot, slot_version(slot)?))
}

/// Fetches `offer` into the slot that is free (`Record::free`), each file
/// checked against the package's list as the Store checks an app's, and
/// sets it to be tried at the next start. Its slot.
pub fn fetch_system(offer: &SystemOffer, progress: &mut dyn FnMut(u64, u64)) -> Result<Slot, &'static str> {
    let running = Running::now();
    let mut record = record();
    let slot = record.free(running.slot);
    let url = alloc::format!("{}packages/system.ppk", offer.source);
    let package = pinnacle_rt::net::http_get(&url, 20_000).map_err(|_| "the package could not be fetched")?;
    let keys = fs::read_string(SYSTEM_KEYS).unwrap_or_default();
    let entries = pinnacle_pkg::open(&package, &pinnacle_pkg::parse_keys(&keys))
        .map_err(pinnacle_pkg::Error::describe)?;
    let entry = |want: &str| {
        entries
            .iter()
            .find(|(n, _)| *n == want)
            .and_then(|(_, d)| core::str::from_utf8(d).ok())
    };
    let manifest = entry("manifest").ok_or("it has no manifest")?;
    let listed = entry("files").ok_or("it lists no files")?;
    if fs::field(manifest, "board").map(str::trim) != Some(running.board.as_str()) {
        return Err("it is for another board");
    }
    if fs::field(manifest, "version").map(str::trim) != Some(offer.version.as_str()) {
        return Err("its version is not the one offered");
    }
    let files = pinnacle_pkg::files(listed).ok_or("its list of files is not one")?;
    if !files.iter().any(|f| f.path == "kernel") || files.iter().any(|f| f.path == "package") {
        return Err("it is not a system");
    }
    // The slot is not tried while it changes: the record forgets it first,
    // and its package, which the boot kernel checks, comes last.
    if record.next == Some(slot) {
        record.next = None;
        record.tried = false;
        if !write_record(&record) {
            return Err("the disk is full");
        }
    }
    let dir = alloc::format!("system:{}", slot.folder());
    let before = slot_package(slot).map(|(_, files)| files).unwrap_or_default();
    let before = pinnacle_pkg::files(&before).unwrap_or_default();
    fs::remove(&alloc::format!("{dir}/package"));
    fs::create_dir("system:/system");
    fs::create_dir(&dir);
    let kept = |file: &pinnacle_pkg::File| {
        before.contains(file)
            && fs::stat(&alloc::format!("{dir}/{}", file.path)).is_some_and(|s| s.size == file.size)
    };
    let needed: u64 = files.iter().filter(|f| !kept(f)).map(|f| f.size).sum();
    if let Some((_, free)) = fs::disk("system")
        && needed > free
    {
        return Err("there is not enough room on the disk");
    }
    let total: u64 = files.iter().map(|f| f.size).sum();
    let mut done = 0;
    let mut folders: Vec<&str> = Vec::new();
    for file in &files {
        if !kept(file) {
            for (i, _) in file.path.match_indices('/') {
                let folder = &file.path[..i];
                if !folders.contains(&folder) {
                    fs::create_dir(&alloc::format!("{dir}/{folder}"));
                    folders.push(folder);
                }
            }
            let url = alloc::format!("{}blobs/{}", offer.source, file.blob());
            crate::store::fetch(&url, &alloc::format!("{dir}/{}", file.path), file, &mut |n| {
                progress(done + n, total)
            })?;
        }
        done += file.size;
        progress(done, total);
    }
    for old in &before {
        if !files.iter().any(|f| f.path == old.path) {
            fs::remove(&alloc::format!("{dir}/{}", old.path));
        }
    }
    if !fs::write(&alloc::format!("{dir}/package"), &package) {
        return Err("the disk is full");
    }
    record.next = Some(slot);
    record.tried = false;
    record.failed = None;
    if !write_record(&record) {
        return Err("the disk is full");
    }
    Ok(slot)
}

/// Sets the system kept in the slot that does not run to be tried at the
/// next start: going back to it. Its version, if there is one there.
pub fn go_back() -> Option<String> {
    let running = Running::now();
    let other = running.slot?.other();
    let version = slot_version(other)?;
    let mut record = record();
    record.next = Some(other);
    record.tried = false;
    record.failed = None;
    write_record(&record).then_some(version)
}

/// Puts the files that come with the system that runs (the apps it comes
/// with, its fonts, the certificates' roots: all but its kernel) in their
/// places, once a slot's system runs well and they are not yet. How many
/// it put there, when it did.
pub fn apply_files() -> Option<usize> {
    let running = Running::now();
    let slot = running.slot?;
    if record().current != Some(slot) {
        return None;
    }
    let stamp = alloc::format!("{} {}", slot.name(), running.version);
    if fs::read_string(APPLIED).as_deref().map(str::trim) == Some(stamp.as_str()) {
        return None;
    }
    let (_, listed) = slot_package(slot)?;
    let files = pinnacle_pkg::files(&listed)?;
    let mut put = 0;
    for file in files.iter().filter(|f| f.path != "kernel") {
        let from = alloc::format!("system:{}/{}", slot.folder(), file.path);
        let to = alloc::format!("system:/{}", file.path);
        let Some(bytes) = fs::read(&from) else { continue };
        let mut at = 0;
        while let Some(i) = file.path[at..].find('/') {
            fs::create_dir(&alloc::format!("system:/{}", &file.path[..at + i]));
            at += i + 1;
        }
        if fs::read(&to).as_deref() != Some(bytes.as_slice()) && fs::write(&to, &bytes) {
            put += 1;
        }
    }
    fs::write(APPLIED, stamp.as_bytes());
    Some(put)
}

/// Restarts the device.
pub fn restart() {
    pinnacle_rt::restart();
}