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>
This commit is contained in:
@@ -23,6 +23,10 @@ pub struct AppManifest {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: AppKind,
|
||||
/// Package version (semver). Published as `sf-app-<id>` when it changes;
|
||||
/// the newer of a factory and an installed copy wins.
|
||||
#[serde(default = "default_version")]
|
||||
pub version: String,
|
||||
/// Short label above the title in the hero ("Saját app", "Castolás"...).
|
||||
#[serde(default)]
|
||||
pub category: String,
|
||||
@@ -50,6 +54,11 @@ pub struct AppManifest {
|
||||
pub web: WebOptions,
|
||||
#[serde(default)]
|
||||
pub dial: Option<DialOptions>,
|
||||
/// Background receiver (AirPlay, Miracast): sf-core keeps it running all
|
||||
/// the time and it shows its own window when something connects. The
|
||||
/// launcher tile only opens the details sheet.
|
||||
#[serde(default)]
|
||||
pub service: bool,
|
||||
/// Folder the manifest was loaded from (not serialized).
|
||||
#[serde(skip)]
|
||||
pub dir: PathBuf,
|
||||
@@ -74,6 +83,10 @@ pub struct DialOptions {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
fn default_version() -> String {
|
||||
"0.0.0".into()
|
||||
}
|
||||
|
||||
fn default_accent() -> String {
|
||||
"#ffffff".into()
|
||||
}
|
||||
@@ -99,10 +112,46 @@ pub fn load_apps(dir: &Path) -> Result<Vec<AppManifest>> {
|
||||
Err(e) => log::warn!("skipping {}: {e:#}", path.display()),
|
||||
}
|
||||
}
|
||||
apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name)));
|
||||
sort_apps(&mut apps);
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
/// Loads apps from several folders (factory apps, then installed packages).
|
||||
/// Missing folders are skipped; of two apps with the same id the higher
|
||||
/// `version` wins, on a tie the later folder.
|
||||
pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
|
||||
let mut apps: Vec<AppManifest> = Vec::new();
|
||||
let mut found = false;
|
||||
for dir in dirs {
|
||||
if !dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
found = true;
|
||||
for app in load_apps(dir)? {
|
||||
match apps.iter_mut().find(|a| a.id == app.id) {
|
||||
Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app,
|
||||
Some(_) => {}
|
||||
None => apps.push(app),
|
||||
}
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(found, "none of the app folders exist: {dirs:?}");
|
||||
sort_apps(&mut apps);
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
fn sort_apps(apps: &mut [AppManifest]) {
|
||||
apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name)));
|
||||
}
|
||||
|
||||
/// Compares dotted numeric versions ("1.10.0" > "1.9.2"); anything that
|
||||
/// isn't a number compares as 0.
|
||||
pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
(0..3).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
|
||||
fn load_one(path: &Path) -> Result<AppManifest> {
|
||||
let text = std::fs::read_to_string(path)?;
|
||||
let mut app: AppManifest = toml::from_str(&text)?;
|
||||
@@ -133,5 +182,14 @@ mod tests {
|
||||
let mut s = Settings::default();
|
||||
s.values.insert("netflex_server".into(), "http://10.0.0.5:7880".into());
|
||||
assert_eq!(app.resolved_url(&s).unwrap(), "http://10.0.0.5:7880/");
|
||||
assert_eq!(app.version, "0.0.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compares_versions() {
|
||||
use std::cmp::Ordering::*;
|
||||
assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater);
|
||||
assert_eq!(version_cmp("0.2", "0.2.0"), Equal);
|
||||
assert_eq!(version_cmp("0.1.9", "0.2.0"), Less);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,26 +31,31 @@ slint::include_modules!();
|
||||
const CROSSFADE: f32 = 0.35;
|
||||
|
||||
struct Options {
|
||||
apps_dir: PathBuf,
|
||||
/// Factory apps, then installed app packages (`--apps` may repeat).
|
||||
apps_dirs: Vec<PathBuf>,
|
||||
settings_path: PathBuf,
|
||||
fullscreen: bool,
|
||||
}
|
||||
|
||||
fn parse_args() -> Options {
|
||||
let mut apps_dir = None;
|
||||
let mut apps_dirs = Vec::new();
|
||||
let mut settings_path = None;
|
||||
let mut fullscreen = false;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--apps" => apps_dir = args.next().map(PathBuf::from),
|
||||
"--apps" => apps_dirs.extend(args.next().map(PathBuf::from)),
|
||||
"--settings" => settings_path = args.next().map(PathBuf::from),
|
||||
"--fullscreen" | "-f" => fullscreen = true,
|
||||
other => log::warn!("unknown argument {other}"),
|
||||
}
|
||||
}
|
||||
Options {
|
||||
apps_dir: apps_dir.or_else(find_apps_dir).unwrap_or_else(|| PathBuf::from("/usr/share/smartfox/apps")),
|
||||
apps_dirs: if apps_dirs.is_empty() {
|
||||
vec![find_apps_dir().unwrap_or_else(|| PathBuf::from("/usr/share/smartfox/apps"))]
|
||||
} else {
|
||||
apps_dirs
|
||||
},
|
||||
settings_path: settings_path.unwrap_or_else(default_settings_path),
|
||||
fullscreen,
|
||||
}
|
||||
@@ -311,8 +316,9 @@ fn main() -> Result<()> {
|
||||
}
|
||||
let data_dir = opts.settings_path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
|
||||
|
||||
let apps = sf_ipc::load_apps(&opts.apps_dir).with_context(|| format!("loading apps from {}", opts.apps_dir.display()))?;
|
||||
log::info!("{} apps from {}", apps.len(), opts.apps_dir.display());
|
||||
let apps = sf_ipc::manifest::load_apps_from(&opts.apps_dirs).with_context(|| format!("loading apps from {:?}", opts.apps_dirs))?;
|
||||
log::info!("{} apps from {:?}", apps.len(), opts.apps_dirs);
|
||||
system::confirm_shell_trial();
|
||||
|
||||
let ui = App::new()?;
|
||||
let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings)).collect();
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
|
||||
|
||||
use crate::system::{self, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, Wifi, WifiNetwork};
|
||||
use crate::system::{self, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, UpdateStatus, Wifi, WifiNetwork};
|
||||
use crate::power;
|
||||
use crate::{App, SettingRow, keyboard};
|
||||
|
||||
@@ -21,6 +21,7 @@ const DISPLAY: i32 = 0;
|
||||
const DEVICES: i32 = 1;
|
||||
const NETWORK: i32 = 2;
|
||||
const ENERGY: i32 = 3;
|
||||
const SYSTEM: i32 = 4;
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
enum Action {
|
||||
@@ -50,6 +51,9 @@ enum Action {
|
||||
SuspendAfter,
|
||||
PickSuspendAfter(u32),
|
||||
StandbyNow,
|
||||
Updates,
|
||||
UpdateCheck,
|
||||
UpdateInstall,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
@@ -64,6 +68,7 @@ enum Sub {
|
||||
RemoteDebug,
|
||||
PowerMode,
|
||||
SuspendAfter,
|
||||
Updates,
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
@@ -88,6 +93,9 @@ enum Loaded {
|
||||
Removed { name: String, result: Result<(), String>, then_pair: bool },
|
||||
RemoteDebug(RemoteDebug),
|
||||
RemoteDebugSet { on: bool, result: Result<(), String> },
|
||||
/// sf-update's status.json (None: it never ran).
|
||||
Updates(Option<UpdateStatus>),
|
||||
UpdateRequested { install: bool, result: Result<(), String> },
|
||||
}
|
||||
|
||||
struct State {
|
||||
@@ -105,6 +113,8 @@ struct State {
|
||||
info: Option<DeviceInfo>,
|
||||
/// Whether sshd runs (remote debugging); None until queried.
|
||||
remote_debug: Option<RemoteDebug>,
|
||||
/// Package updates; None until read, Some(None) if sf-update never ran.
|
||||
updates: Option<Option<UpdateStatus>>,
|
||||
remote_status: String,
|
||||
/// One-line feedback shown under the page title (e.g. "AirPods eltávolítva").
|
||||
notice: String,
|
||||
@@ -182,6 +192,7 @@ impl Screen {
|
||||
wifi_pending: None,
|
||||
info: None,
|
||||
remote_debug: None,
|
||||
updates: None,
|
||||
remote_status: String::new(),
|
||||
notice: String::new(),
|
||||
actions: Vec::new(),
|
||||
@@ -253,6 +264,7 @@ impl Screen {
|
||||
post(|| Loaded::Net(system::network()));
|
||||
post(|| Loaded::Wifi(wifi_result(system::wifi())));
|
||||
post(|| Loaded::RemoteDebug(system::remote_debug()));
|
||||
post(|| Loaded::Updates(system::update_status()));
|
||||
if self.state.borrow().info.is_none() {
|
||||
post(|| Loaded::Info(system::device_info()));
|
||||
}
|
||||
@@ -271,6 +283,10 @@ impl Screen {
|
||||
if sub == Sub::KeepMode {
|
||||
self.rebuild(None);
|
||||
}
|
||||
// The updater reports progress through a file: cheap to poll.
|
||||
if self.is_open() && category == SYSTEM && matches!(sub, Sub::None | Sub::Updates) && ticks % 2 == 0 {
|
||||
post(|| Loaded::Updates(system::update_status()));
|
||||
}
|
||||
if !self.is_open() || sub != Sub::None || ticks % 4 != 0 {
|
||||
return;
|
||||
}
|
||||
@@ -401,6 +417,21 @@ impl Screen {
|
||||
}
|
||||
}
|
||||
Loaded::Info(i) => self.state.borrow_mut().info = Some(i),
|
||||
Loaded::Updates(u) => self.state.borrow_mut().updates = Some(u),
|
||||
Loaded::UpdateRequested { install, result } => {
|
||||
self.state.borrow_mut().notice = match result {
|
||||
Ok(()) if install => "Telepítés folyamatban. Utána a felület magától újraindul.".into(),
|
||||
Ok(()) => "Frissítések keresése…".into(),
|
||||
Err(e) => {
|
||||
log::warn!("update request: {e}");
|
||||
format!("Nem sikerült: {}", short_err(&e))
|
||||
}
|
||||
};
|
||||
post(|| {
|
||||
std::thread::sleep(Duration::from_millis(700));
|
||||
Loaded::Updates(system::update_status())
|
||||
});
|
||||
}
|
||||
Loaded::RemoteDebug(on) => self.state.borrow_mut().remote_debug = Some(on),
|
||||
Loaded::RemoteDebugSet { on, result } => {
|
||||
{
|
||||
@@ -687,6 +718,18 @@ impl Screen {
|
||||
Some(true) => self.run(Action::SetRemoteDebug(false)),
|
||||
None => {}
|
||||
},
|
||||
Action::Updates => {
|
||||
self.state.borrow_mut().notice.clear();
|
||||
self.enter(Sub::Updates, 0);
|
||||
}
|
||||
Action::UpdateCheck | Action::UpdateInstall => {
|
||||
let install = action == Action::UpdateInstall;
|
||||
log::info!("updates: {}", if install { "install" } else { "check" });
|
||||
post(move || Loaded::UpdateRequested {
|
||||
install,
|
||||
result: system::request_update(if install { "install" } else { "check" }).map_err(|e| format!("{e:#}")),
|
||||
});
|
||||
}
|
||||
Action::SetRemoteDebug(on) => {
|
||||
log::info!("remote debug: turning {}", if on { "on" } else { "off" });
|
||||
self.state.borrow_mut().busy = true;
|
||||
@@ -855,6 +898,31 @@ impl Screen {
|
||||
push(row("Mégse", "", "", "action"), Action::Back);
|
||||
("Felület újraindítása".to_string(), "A futó alkalmazás bezárul, a kezdőképernyő újraindul.".to_string())
|
||||
}
|
||||
(Sub::Updates, _) => {
|
||||
let status = st.updates.clone().flatten();
|
||||
let busy = status.as_ref().is_some_and(UpdateStatus::busy);
|
||||
let updates: Vec<_> = status.as_ref().map(|s| s.updates().into_iter().cloned().collect()).unwrap_or_default();
|
||||
if !updates.is_empty() {
|
||||
let label = if busy { "Folyamatban…" } else { "Telepítés most" };
|
||||
push(row(label, "", "A felület utána újraindul", "danger"), Action::UpdateInstall);
|
||||
}
|
||||
let label = if busy { "Folyamatban…" } else { "Frissítések keresése" };
|
||||
push(row(label, "", "", "action"), Action::UpdateCheck);
|
||||
for p in status.iter().flat_map(|s| s.packages.iter()) {
|
||||
let (value, detail) = match p.update() {
|
||||
Some(v) if p.ready() => (format!("{} → {v}", p.installed), "Letöltve, újraindításkor települ".to_string()),
|
||||
Some(v) => (format!("{} → {v}", p.installed), "Új verzió".to_string()),
|
||||
None => (p.installed.clone(), String::new()),
|
||||
};
|
||||
push(row(p.title.clone(), value, detail, "info"), Action::None);
|
||||
}
|
||||
push(row("Vissza", "", "", "action"), Action::Back);
|
||||
let subtitle = match &status {
|
||||
None => "A frissítő még nem futott ezen a gépen.".to_string(),
|
||||
Some(s) => update_summary(s).1,
|
||||
};
|
||||
("Frissítések".to_string(), notice_or(&subtitle))
|
||||
}
|
||||
(Sub::RemoteDebug, _) => {
|
||||
let label = if st.busy { "Bekapcsolás…" } else { "Bekapcsolás" };
|
||||
push(row(label, "", "", "danger"), Action::SetRemoteDebug(true));
|
||||
@@ -1012,6 +1080,12 @@ impl Screen {
|
||||
(false, Some(_)) => ("Ki".to_string(), "SSH a helyi hálózatról".to_string()),
|
||||
};
|
||||
push(row("Távoli hibakeresés", value, detail, "action"), Action::RemoteDebug);
|
||||
let (value, detail) = match &st.updates {
|
||||
None => ("…".to_string(), String::new()),
|
||||
Some(None) => ("Nem elérhető".to_string(), "A frissítő még nem futott".to_string()),
|
||||
Some(Some(u)) => update_summary(u),
|
||||
};
|
||||
push(row("Frissítések", value, detail, "action"), Action::Updates);
|
||||
push(row("Felület újraindítása", "", "", "action"), Action::Restart);
|
||||
("Rendszer".to_string(), notice_or("Az eszköz adatai."))
|
||||
}
|
||||
@@ -1089,3 +1163,29 @@ pub fn glass(ui: &App, scale: f32) -> Vec<crate::glass::Panel> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Value and detail for the Updates row: "2 frissítés" / "SmartFox felület 0.2.0 · YouTube 1.1.0".
|
||||
fn update_summary(u: &UpdateStatus) -> (String, String) {
|
||||
let checked = || {
|
||||
use chrono::TimeZone;
|
||||
match chrono::Local.timestamp_opt(u.checked_at, 0).single() {
|
||||
Some(t) if u.checked_at > 0 => format!("Utoljára ellenőrizve: {}", t.format("%m. %d. %H:%M")),
|
||||
_ => "Még nem kereste".to_string(),
|
||||
}
|
||||
};
|
||||
match u.state.as_str() {
|
||||
"checking" => return ("Keresés…".into(), String::new()),
|
||||
"downloading" => return ("Letöltés…".into(), u.message.clone()),
|
||||
"installing" => return ("Telepítés…".into(), String::new()),
|
||||
"error" => return ("Hiba".into(), short_err(&u.message)),
|
||||
_ => {}
|
||||
}
|
||||
let updates = u.updates();
|
||||
if updates.is_empty() {
|
||||
return ("Naprakész".into(), checked());
|
||||
}
|
||||
let list = updates.iter().map(|p| format!("{} {}", p.title, p.update().unwrap_or_default())).collect::<Vec<_>>().join(" · ");
|
||||
let value = if updates.len() == 1 { "1 frissítés".to_string() } else { format!("{} frissítés", updates.len()) };
|
||||
let detail = if updates.iter().all(|p| p.ready()) { format!("{list} · újraindításkor települ") } else { list };
|
||||
(value, detail)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! backend with in-memory state keeps the settings screen usable.
|
||||
//! All calls can block for a moment, so run them off the UI thread.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -855,6 +856,139 @@ pub fn set_remote_debug(on: bool) -> Result<()> {
|
||||
bail!("ssh.service is still {}", if on { "stopped" } else { "running" })
|
||||
}
|
||||
|
||||
// ---- updates (sf-update, docs/updates.md) --------------------------------
|
||||
|
||||
/// Written by sf-update (root), readable by everyone.
|
||||
const UPDATE_STATUS: &str = "/var/lib/sf-pkg/status.json";
|
||||
/// The launcher asks sf-update for things by dropping empty files here.
|
||||
const UPDATE_REQUESTS: &str = "/var/lib/smartfox/update-requests";
|
||||
|
||||
static DEMO_UPDATE: Mutex<u8> = Mutex::new(0);
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct UpdateStatus {
|
||||
/// idle | checking | downloading | installing | error
|
||||
pub state: String,
|
||||
pub message: String,
|
||||
/// Unix time of the last check, 0 if never.
|
||||
pub checked_at: i64,
|
||||
pub packages: Vec<UpdatePackage>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct UpdatePackage {
|
||||
/// Display name ("SmartFox felület", "YouTube").
|
||||
pub title: String,
|
||||
pub installed: String,
|
||||
pub available: Option<String>,
|
||||
pub staged: Option<String>,
|
||||
}
|
||||
|
||||
impl UpdatePackage {
|
||||
/// The newer version on the server, if there is one.
|
||||
pub fn update(&self) -> Option<&str> {
|
||||
self.available.as_deref().filter(|a| sf_ipc::manifest::version_cmp(a, &self.installed).is_gt())
|
||||
}
|
||||
|
||||
/// Downloaded already, goes live at the next start.
|
||||
pub fn ready(&self) -> bool {
|
||||
self.update().is_some() && self.staged.as_deref() == self.update()
|
||||
}
|
||||
}
|
||||
|
||||
impl UpdateStatus {
|
||||
pub fn busy(&self) -> bool {
|
||||
matches!(self.state.as_str(), "checking" | "downloading" | "installing")
|
||||
}
|
||||
|
||||
pub fn updates(&self) -> Vec<&UpdatePackage> {
|
||||
self.packages.iter().filter(|p| p.update().is_some()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// "sf-shell" -> "SmartFox felület", "sf-app-youtube" -> the app's name.
|
||||
fn package_title(name: &str) -> String {
|
||||
if name == "sf-shell" {
|
||||
return "SmartFox felület".into();
|
||||
}
|
||||
let id = name.strip_prefix("sf-app-").unwrap_or(name);
|
||||
let dirs = [PathBuf::from("/usr/share/smartfox/apps"), PathBuf::from("/var/lib/sf-pkg/apps")];
|
||||
sf_ipc::manifest::load_apps_from(&dirs)
|
||||
.ok()
|
||||
.and_then(|apps| apps.into_iter().find(|a| a.id == id).map(|a| a.name))
|
||||
.unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
/// What sf-update last reported; None if it never ran.
|
||||
pub fn update_status() -> Option<UpdateStatus> {
|
||||
if demo() {
|
||||
let step = *DEMO_UPDATE.lock().unwrap();
|
||||
let pkg = |title: &str, installed: &str, available: &str| UpdatePackage {
|
||||
title: title.into(),
|
||||
installed: installed.into(),
|
||||
available: Some(available.into()),
|
||||
staged: None,
|
||||
};
|
||||
let packages = match step {
|
||||
0 => vec![pkg("SmartFox felület", "0.1.0", "0.2.0"), pkg("YouTube", "1.0.0", "1.1.0"), pkg("Netflex", "1.0.0", "1.0.0")],
|
||||
_ => vec![pkg("SmartFox felület", "0.2.0", "0.2.0"), pkg("YouTube", "1.1.0", "1.1.0")],
|
||||
};
|
||||
return Some(UpdateStatus { state: "idle".into(), message: String::new(), checked_at: 1_792_800_000, packages });
|
||||
}
|
||||
let text = std::fs::read_to_string(UPDATE_STATUS).ok()?;
|
||||
let v: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
let s = |v: &serde_json::Value, k: &str| v.get(k).and_then(|x| x.as_str()).map(str::to_string);
|
||||
let packages = v
|
||||
.get("packages")
|
||||
.and_then(|p| p.as_array())
|
||||
.map(|list| {
|
||||
list.iter()
|
||||
.map(|p| UpdatePackage {
|
||||
title: package_title(&s(p, "name").unwrap_or_default()),
|
||||
installed: s(p, "installed").unwrap_or_default(),
|
||||
available: s(p, "available"),
|
||||
staged: s(p, "staged"),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Some(UpdateStatus {
|
||||
state: s(&v, "state").unwrap_or_else(|| "idle".into()),
|
||||
message: s(&v, "message").unwrap_or_default(),
|
||||
checked_at: v.get("checked_at").and_then(|x| x.as_i64()).unwrap_or(0),
|
||||
packages,
|
||||
})
|
||||
}
|
||||
|
||||
/// Asks sf-update (root) to `check` or `install`; it runs from
|
||||
/// sf-update-requests.path and reports through status.json.
|
||||
pub fn request_update(what: &str) -> Result<()> {
|
||||
if demo() {
|
||||
if what == "install" {
|
||||
*DEMO_UPDATE.lock().unwrap() = 1;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let path = Path::new(UPDATE_REQUESTS).join(what);
|
||||
std::fs::write(&path, b"").with_context(|| format!("writing {}", path.display()))
|
||||
}
|
||||
|
||||
/// A freshly installed shell is on trial (sf-launcher-start sets
|
||||
/// SMARTFOX_SHELL_TRIAL); once it has run for a while it tells sf-update to
|
||||
/// keep it. If it never gets here, sf-update rolls it back.
|
||||
pub fn confirm_shell_trial() {
|
||||
if std::env::var_os("SMARTFOX_SHELL_TRIAL").is_none() {
|
||||
return;
|
||||
}
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(Duration::from_secs(30));
|
||||
match request_update("confirm") {
|
||||
Ok(()) => log::info!("new shell confirmed"),
|
||||
Err(e) => log::warn!("confirming the new shell: {e:#}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
20
crates/sf-update/Cargo.toml
Normal file
20
crates/sf-update/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "sf-update"
|
||||
description = "SmartFox package updater: signed shell and app packages from the Gitea package registry"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sf-ipc.workspace = true
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
toml.workspace = true
|
||||
ureq = "3"
|
||||
ed25519-dalek = "2"
|
||||
base64 = "0.22"
|
||||
tar = "0.4"
|
||||
ruzstd = "0.8"
|
||||
97
crates/sf-update/src/config.rs
Normal file
97
crates/sf-update/src/config.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
//! Updater settings: /usr/share/smartfox/update.toml from the image, with
|
||||
//! /var/lib/sf-pkg/update.toml (if present) overriding single keys, so a TV
|
||||
//! can be pointed elsewhere or get a new token without reinstalling.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use base64::Engine;
|
||||
use serde::Deserialize;
|
||||
|
||||
const IMAGE_CONFIG: &str = "/usr/share/smartfox/update.toml";
|
||||
const LOCAL_CONFIG: &str = "/var/lib/sf-pkg/update.toml";
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct File {
|
||||
server: Option<String>,
|
||||
owner: Option<String>,
|
||||
token_file: Option<PathBuf>,
|
||||
public_key: Option<String>,
|
||||
root: Option<PathBuf>,
|
||||
requests: Option<PathBuf>,
|
||||
factory: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl File {
|
||||
fn read(path: &Path) -> Result<Self> {
|
||||
let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
|
||||
toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))
|
||||
}
|
||||
|
||||
fn overlay(self, o: File) -> File {
|
||||
File {
|
||||
server: o.server.or(self.server),
|
||||
owner: o.owner.or(self.owner),
|
||||
token_file: o.token_file.or(self.token_file),
|
||||
public_key: o.public_key.or(self.public_key),
|
||||
root: o.root.or(self.root),
|
||||
requests: o.requests.or(self.requests),
|
||||
factory: o.factory.or(self.factory),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Config {
|
||||
/// Gitea base URL, e.g. https://gitea.example.org
|
||||
pub server: String,
|
||||
/// User or organization that owns the packages.
|
||||
pub owner: String,
|
||||
/// "user:token" for HTTP basic auth (read:package scope), if any.
|
||||
pub auth: Option<String>,
|
||||
/// Ed25519 key that signs every package.
|
||||
pub public_key: [u8; 32],
|
||||
/// Installed packages and status.json (root-owned).
|
||||
pub root: PathBuf,
|
||||
/// Request files from the launcher (tv-owned folder).
|
||||
pub requests: PathBuf,
|
||||
/// Versions of the copies built into the image.
|
||||
pub factory: PathBuf,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> Result<Self> {
|
||||
let mut file = match std::env::var_os("SF_UPDATE_CONFIG") {
|
||||
Some(p) => File::read(Path::new(&p))?,
|
||||
None => File::read(Path::new(IMAGE_CONFIG))?,
|
||||
};
|
||||
if Path::new(LOCAL_CONFIG).exists() && std::env::var_os("SF_UPDATE_CONFIG").is_none() {
|
||||
file = file.overlay(File::read(Path::new(LOCAL_CONFIG))?);
|
||||
}
|
||||
let Some(server) = file.server else { bail!("update.toml: server is missing") };
|
||||
let Some(owner) = file.owner else { bail!("update.toml: owner is missing") };
|
||||
let Some(key) = file.public_key else { bail!("update.toml: public_key is missing") };
|
||||
let key = base64::engine::general_purpose::STANDARD.decode(key.trim()).context("public_key: not base64")?;
|
||||
let public_key: [u8; 32] = key.try_into().map_err(|_| anyhow::anyhow!("public_key: not a 32-byte Ed25519 key"))?;
|
||||
let auth = match &file.token_file {
|
||||
Some(p) if p.exists() => {
|
||||
let t = std::fs::read_to_string(p).with_context(|| format!("reading {}", p.display()))?;
|
||||
Some(t.trim().to_string()).filter(|t| !t.is_empty())
|
||||
}
|
||||
Some(p) => {
|
||||
log::warn!("token file {} missing, trying without login", p.display());
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Config {
|
||||
server: server.trim_end_matches('/').to_string(),
|
||||
owner,
|
||||
auth,
|
||||
public_key,
|
||||
root: file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into()),
|
||||
requests: file.requests.unwrap_or_else(|| "/var/lib/smartfox/update-requests".into()),
|
||||
factory: file.factory.unwrap_or_else(|| "/usr/share/smartfox/factory-versions.toml".into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
216
crates/sf-update/src/main.rs
Normal file
216
crates/sf-update/src/main.rs
Normal file
@@ -0,0 +1,216 @@
|
||||
//! sf-update: installs signed SmartFox packages (the shell and the apps) from
|
||||
//! the Gitea package registry onto the writable data partition. The root
|
||||
//! file system stays read-only and keeps the factory copies as a fallback.
|
||||
//!
|
||||
//! Protocol and layout: docs/updates.md.
|
||||
//!
|
||||
//! sf-update check ask the server what's new (status.json)
|
||||
//! sf-update auto check, then download and stage what's new (timer)
|
||||
//! sf-update apply switch staged packages live (at boot)
|
||||
//! sf-update install check, download, apply now and restart the UI
|
||||
//! sf-update requests handle the launcher's request files (path unit)
|
||||
//! sf-update status print status.json
|
||||
|
||||
mod config;
|
||||
mod registry;
|
||||
mod store;
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::store::Store;
|
||||
|
||||
fn main() {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
let cmd = std::env::args().nth(1).unwrap_or_default();
|
||||
if let Err(e) = run(&cmd) {
|
||||
log::error!("{cmd}: {e:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(cmd: &str) -> Result<()> {
|
||||
let cfg = Config::load()?;
|
||||
let store = Store::open(&cfg)?;
|
||||
match cmd {
|
||||
"status" => {
|
||||
println!("{}", serde_json::to_string_pretty(&store.read_status())?);
|
||||
return Ok(());
|
||||
}
|
||||
"check" | "auto" | "apply" | "install" | "requests" => {}
|
||||
_ => bail!("usage: sf-update check|auto|apply|install|requests|status"),
|
||||
}
|
||||
// One run at a time (timer, boot and launcher requests can overlap).
|
||||
let _lock = store.lock(Duration::from_secs(600))?;
|
||||
match cmd {
|
||||
"check" => check(&cfg, &store).map(drop),
|
||||
"auto" => auto(&cfg, &store),
|
||||
"apply" => apply(&store).map(drop),
|
||||
"install" => install(&cfg, &store),
|
||||
"requests" => requests(&cfg, &store),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the registry for the newest version of every package and records
|
||||
/// which ones are newer than what's installed.
|
||||
fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> {
|
||||
store.set_state("checking", "");
|
||||
let latest = match registry::latest_versions(cfg) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
store.set_state("error", &format!("{e:#}"));
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let pending = store.refresh(&latest);
|
||||
store.set_state("idle", "");
|
||||
log::info!("{} update(s) available", pending.len());
|
||||
Ok(pending)
|
||||
}
|
||||
|
||||
/// Downloads and stages each pending package. Failures of one package don't
|
||||
/// stop the others; the first error is reported.
|
||||
fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<usize> {
|
||||
let mut first_err = None;
|
||||
let mut done = 0;
|
||||
for p in pending {
|
||||
if store.staged(&p.name).as_deref() == Some(p.version.as_str()) {
|
||||
done += 1;
|
||||
continue;
|
||||
}
|
||||
store.set_state("downloading", &format!("{} {}", p.name, p.version));
|
||||
let result = (|| -> Result<()> {
|
||||
let dir = store.download_dir()?;
|
||||
let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?;
|
||||
store.verify_and_unpack(cfg, &p.name, &p.version, &pkg, &sig)?;
|
||||
store.stage(&p.name, &p.version)
|
||||
})();
|
||||
let _ = std::fs::remove_dir_all(store.download_dir_path());
|
||||
match result {
|
||||
Ok(()) => {
|
||||
log::info!("staged {} {}", p.name, p.version);
|
||||
done += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{} {}: {e:#}", p.name, p.version);
|
||||
first_err.get_or_insert(e.context(format!("{} {}", p.name, p.version)));
|
||||
}
|
||||
}
|
||||
}
|
||||
store.write_status(|_| {});
|
||||
match first_err {
|
||||
Some(e) => {
|
||||
store.set_state("error", &format!("{e:#}"));
|
||||
Err(e)
|
||||
}
|
||||
None => {
|
||||
store.set_state("idle", "");
|
||||
Ok(done)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn auto(cfg: &Config, store: &Store) -> Result<()> {
|
||||
let pending = check(cfg, store)?;
|
||||
download(cfg, store, &pending)?;
|
||||
store.gc();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Switches staged packages live. Returns which kinds changed.
|
||||
fn apply(store: &Store) -> Result<store::Applied> {
|
||||
let applied = store.apply_staged()?;
|
||||
store.gc();
|
||||
store.write_status(|_| {});
|
||||
Ok(applied)
|
||||
}
|
||||
|
||||
fn install(cfg: &Config, store: &Store) -> Result<()> {
|
||||
let pending = check(cfg, store)?;
|
||||
let result = download(cfg, store, &pending);
|
||||
store.set_state("installing", "");
|
||||
let applied = apply(store)?;
|
||||
store.set_state("idle", "");
|
||||
restart(&applied);
|
||||
result.map(drop)
|
||||
}
|
||||
|
||||
/// Restarts what an update touched: the remote driver for a new shell, the
|
||||
/// TV session (cage + launcher) for a new shell or new apps.
|
||||
fn restart(applied: &store::Applied) {
|
||||
if applied.shell {
|
||||
systemctl(&["restart", "sf-remote.service"]);
|
||||
}
|
||||
if applied.shell || applied.apps {
|
||||
restart_ui();
|
||||
}
|
||||
}
|
||||
|
||||
fn restart_ui() {
|
||||
let _ = std::process::Command::new("pkill").args(["-x", "sf-launcher"]).status();
|
||||
systemctl(&["restart", "getty@tty1.service"]);
|
||||
}
|
||||
|
||||
fn systemctl(args: &[&str]) {
|
||||
match std::process::Command::new("systemctl").args(args).status() {
|
||||
Ok(s) if s.success() => {}
|
||||
other => log::warn!("systemctl {}: {other:?}", args.join(" ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The launcher (user tv) can't run anything as root; it drops empty files
|
||||
/// named after a request into the requests folder, sf-update-requests.path
|
||||
/// starts this. Only the file names are used, never their contents.
|
||||
fn requests(cfg: &Config, store: &Store) -> Result<()> {
|
||||
const ORDER: [&str; 4] = ["rollback", "confirm", "install", "check"];
|
||||
let dir = &cfg.requests;
|
||||
let mut result = Ok(());
|
||||
for _ in 0..10 {
|
||||
let mut any = false;
|
||||
for name in ORDER {
|
||||
if take(dir, name) {
|
||||
any = true;
|
||||
log::info!("request: {name}");
|
||||
let r = match name {
|
||||
"rollback" => rollback(store),
|
||||
"confirm" => store.confirm_shell(),
|
||||
"install" => install(cfg, store),
|
||||
_ => check(cfg, store).map(drop),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
log::error!("{name}: {e:#}");
|
||||
result = Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unknown files: remove so the path unit doesn't loop on them.
|
||||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||
for e in entries.flatten() {
|
||||
log::warn!("ignoring request {:?}", e.file_name());
|
||||
let _ = std::fs::remove_file(e.path());
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
break;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Removes a request file; true if it was there. Never follows symlinks.
|
||||
fn take(dir: &Path, name: &str) -> bool {
|
||||
std::fs::remove_file(dir.join(name)).is_ok()
|
||||
}
|
||||
|
||||
fn rollback(store: &Store) -> Result<()> {
|
||||
if store.rollback_shell().context("rolling back the shell")? {
|
||||
systemctl(&["restart", "sf-remote.service"]);
|
||||
restart_ui();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
132
crates/sf-update/src/registry.rs
Normal file
132
crates/sf-update/src/registry.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
//! Gitea generic package registry client.
|
||||
//!
|
||||
//! list: GET {server}/api/v1/packages/{owner}?type=generic&q=sf-
|
||||
//! download: GET {server}/api/packages/{owner}/generic/{name}/{version}/{name}-{version}.tar.zst (+ .sig)
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use base64::Engine;
|
||||
use serde::Deserialize;
|
||||
use sf_ipc::manifest::version_cmp;
|
||||
|
||||
/// Largest package we'll download.
|
||||
const MAX_PACKAGE: u64 = 1024 * 1024 * 1024;
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
/// Package names this updater handles.
|
||||
pub fn is_ours(name: &str) -> bool {
|
||||
name == "sf-shell" || name.strip_prefix("sf-app-").is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
|
||||
}
|
||||
|
||||
/// Release versions only: digits and dots (prereleases like 1.2.0-rc1 are skipped).
|
||||
pub fn is_release(version: &str) -> bool {
|
||||
!version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 3
|
||||
}
|
||||
|
||||
fn agent() -> ureq::Agent {
|
||||
ureq::Agent::config_builder()
|
||||
.timeout_connect(Some(Duration::from_secs(15)))
|
||||
.timeout_recv_body(Some(Duration::from_secs(1800)))
|
||||
.timeout_recv_response(Some(Duration::from_secs(60)))
|
||||
.https_only(false)
|
||||
.build()
|
||||
.into()
|
||||
}
|
||||
|
||||
fn get(cfg: &Config, agent: &ureq::Agent, url: &str) -> Result<ureq::http::Response<ureq::Body>> {
|
||||
let mut req = agent.get(url);
|
||||
if let Some(auth) = &cfg.auth {
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(auth);
|
||||
req = req.header("Authorization", format!("Basic {b64}"));
|
||||
}
|
||||
req.call().with_context(|| format!("GET {}", strip_query(url)))
|
||||
}
|
||||
|
||||
fn strip_query(url: &str) -> &str {
|
||||
url.split('?').next().unwrap_or(url)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PackageVersion {
|
||||
name: String,
|
||||
version: String,
|
||||
}
|
||||
|
||||
/// Newest release version of every package on the server.
|
||||
pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
|
||||
let agent = agent();
|
||||
let mut latest: BTreeMap<String, String> = BTreeMap::new();
|
||||
for page in 1..=100 {
|
||||
let url = format!("{}/api/v1/packages/{}?type=generic&q=sf-&limit=50&page={page}", cfg.server, cfg.owner);
|
||||
let text = get(cfg, &agent, &url)?.body_mut().read_to_string()?;
|
||||
let list: Vec<PackageVersion> = serde_json::from_str(&text).context("package list")?;
|
||||
if list.is_empty() {
|
||||
break;
|
||||
}
|
||||
for p in list {
|
||||
if !is_ours(&p.name) || !is_release(&p.version) {
|
||||
continue;
|
||||
}
|
||||
match latest.get(&p.name) {
|
||||
Some(v) if version_cmp(v, &p.version).is_ge() => {}
|
||||
_ => {
|
||||
latest.insert(p.name, p.version);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(latest)
|
||||
}
|
||||
|
||||
/// File name of a package in the registry.
|
||||
pub fn file_name(name: &str, version: &str) -> String {
|
||||
format!("{name}-{version}.tar.zst")
|
||||
}
|
||||
|
||||
/// Downloads a package and its signature into `dir`.
|
||||
pub fn download(cfg: &Config, name: &str, version: &str, dir: &Path) -> Result<(PathBuf, Vec<u8>)> {
|
||||
if !is_ours(name) || !is_release(version) {
|
||||
bail!("refusing package {name} {version}");
|
||||
}
|
||||
let agent = agent();
|
||||
let file = file_name(name, version);
|
||||
let base = format!("{}/api/packages/{}/generic/{name}/{version}", cfg.server, cfg.owner);
|
||||
|
||||
let mut sig = Vec::new();
|
||||
get(cfg, &agent, &format!("{base}/{file}.sig"))?.into_body().into_reader().take(1024).read_to_end(&mut sig)?;
|
||||
|
||||
let path = dir.join(&file);
|
||||
let mut out = std::fs::File::create(&path).with_context(|| format!("creating {}", path.display()))?;
|
||||
let resp = get(cfg, &agent, &format!("{base}/{file}"))?;
|
||||
let mut body = resp.into_body().into_reader().take(MAX_PACKAGE + 1);
|
||||
let n = std::io::copy(&mut body, &mut out).with_context(|| format!("downloading {file}"))?;
|
||||
if n > MAX_PACKAGE {
|
||||
bail!("{file} is larger than {MAX_PACKAGE} bytes");
|
||||
}
|
||||
out.sync_all()?;
|
||||
log::info!("downloaded {file} ({n} bytes)");
|
||||
Ok((path, sig))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_and_versions() {
|
||||
assert!(is_ours("sf-shell"));
|
||||
assert!(is_ours("sf-app-youtube"));
|
||||
assert!(!is_ours("sf-app-"));
|
||||
assert!(!is_ours("sf-app-../x"));
|
||||
assert!(!is_ours("other"));
|
||||
assert!(is_release("1.2.3"));
|
||||
assert!(!is_release("1.2.3-rc1"));
|
||||
assert!(!is_release("1..2"));
|
||||
assert!(!is_release("../1"));
|
||||
}
|
||||
}
|
||||
363
crates/sf-update/src/store.rs
Normal file
363
crates/sf-update/src/store.rs
Normal file
@@ -0,0 +1,363 @@
|
||||
//! 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();
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user