//! Installed packages on the data partition (root-owned, default /var/lib/sf-pkg): //! //! // unpacked package //! /current -> the live copy (none: factory copy) //! /previous -> for rollback //! /staged -> downloaded, goes live at the next apply //! /bad versions that failed, never installed again //! sf-shell/trial a new shell that hasn't confirmed a good start yet //! apps/ -> ../sf-app-/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, /// Shell version on trial (installed, not yet confirmed by the launcher). pub shell_trial: Option, } #[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, /// Downloaded, goes live at the next boot. pub staged: Option, } 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, 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, _link: &Path) -> std::io::Result<()> { Err(std::io::Error::other("symlinks need Linux")) } pub struct Store { root: PathBuf, factory: BTreeMap, } pub struct Lock(#[allow(dead_code)] fs::File); impl Store { pub fn open(cfg: &Config) -> Result { 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 { 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 { 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 `/` at `` (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 { self.link(name, "staged") } /// The version running now: installed package or factory copy, the newer one. fn installed(&self, name: &str) -> Option { 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 { 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) -> BTreeSet { let mut names: BTreeSet = 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) -> Vec { 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 { 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 `//`. 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 { 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/ -> ../sf-app-/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 { 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::>().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 = ["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 = s.packages.iter().map(|p| p.name.clone()).collect(); names.extend(self.names(&BTreeMap::new())); let old: BTreeMap> = 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(); }); } }