garage44.eu/jeroen/pinnacle

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

.. /ui/src/store.rs

raw

//! What the Store and the updates service share: the package sources, their
//! catalogs (`<source>catalog`), and installing an app or bringing it to
//! another version (`<source>packages/<name>.ppk`, `<source>blobs/<sha256>`).
//! Installing checks the package's signature against the publishers the
//! system trusts ([`trust`], `pinnacle_pkg::trust`) and refuses one nobody
//! trusted signed, or one from another publisher than the app installed
//! (`/apps/<name>/publisher`); then it fetches the files the package lists, each
//! checked against its SHA-256 as it is written into `/apps/<name>/` on the
//! system disk, where the launcher and `spawn` find it. Uninstalling
//! ([`uninstall`]) removes that folder, and the app's data when asked.
//!
//! The sources: `/settings/store-url` (the one a development system's
//! `cargo xtask` serves), then each line of `/settings/store-sources` (the
//! hosted ones, `https://pinnacle-os.eu/store/<publisher>/`). One that does
//! not answer is left out; an app offered twice comes from the first.

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

use pinnacle_rt::fs;

pub struct Offer {
    /// The package source it comes from.
    pub source: String,
    pub name: String,
    pub title: String,
    pub version: String,
    pub description: String,
    /// Of its files, all told: what installing it fetches at most.
    pub size: u64,
    /// What it may do beyond its own folder, as the catalog says: shown
    /// before it is installed, and what its signed manifest must not exceed.
    pub rights: pinnacle_pkg::Rights,
}

/// Where packages come from: `system:/settings/store-url` (else QEMU's host
/// as seen from the guest), then `system:/settings/store-sources`, a URL a
/// line.
pub fn sources() -> Vec<String> {
    let first = fs::read_string("system:/settings/store-url")
        .map(|s| String::from(s.trim()))
        .unwrap_or_else(|| "http://10.0.2.2:8080/".into());
    let more = fs::read_string("system:/settings/store-sources").unwrap_or_default();
    let mut out = alloc::vec![first];
    for line in more.lines().map(str::trim) {
        if !line.is_empty() && !line.starts_with('#') && !out.iter().any(|s| s == line) {
            out.push(line.into());
        }
    }
    out
}

/// The catalogs: a line per package, `name|title|version|size|description`
/// and its rights (`pinnacle_pkg::Rights`), none when left out. None when
/// no source answered.
pub fn catalog() -> Option<Vec<Offer>> {
    let mut offers: Vec<Offer> = Vec::new();
    let mut answered = false;
    for source in sources() {
        let Ok(body) = pinnacle_rt::net::http_get(&alloc::format!("{source}catalog"), 8000) else {
            continue;
        };
        answered = true;
        take_registry(&source);
        let Ok(text) = String::from_utf8(body) else {
            continue;
        };
        for line in text.lines() {
            let mut f = line.split('|');
            let offer = (|| {
                Some(Offer {
                    source: source.clone(),
                    name: f.next()?.into(),
                    title: f.next()?.into(),
                    version: f.next()?.into(),
                    size: f.next()?.parse().ok()?,
                    description: f.next()?.into(),
                    rights: pinnacle_pkg::Rights::of_catalog(f.next().unwrap_or(""))?,
                })
            })();
            if let Some(offer) = offer
                && !offers.iter().any(|o| o.name == offer.name)
            {
                offers.push(offer);
            }
        }
    }
    answered.then_some(offers)
}

/// The publishers whose packages install (`pinnacle_pkg::trust`): the keys
/// the system trusts itself (`/settings/trusted-keys`), those the registry
/// lists it keeps vouch for (`/settings/publishers-<registry>`, each
/// checked again here), less every key taken back
/// (`/settings/revoked-keys`).
pub fn trust() -> pinnacle_pkg::trust::Trust {
    use pinnacle_pkg::trust::{Registry, Trust};
    let read = |path: &str| fs::read_string(path).unwrap_or_default();
    let mut trust = Trust::parse(
        &read("system:/settings/trusted-keys"),
        &read("system:/settings/revoked-keys"),
    );
    let kept = fs::list("system:/settings").unwrap_or_default();
    for name in kept.iter().filter(|n| n.starts_with("publishers-")) {
        if let Some(list) = fs::read(&alloc::format!("system:/settings/{name}"))
            && let Ok(registry) = Registry::open(&list, &trust)
        {
            trust.admit(&registry);
        }
    }
    trust
}

/// A source's registry list (`packages/publishers.ppk`), when it has one a
/// registry key signed and it is newer than the one kept: kept, and the
/// keys it takes back added to those taken back for good.
fn take_registry(source: &str) {
    use pinnacle_pkg::trust::Registry;
    let Ok(list) = pinnacle_rt::net::http_get(&alloc::format!("{source}packages/publishers.ppk"), 8000)
    else {
        return;
    };
    let mut trust = trust();
    let Ok(registry) = Registry::open(&list, &trust) else {
        return;
    };
    let path = alloc::format!("system:/settings/publishers-{}", registry.publisher);
    let kept = fs::read(&path).and_then(|old| Registry::open(&old, &trust).ok());
    if kept.is_some_and(|old| old.issued >= registry.issued) {
        return;
    }
    trust.admit(&registry);
    fs::write(&path, &list);
    fs::write("system:/settings/revoked-keys", trust.revoked_text().as_bytes());
}

/// The manifest of the app installed as `name`, if one is.
fn manifest(name: &str) -> Option<String> {
    fs::read_string(&alloc::format!("system:/apps/{name}/manifest"))
}

/// The version of the app installed as `name`, if one is.
pub fn installed(name: &str) -> Option<String> {
    Some(fs::field(&manifest(name)?, "version").unwrap_or("").trim().into())
}

/// What the app installed as `name` may do now, if one is.
pub fn installed_rights(name: &str) -> Option<pinnacle_pkg::Rights> {
    pinnacle_pkg::Rights::of_manifest(&manifest(name)?)
}

/// An app installed from a package source, as its manifest says.
pub struct Installed {
    pub name: String,
    pub title: String,
    pub version: String,
    pub description: String,
}

/// Whether the app installed as `name` came from a package source, and so
/// may be uninstalled: such an app keeps the list of its files
/// (`/apps/<name>/files`), which an app the system comes with has not.
pub fn removable(name: &str) -> bool {
    let plain = !name.is_empty() && !name.contains('/') && name != "." && name != "..";
    plain && manifest(name).is_some() && fs::exists(&alloc::format!("system:/apps/{name}/files"))
}

/// The apps installed from package sources, by title.
pub fn removable_apps() -> Vec<Installed> {
    let mut apps: Vec<Installed> = fs::list("system:/apps")
        .unwrap_or_default()
        .iter()
        .filter_map(|entry| entry.strip_suffix('/'))
        .filter(|name| removable(name))
        .map(|name| {
            let text = manifest(name).unwrap_or_default();
            let field = |key: &str| String::from(fs::field(&text, key).unwrap_or("").trim());
            let title = field("title");
            Installed {
                name: name.into(),
                title: if title.is_empty() { name.into() } else { title },
                version: field("version"),
                description: field("description"),
            }
        })
        .collect();
    apps.sort_by(|a, b| a.title.cmp(&b.title));
    apps
}

/// The folders the app `name` keeps its data in, those that are there: its
/// own folder (`app:`) in the vault once it is open, and on the system disk
/// from before the vault was (as the kernel's `app_folder` has them).
pub fn data_folders(name: &str) -> Vec<String> {
    [
        alloc::format!("data:/apps/{name}"),
        alloc::format!("system:/data/{name}"),
    ]
    .into_iter()
    .filter(|path| fs::list(path).is_some())
    .collect()
}

/// What the app `name` keeps in its data folders, in bytes.
pub fn data_size(name: &str) -> u64 {
    fn walk(path: &str) -> u64 {
        fs::list(path)
            .unwrap_or_default()
            .iter()
            .map(|entry| {
                let at = alloc::format!("{path}/{}", entry.trim_end_matches('/'));
                if entry.ends_with('/') {
                    walk(&at)
                } else {
                    fs::stat(&at).map_or(0, |s| s.size)
                }
            })
            .sum()
    }
    data_folders(name).iter().map(|f| walk(f)).sum()
}

/// Uninstalls the app installed as `name` from a package source: its
/// manifest first, so that it is off the home screen and no app at once
/// (the launcher's tiles are the folders with one), then its folder on the
/// system disk; with `data` its data folders too, else they stay, for Files
/// to show and a later install of it to find. The caller makes sure it is
/// not running. Refused for an app the system comes with.
pub fn uninstall(name: &str, data: bool) -> Result<(), &'static str> {
    if !removable(name) {
        return Err("it came with the system, or is not installed");
    }
    let dir = alloc::format!("system:/apps/{name}");
    if !fs::remove(&alloc::format!("{dir}/manifest")) || !fs::remove(&dir) {
        return Err("its files could not all be removed");
    }
    // What could not be removed of its data stays, as `data_folders` says.
    if data {
        for folder in data_folders(name) {
            fs::remove(&folder);
        }
    }
    Ok(())
}

/// What the Store does when its button is tapped.
#[derive(Clone, Copy, PartialEq)]
pub enum Action {
    Install,
    Update,
    Open,
}

pub fn action(offer: &Offer) -> Action {
    match installed(&offer.name) {
        None => Action::Install,
        Some(version) if version != offer.version => Action::Update,
        Some(_) => Action::Open,
    }
}

/// Installs `offer` (or brings it to the offered version), telling
/// `progress` how many of how many bytes it has.
pub fn install(offer: &Offer, progress: &mut dyn FnMut(u64, u64)) -> Result<(), &'static str> {
    let (source, name) = (&offer.source, &offer.name);
    let url = alloc::format!("{source}packages/{name}.ppk");
    let package = pinnacle_rt::net::http_get(&url, 20_000).map_err(|_| "the package could not be fetched")?;
    // Only what a publisher the system trusts signed is installed, and an
    // app installed already only from the publisher it came from.
    let trust = trust();
    let (entries, publisher) = trust.open(&package).map_err(pinnacle_pkg::Error::describe)?;
    let dir = alloc::format!("system:/apps/{name}");
    let installed_from = fs::read_string(&alloc::format!("{dir}/publisher"));
    if manifest(name).is_some()
        && !pinnacle_pkg::trust::may_replace(installed_from.as_deref().map(str::trim), publisher)
    {
        return Err("it is from another publisher than the app installed");
    }
    let entry = |want: &str| {
        entries
            .iter()
            .find(|(n, _)| *n == want)
            .and_then(|(_, data)| core::str::from_utf8(data).ok())
    };
    let manifest = entry("manifest").ok_or("it has no manifest")?;
    let listed = entry("files").ok_or("it lists no files")?;
    // What the person saw before tapping Install is all it gets.
    let rights = pinnacle_pkg::Rights::of_manifest(manifest).ok_or("its manifest is not one")?;
    if !rights.within(offer.rights) {
        return Err("it asks for more than the Store showed");
    }
    let files = pinnacle_pkg::files(listed).ok_or("its list of files is not one")?;
    // What an earlier version left: a file with the same hash is kept.
    let before_text = fs::read_string(&alloc::format!("{dir}/files")).unwrap_or_default();
    let before = pinnacle_pkg::files(&before_text).unwrap_or_default();
    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 total: u64 = files.iter().map(|f| f.size).sum();
    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");
    }
    // Not an app while its files change: the manifest goes first, and
    // comes back last.
    fs::remove(&alloc::format!("{dir}/manifest"));
    if !fs::create_dir(&dir) && !fs::exists(&dir) {
        return Err("could not make the app's folder");
    }
    let mut done = 0;
    progress(done, total);
    let mut folders: Vec<&str> = Vec::new();
    for file in &files {
        if kept(file) {
            done += file.size;
            progress(done, total);
            continue;
        }
        // Its folders, each made once.
        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!("{source}blobs/{}", file.blob());
        fetch(&url, &alloc::format!("{dir}/{}", file.path), file, &mut |n| {
            progress(done + n, total)
        })?;
        done += file.size;
    }
    // What the version before had and this one does not.
    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}/files"), listed.as_bytes())
        || !fs::write(&alloc::format!("{dir}/publisher"), publisher.as_bytes())
        || !fs::write(&alloc::format!("{dir}/manifest"), manifest.as_bytes())
    {
        return Err("the disk is full");
    }
    Ok(())
}

/// Fetches `file` from `url` into `path`, a megabyte at a time, and checks
/// it is what the package listed: its size and its SHA-256. A file that is
/// not is removed.
pub fn fetch(
    url: &str,
    path: &str,
    file: &pinnacle_pkg::File,
    progress: &mut dyn FnMut(u64),
) -> Result<(), &'static str> {
    const CHUNK: usize = 1 << 20;
    // A stale or half-fetched one: writing over it would keep a longer tail.
    fs::remove(path);
    let mut hash = pinnacle_pkg::Sha256::new();
    let mut buffer: Vec<u8> = Vec::with_capacity(CHUNK);
    let mut written = 0u64;
    let mut failed = None;
    let head = pinnacle_rt::net::request("GET", url, &[], &[], 20_000, |piece| {
        if written + (buffer.len() + piece.len()) as u64 > file.size {
            failed = Some("a file of it is longer than its list says");
            return false;
        }
        hash.update(piece);
        buffer.extend_from_slice(piece);
        if buffer.len() >= CHUNK {
            if !fs::write_at(path, written, &buffer) {
                failed = Some("the disk is full");
                return false;
            }
            written += buffer.len() as u64;
            buffer.clear();
            progress(written);
        }
        true
    });
    let result = match (head, failed) {
        (_, Some(why)) => Err(why),
        (Ok(head), None) if head.status == 200 => {
            // The rest, or an empty file made.
            let stored = match (written, buffer.is_empty()) {
                (0, true) => fs::write(path, &[]),
                (_, true) => true,
                _ => fs::write_at(path, written, &buffer),
            };
            if !stored {
                Err("the disk is full")
            } else if written + buffer.len() as u64 != file.size || hash.finish() != file.sha256 {
                Err("a file of it is not what its package says")
            } else {
                progress(file.size);
                Ok(())
            }
        }
        _ => Err("a file of it could not be fetched"),
    };
    if result.is_err() {
        fs::remove(path);
    }
    result
}

/// A size as a person reads it.
pub fn size(bytes: u64) -> String {
    if bytes < 1 << 20 {
        alloc::format!("{} KB", bytes.div_ceil(1024))
    } else {
        alloc::format!("{} MB", bytes.div_ceil(1 << 20))
    }
}