Files
os/crates/sf-update/src/store.rs
Tamas Csikel d5be90443d Package-based updates: sf-update, signed shell and app packages
- sf-update (root): lists sf-shell / sf-app-* in the Gitea generic registry,
  downloads, checks the Ed25519 signature and unpacks to /var/lib/sf-pkg,
  switches via current/previous/staged symlinks; the factory copies on the
  read-only root stay as fallback. A new shell is on trial and rolls back
  after 3 failed starts.
- Launcher: apps from factory + installed packages (newer version wins),
  Settings > System > Updates (check, install now), shell trial confirm.
- Image: sf-update units (boot apply, 6-hourly download, launcher requests),
  sf-shell-exec wrapper for sf-remote, factory versions, registry token.
- CI: .gitea/workflows/packages.yml builds, signs and uploads packages whose
  version isn't published yet (tools/pkg/packages.sh).
- docs/updates.md: protocol and layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:27:59 +02:00

364 lines
14 KiB
Rust

//! Installed packages on the data partition (root-owned, default /var/lib/sf-pkg):
//!
//! <name>/<version>/ unpacked package
//! <name>/current -> <version> the live copy (none: factory copy)
//! <name>/previous -> <version> for rollback
//! <name>/staged -> <version> downloaded, goes live at the next apply
//! <name>/bad versions that failed, never installed again
//! sf-shell/trial a new shell that hasn't confirmed a good start yet
//! apps/<id> -> ../sf-app-<id>/current (the launcher reads this folder)
//! status.json for the launcher's Updates row
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use ed25519_dalek::{Signature, VerifyingKey};
use serde::{Deserialize, Serialize};
use sf_ipc::manifest::version_cmp;
use crate::config::Config;
use crate::registry;
pub const SHELL: &str = "sf-shell";
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Status {
/// idle | checking | downloading | installing | error
pub state: String,
pub message: String,
/// Unix time of the last successful check (0: never).
pub checked_at: u64,
pub packages: Vec<PackageStatus>,
/// Shell version on trial (installed, not yet confirmed by the launcher).
pub shell_trial: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackageStatus {
pub name: String,
/// What runs now: the installed package or the factory copy, whichever is newer.
pub installed: String,
/// Newest version on the server (from the last check).
pub available: Option<String>,
/// Downloaded, goes live at the next boot.
pub staged: Option<String>,
}
pub struct Pending {
pub name: String,
pub version: String,
}
#[derive(Debug, Default)]
pub struct Applied {
pub shell: bool,
pub apps: bool,
}
#[derive(Deserialize)]
struct PkgInfo {
name: String,
version: String,
}
#[cfg(unix)]
fn symlink(target: impl AsRef<Path>, link: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(target, link)
}
/// The updater only runs on the TV; elsewhere it builds but can't install.
#[cfg(not(unix))]
fn symlink(_target: impl AsRef<Path>, _link: &Path) -> std::io::Result<()> {
Err(std::io::Error::other("symlinks need Linux"))
}
pub struct Store {
root: PathBuf,
factory: BTreeMap<String, String>,
}
pub struct Lock(#[allow(dead_code)] fs::File);
impl Store {
pub fn open(cfg: &Config) -> Result<Self> {
fs::create_dir_all(&cfg.root).with_context(|| format!("creating {}", cfg.root.display()))?;
let factory = match fs::read_to_string(&cfg.factory) {
Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", cfg.factory.display()))?,
Err(_) => BTreeMap::new(),
};
Ok(Store { root: cfg.root.clone(), factory })
}
pub fn lock(&self, wait: Duration) -> Result<Lock> {
let f = fs::OpenOptions::new().create(true).truncate(false).write(true).open(self.root.join(".lock"))?;
let start = Instant::now();
loop {
match f.try_lock() {
Ok(()) => return Ok(Lock(f)),
Err(fs::TryLockError::WouldBlock) if start.elapsed() < wait => std::thread::sleep(Duration::from_millis(500)),
Err(fs::TryLockError::WouldBlock) => bail!("another sf-update is still running"),
Err(fs::TryLockError::Error(e)) => return Err(e.into()),
}
}
}
fn dir(&self, name: &str) -> PathBuf {
self.root.join(name)
}
fn link(&self, name: &str, which: &str) -> Option<String> {
let target = fs::read_link(self.dir(name).join(which)).ok()?;
let v = target.file_name()?.to_str()?.to_string();
self.dir(name).join(&v).is_dir().then_some(v)
}
/// Points `<name>/<which>` at `<version>` (atomically, via rename).
fn set_link(&self, name: &str, which: &str, version: &str) -> Result<()> {
let dir = self.dir(name);
let tmp = dir.join(format!(".{which}.tmp"));
let _ = fs::remove_file(&tmp);
symlink(version, &tmp)?;
fs::rename(&tmp, dir.join(which))?;
Ok(())
}
fn remove_link(&self, name: &str, which: &str) {
let _ = fs::remove_file(self.dir(name).join(which));
}
pub fn staged(&self, name: &str) -> Option<String> {
self.link(name, "staged")
}
/// The version running now: installed package or factory copy, the newer one.
fn installed(&self, name: &str) -> Option<String> {
let current = self.link(name, "current");
let factory = self.factory.get(name).cloned();
match (current, factory) {
(Some(c), Some(f)) => Some(if version_cmp(&c, &f).is_ge() { c } else { f }),
(c, f) => c.or(f),
}
}
fn bad(&self, name: &str) -> BTreeSet<String> {
fs::read_to_string(self.dir(name).join("bad")).unwrap_or_default().lines().map(str::to_string).collect()
}
/// Names of all packages: on the server, installed or built in.
fn names(&self, latest: &BTreeMap<String, String>) -> BTreeSet<String> {
let mut names: BTreeSet<String> = latest.keys().cloned().collect();
names.extend(self.factory.keys().cloned());
if let Ok(entries) = fs::read_dir(&self.root) {
names.extend(entries.flatten().filter_map(|e| e.file_name().into_string().ok()).filter(|n| registry::is_ours(n)));
}
names
}
/// Records the server's versions; returns the packages that need an update.
pub fn refresh(&self, latest: &BTreeMap<String, String>) -> Vec<Pending> {
let mut pending = Vec::new();
for name in self.names(latest) {
let Some(v) = latest.get(&name) else { continue };
let newer = self.installed(&name).is_none_or(|i| version_cmp(v, &i).is_gt());
if newer && !self.bad(&name).contains(v) {
pending.push(Pending { name: name.clone(), version: v.clone() });
}
}
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
self.write_status(|s| {
s.checked_at = now;
s.packages = self
.names(latest)
.into_iter()
.map(|name| PackageStatus { available: latest.get(&name).cloned(), installed: String::new(), staged: None, name })
.collect();
});
pending
}
pub fn download_dir_path(&self) -> PathBuf {
self.root.join(".download")
}
pub fn download_dir(&self) -> Result<PathBuf> {
let d = self.download_dir_path();
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d)?;
Ok(d)
}
/// Checks the signature and unpacks into `<name>/<version>/`.
pub fn verify_and_unpack(&self, cfg: &Config, name: &str, version: &str, pkg: &Path, sig: &[u8]) -> Result<()> {
let data = fs::read(pkg)?;
let key = VerifyingKey::from_bytes(&cfg.public_key).context("public key")?;
let sig = Signature::from_slice(sig).context("signature: not 64 bytes")?;
key.verify_strict(&data, &sig).context("bad signature")?;
let dir = self.dir(name);
fs::create_dir_all(&dir)?;
let dest = dir.join(version);
if dest.is_dir() {
if self.link(name, "current").as_deref() == Some(version) || self.link(name, "previous").as_deref() == Some(version) {
return Ok(());
}
fs::remove_dir_all(&dest)?;
}
let tmp = dir.join(format!(".tmp-{version}"));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp)?;
let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?;
let mut archive = tar::Archive::new(decoder);
archive.set_preserve_permissions(true);
archive.set_preserve_ownerships(false);
archive.unpack(&tmp).context("unpacking")?;
let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?;
if info.name != name || info.version != version {
let _ = fs::remove_dir_all(&tmp);
bail!("package says it is {} {}, expected {name} {version}", info.name, info.version);
}
fs::rename(&tmp, &dest)?;
Ok(())
}
pub fn stage(&self, name: &str, version: &str) -> Result<()> {
self.set_link(name, "staged", version)
}
/// Makes every staged package live.
pub fn apply_staged(&self) -> Result<Applied> {
let mut applied = Applied::default();
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(applied) };
for e in entries.flatten() {
let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue };
let Some(v) = self.staged(&name) else { continue };
if self.link(&name, "current").as_deref() != Some(v.as_str()) {
if let Some(cur) = self.link(&name, "current") {
self.set_link(&name, "previous", &cur)?;
}
self.set_link(&name, "current", &v)?;
log::info!("{name} {v} is live");
if name == SHELL {
fs::write(self.dir(&name).join("trial"), &v)?;
applied.shell = true;
} else {
applied.apps = true;
}
}
self.remove_link(&name, "staged");
}
self.link_apps()?;
Ok(applied)
}
/// apps/<id> -> ../sf-app-<id>/current for every installed app.
fn link_apps(&self) -> Result<()> {
let apps = self.root.join("apps");
fs::create_dir_all(&apps)?;
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(()) };
for e in entries.flatten() {
let Some(name) = e.file_name().into_string().ok() else { continue };
let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_ours(&name)) else { continue };
let link = apps.join(id);
if self.link(&name, "current").is_some() && fs::symlink_metadata(&link).is_err() {
symlink(format!("../{name}/current"), &link)?;
}
}
Ok(())
}
/// The launcher started fine on the new shell.
pub fn confirm_shell(&self) -> Result<()> {
if fs::remove_file(self.dir(SHELL).join("trial")).is_ok() {
log::info!("shell {} confirmed", self.link(SHELL, "current").unwrap_or_default());
}
self.write_status(|_| {});
Ok(())
}
/// The new shell keeps failing: back to the previous one (or the factory
/// copy) and never install this version again. True if anything changed.
pub fn rollback_shell(&self) -> Result<bool> {
let trial = self.dir(SHELL).join("trial");
if !trial.exists() {
return Ok(false);
}
if let Some(bad) = self.link(SHELL, "current") {
log::warn!("shell {bad} failed to start, rolling back");
let mut list = self.bad(SHELL);
list.insert(bad);
fs::write(self.dir(SHELL).join("bad"), list.into_iter().collect::<Vec<_>>().join("\n") + "\n")?;
}
match self.link(SHELL, "previous") {
Some(prev) => {
self.set_link(SHELL, "current", &prev)?;
self.remove_link(SHELL, "previous");
}
None => self.remove_link(SHELL, "current"),
}
fs::remove_file(&trial)?;
self.gc();
self.write_status(|_| {});
Ok(true)
}
/// Removes versions nothing points at, and leftovers of failed unpacks.
pub fn gc(&self) {
let Ok(entries) = fs::read_dir(&self.root) else { return };
for e in entries.flatten() {
let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue };
let keep: BTreeSet<String> = ["current", "previous", "staged"].iter().filter_map(|w| self.link(&name, w)).collect();
let Ok(versions) = fs::read_dir(e.path()) else { continue };
for v in versions.flatten() {
let file = v.file_name().to_string_lossy().to_string();
let is_version = registry::is_release(&file) && v.path().is_dir() && !v.path().is_symlink();
if (is_version && !keep.contains(&file)) || file.starts_with(".tmp-") {
log::info!("removing {name}/{file}");
let _ = fs::remove_dir_all(v.path());
}
}
}
}
pub fn read_status(&self) -> Status {
fs::read_to_string(self.root.join("status.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
/// Updates status.json; installed/staged are always re-read from disk.
pub fn write_status(&self, f: impl FnOnce(&mut Status)) {
let mut s = self.read_status();
if s.state.is_empty() {
s.state = "idle".into();
}
f(&mut s);
let mut names: BTreeSet<String> = s.packages.iter().map(|p| p.name.clone()).collect();
names.extend(self.names(&BTreeMap::new()));
let old: BTreeMap<String, Option<String>> = s.packages.iter().map(|p| (p.name.clone(), p.available.clone())).collect();
s.packages = names
.into_iter()
.map(|name| PackageStatus {
installed: self.installed(&name).unwrap_or_default(),
available: old.get(&name).cloned().flatten(),
staged: self.staged(&name),
name,
})
.collect();
s.shell_trial = fs::read_to_string(self.dir(SHELL).join("trial")).ok().map(|t| t.trim().to_string());
let tmp = self.root.join(".status.json.tmp");
let ok = serde_json::to_vec_pretty(&s).ok().and_then(|data| fs::write(&tmp, data).ok()).and_then(|_| fs::rename(&tmp, self.root.join("status.json")).ok());
if ok.is_none() {
log::warn!("could not write status.json");
}
}
pub fn set_state(&self, state: &str, message: &str) {
self.write_status(|s| {
s.state = state.into();
s.message = message.into();
});
}
}