update#
signed app updates: check, download, apply at the next start, health marker, rollback -- crate root lib/update/lib.rs
update -- signed updates of an app: check, download, put in place at the next start, roll
back a version that does not start
Config::new(app, version, url, keys) the app's id and running version, the address of
its update.json and the trusted Ed25519 public keys (hex);
then dir (default data://update), exe, target, attempts,
restart, max_size, ca_pem, timeout_ms
startup(&cfg) -> Startup first thing in main (before ui::launch): puts a downloaded
update in place and restarts into it, counts the starts of a
new version, rolls back one that never reported healthy;
a program that calls itself neither the trial's version nor
the old one ends the trial (the version recorded as bad)
healthy(&cfg) -> bool the health marker: the new version works (after its first
frame, for example); without it the next start rolls back
Updater::new(cfg) check() / download() / apply() (blocking), start_check() /
start_download() (a background thread, plat::wake() when
done), status() (phase, progress, error), cancel(), staged()
state(&cfg), newer(a, b), target(), Manifest::parse, verify
fetch::{get, download, join, Progress} its HTTP(S) for other downloads of an app (fetch.rs)
install(&cfg) -> Packaged how the program is installed (plat::pkg::packaged; cfg.exe
set: Plain), which decides what an update is:
Plain exe / bundle / package entries of update.json (below); a program in a macOS
app bundle (NAME.app/Contents/MacOS/NAME) takes the "app" entry instead: the
bundle is replaced as a whole (unpacked next to it, its signature checked against
the installed one's requirement -- plat::pkg::app_bundle_follows --, exchanged in
one step, the old bundle the backup; trial and rollback as for an exe); a folder
the user cannot write or a bundle macOS moved away (App Translocation):
Error::ReadOnly
AppImage the "appimage" entry: the .AppImage file ($APPIMAGE) is replaced as a whole
(copied next to it, checked, renamed over it; the old file is the backup, the
trial and the rollback as for an exe; restarted through the AppImage); a folder
the user cannot write: check() fails with Error::ReadOnly. A signed AppImage
(.sha256_sig / .sig_key, appimagetool --sign) only takes an update signed by a
key of its own key block (appimage.rs, pgp.rs)
Flatpak no update.json: the portal's update monitor (plat::pkg::FlatpakMonitor) --
check() reports what it found (Kind::Flatpak), download() installs it
(Update, Progress), apply() starts the newest version (Spawn) and ends this
one; without the portal: Check::Managed(Manager::Flatpak, None)
Msix Check::Managed: App Installer (an .appinstaller: updated at the next start,
with whether it knows of a newer version) or whoever installed the package
Snap Check::Managed(Manager::Snap, None)
appimage_signature(path) the embedded signature of an AppImage file (Signed)
The channel: update.json (UTF-8 JSON) and update.json.sig beside it (the Base64 Ed25519
signature over the exact bytes of update.json); tools/update_manifest.py writes both:
{"format": 1, "app": "Kritzel", "version": "1.2.0", "date": 1760000000,
"expires": 1762600000, "notes": "...",
"files": [{"target": "windows-x86_64", "kind": "exe", "url": "Kritzel-1.2.0.exe",
"size": 123456, "sha256": "<64 hex digits>"}, ...]}
kind "exe" replaces the program file, "bundle" is a JFA1 bundle of files relative to the
program's folder (the program and its modules), "package" an installer (.deb, setup) that
is only downloaded and checked (Updater::staged), "appimage" a whole AppImage (only for a
program running as one; entries of unknown kinds are left out). A relative url is resolved
against the address update.json came from; redirects are followed (at most 5).
Checks: the signature against cfg.keys; "app" must be cfg.app; "expires" (unix seconds) not
passed; a version older than one a signed manifest named before is refused (replay); only a
newer version than cfg.version that was not rolled back is offered; the file's size and
SHA-256 while it downloads, and all of it again before it is put in place. Connections go
through netio and plat::net, so the app's net.connect rules apply (a refused host:
Error::Denied and PERMDENY on stderr); https checks the server against the system's CAs
(plus cfg.ca_pem). The signature protects the content, so http works too.
cfg.dir holds state (stage, version, from, starts, bad, seen), lock, partial/<sha256> (an
interrupted download, continued with a Range request), staged/ (update.json, its signature
and the file) and backup/ (the replaced files of the last update). Putting an update in
place writes the program's folder: in an app with a PERMISSIONS manifest that needs
fs.write $EXE/** (an AppImage: fs.write $APPIMAGE/**); a folder of the system (/usr/lib,
Program Files) needs a "package" update.
update crate root#
Re-exports: plat::pkg::Packaged
struct Configwhat the updater needs to know about the appapp: String-- the app's id as the manifest names it ("app")version: String-- the running versionurl: String-- the address of update.json (https://... or http://...)keys: Vec<[u8; 32]>-- the trusted Ed25519 public keys (built into the app)dir: String-- the folder of the updater's files (default "data://update")exe: String-- the program file an update replaces ("" = the running exe)target: String-- the system whose package is taken (default target())attempts: u32-- starts of a new version without healthy() before it is rolled back (default 1)restart: bool-- startup() and apply() restart the program after a change (default true; false: they return Startup::Applied / RollingBack and the caller restarts)max_size: u64-- the largest package accepted (default 1 GiB)ca_pem: String-- further CA certificates (PEM) for an https channel with its own CAtimeout_ms: u32-- the longest wait for the server (ms; default 60000)
impl Config
fn new(app: &str, version: &str, url: &str, keys: &[&str]) -> Configthe app's id and version, the address of update.json and the trusted public keys (64 hex digits each; others are left out, so a channel without a valid key fails with Error::Config) -- the other fields at their defaultsenum Errorwhy a step failedConfig(String)-- no channel, no valid key or an invalid addressDenied(String)-- the app's PERMISSIONS do not allow the host (net.connect)Net(String)-- connection or protocol failureTls(String)-- the TLS layer refused: the certificate or the handshakeTooLarge(String)-- the answer is over the limit fetch::get was givenHttp(u16)-- the server answered with another status than 200 / 206Signature-- the signature of update.json matches no trusted keyManifest(String)-- update.json is malformed or for another appExpired-- the manifest's "expires" has passedReplay(String)-- the manifest is older than one seen before (its version)Size { expected: u64, got: u64 }-- the file has not the size of the manifestHash-- the file's SHA-256 is not the manifest'sIncomplete { done: u64, total: u64 }-- the connection ended early; what arrived is kept and the next download continues itCancelled-- stopped by cancel()Busy-- another check, download or apply runs (this process or another one)Nothing-- nothing to download or to applyUnsupported(String)-- a package that is not put in place by the updaterIo(String)-- files could not be read or writtenReadOnly(String)-- the AppImage or the macOS app bundle lies in a folder the user cannot write (the folder): it is not replacedRejected(String)-- the downloaded package is not taken: not an AppImage, or its signature does not follow the running one's (why)
struct Offera newer version the channel offersversion: Stringnotes: Stringdate: i64-- unix seconds (0: not given)size: u64-- the package's size in byteskind: Kindstaged: bool-- it is downloaded already (staged)
enum Checkthe answer of a checkUpToDate-- no newer version (or only one that was rolled back)NoPackage(String)-- a newer version without a package for this system and installation (its version): an AppImage takes only "appimage" entries, a plain program none of themAvailable(Offer)-- a newer version to downloadManaged(Manager, Option<bool>)-- this installation is updated by its package system, not through update.json: who, and whether it knows of a newer version (None: it does not say)
enum Managerwho updates an installation that lib/update does not update itself (Check::Managed)AppInstaller-- App Installer: the MSIX package came from an .appinstaller file and is updated as that file says (tools/pkg_msix.py: at the next start)Msix-- an MSIX package without an .appinstaller (the Store, Add-AppxPackage): updated by whoever installed itFlatpak-- Flatpak (flatpak update, a software centre): the portal's update monitor is missingSnap-- snapd
enum Startupwhat startup() didNormal-- nothing to doApplied(String)-- the staged version is in place; the program must restart into it (only with cfg.restart = false or when the restart failed)Trial(String)-- this is a new version on trial: call healthy() once the app worksRollingBack(String)-- the new version never reported healthy and the old one is back; the program must restart (only with cfg.restart = false or when the restart failed)RolledBack(String)-- the old version runs again because this new one failed (reported once)Failed(Error)-- putting the staged update in place failed (a damaged one is dropped)
enum Phasewhat an Updater is doingIdleCheckingUpToDate-- the last check found nothing newerAvailable-- a newer version can be downloaded (Status::version)DownloadingReady-- downloaded and checked: put in place at the next start or by apply()Failed-- the last step failed (Status::error)
struct Statusthe state for a dialog or a status linephase: Phaseversion: String-- the offered or downloaded versionnotes: Stringdone: u64-- bytes downloaded and the file's sizetotal: u64error: Option<Error>
struct Updaterchecks and downloads for one Config; clones share the same state
impl Updater
fn new(cfg: Config) -> Updateran updater for cfg; a downloaded update (stage Staged) starts it in Phase::Readyfn config(&self) -> &Configthe configuration it was made withfn status(&self) -> Statusthe current phase, progress and last errorfn cancel(&self)stop a running download (it ends with Error::Cancelled; what arrived is kept)fn check(&self) -> Result<Check, Error>fetch update.json and its signature and check them (blocking)fn download(&self) -> Result<String, Error>download the package the last check() offered, check it and stage it for the next start (blocking; progress in status()) -> its versionfn start_check(&self) -> boolcheck() on a background thread; plat::wake() (UIC_WAKE / E_WAKE) when it is done -> false while another background step runsfn start_download(&self) -> booldownload() on a background thread; plat::wake() when it is done -> false while another background step runsfn busy(&self) -> boolwhether a background step runsfn staged(&self) -> Option<(String, Kind, String)>the downloaded update: its version, kind and the OS path of its file (a "package" is installed from there by the app or the user)fn apply(&self) -> Result<Startup, Error>put the downloaded update in place now and restart into it (with cfg.restart the process ends here); a Flatpak: start the newest installed version (the portal's Spawn) and end this onefn install(cfg: &Config) -> Packagedhow the running program is installed, which decides what an update is (cfg.exe set: Plain -- an explicit program file)fn startup(cfg: &Config) -> Startupat the start of the program, before its UI: a staged update is put in place and the program restarted into it; a new version on trial counts its start, and one that already had cfg.attempts starts without healthy() is rolled back (the old version restarted). A program whose version is neither the trial's nor the one before (the package's own number differs from its manifest's) ends the trial: Normal, the trial's version recorded as bad. Another process holding the updater's lock: Normal.fn healthy(cfg: &Config) -> boolthe health marker: the new version on trial works. Call it once the app is up (after its first frame, for example); true when it ended a trial. Cheap when no trial runs.
update/appimage.rs#
Source: lib/update/appimage.rs
appimage -- an AppImage file as an update: the type-2 header, its embedded signature (the
sections .sha256_sig and .sig_key appimagetool --sign writes) and whether a new file may
follow the running one
is_type2(path) -> bool ELF with "AI\x02" at byte 8
signature(path) -> Result<Signed, String> No (no or empty sections), By(the signing key
of the embedded key block, its fingerprints), Err: a
signature that does not check
follows(old, new) -> Result<(), String> the rule of an update: a signed AppImage only
takes one signed by a key of its own key block
The signed text is the SHA-256 of the whole file, with the bytes of both sections taken as
zeros, as 64 lower-case hex digits (appimagetool's digest; AppImageUpdate's validate checks
the same). The armored signature and key stand NUL-padded in their sections.
enum Signedwhat an AppImage's signature sections sayNo-- not signed (no sections, or empty ones)By { signer: [u8; 20], keys: Vec<[u8; 20]> }-- signed bysigner(a key of the embedded block, whose fingerprints arekeys)
fn signature(path: &str) -> Result<Signed, String>the embedded signature of the AppImage at path
update/apply.rs#
Source: lib/update/apply.rs
apply -- the state of an update in cfg.dir, putting a staged update in place, the trial of
the new version and the way back
state(cfg) -> State the file cfg.dir/state (key=value lines)
startup(cfg) -> Startup (lib.rs) first thing at program start
healthy(cfg) -> bool (lib.rs) the health marker
Every file of an update is written next to its target as NAME.jfupd-new; the old file is
copied to backup/files/ (backup/list: "H sha256 path" replaced, with the copy's SHA-256, which
the way back checks for every copy before it puts one back, and again while it copies -- "R
path" of earlier versions without one; "N path" new), renamed away
(NAME.jfupd-old-<n>: Windows can rename a running exe, not replace it) and the new file takes
its name. Leftover .jfupd-* files are removed at a later start, once no process uses them.
An AppImage update has one file, the .AppImage itself ($APPIMAGE): copied (and hashed on the
way) from staged/ as NAME.jfupd-new, checked as an AppImage whose signature follows the
running one's (appimage.rs), renamed over the old file (atomic on Linux); the old file is
the backup. Large files are copied in pieces, never read whole.
An app bundle (kind "app", macOS) is replaced as a whole: its files unpacked as
NAME.app.jfupd-new, the bundle's signature checked against the installed one's requirement
(plat::pkg::app_bundle_follows), a copy of the installed bundle in backup/app/ (backup/list:
"A NAME.app"), the two folders exchanged in one step (plat::pkg::app_bundle_swap) and the old
one removed; the rollback exchanges the copy back the same way.
enum Stagewhere an update standsNone-- nothing pendingStaged-- downloaded and checked: put in place at the next start (or by Updater::apply)Trial-- the new version runs on trial until healthy()Ok-- the new version reported healthy() (the backup of the old one is kept)RolledBack-- the new version failed and the old one is back; reported once by startup()
struct Statethe file cfg.dir/statestage: Stageversion: String-- the staged, new or rolled-back versionfrom: String-- the version that was running before itstarts: u32-- starts of the new version without healthy()kind: String-- what the staged file isfile: String-- the staged file's name in staged/bad: Vec<String>-- versions that were rolled back: never offered againseen: String-- the newest version a signed manifest named (older manifests are refused: replay)
fn state(cfg: &Config) -> Statethe state of cfg.dir (a missing or unreadable file: nothing pending)
update/fetch.rs#
Source: lib/update/fetch.rs
fetch -- the updater's HTTP(S), public for an app's other downloads: small files with
redirects, and downloads that hash while they write and resume an interrupted file with a
Range request (docs/UPDATES.md "Downloads without an update")
join(base, href) -> Option<Url> a manifest's file address
get(cfg, url, max) -> (final url, bytes)
download(cfg, url, part, size, sha256, progress) -> Ok when part holds the whole file
Of the Config only app and version (the User-Agent), ca_pem and timeout_ms count, so
Config::new(app, version, "", &[]) is enough. Connections go through netio and plat::net: the
app's net.connect rules apply, an `ask` line asks on the calling thread's behalf (not the UI
thread, these calls block). Failures: Error::Denied (the host), Tls, TooLarge (get), Net, Http,
Size, Hash, Incomplete (the part stays for the next call), Cancelled, Io.
struct Progress<'a>the counters a download updates and the flag that stops itdone: &'a AtomicU64total: &'a AtomicU64cancel: &'a AtomicBool
fn join(base: &Url, href: &str) -> Option<Url>href relative to base: an absolute http(s) address, "//host/..", "/path" or a name relative to base's folderfn get(cfg: &Config, url: &Url, max: usize) -> Result<(Url, Vec<u8>), Error>a small file (at most max bytes), redirects followed -> the address it came from and its bytesfn download(cfg: &Config, url: &Url, part: &str, size: u64, sha256: &[u8; 32], p: &Progress) -> Result<(), Error>download url into the file part: a part that already holds the start of the file is hashed and continued with a Range request (a server that answers 200 instead starts it over). The answer must have exactlysizebytes with this SHA-256; a wrong file is deleted (Error::Size / Error::Hash), an interrupted one kept (Error::Incomplete).
update/manifest.rs#
Source: lib/update/manifest.rs
manifest -- update.json: parse, check the signature, pick the package of this system,
compare versions
Manifest::parse(bytes) -> Result<Manifest, String> (no signature check; entries of a
kind this version does not know are left out)
Manifest::package_for(target, appimage) the entry for this system and installation
verify(bytes, sig_text, keys) -> bool the Base64 Ed25519 signature of update.json.sig
target() -> "windows-x86_64" | "linux-x86_64" | "linux-aarch64" | "macos-aarch64" | ...
newer(a, b) -> bool "1.10.0" > "1.9.2", "2.0.0" > "2.0.0-rc1"
/// the largest update.json read
MAX_MANIFEST: usize = 1 << 20
/// the largest update.json.sig read
MAX_SIG: usize = 4096
enum Kindwhat a package of the manifest isExe-- the program file itselfBundle-- a JFA1 bundle (tools/assetpack.py) of files relative to the program's folderPackage-- an installer (.deb, setup): downloaded and checked, installed by the app or the userAppImage-- a whole AppImage: replaces the running AppImage's file ($APPIMAGE); only offered to a program that runs as an AppImage, which is offered nothing elseFlatpak-- an update of a Flatpak from its repository, through the Flatpak portal (never in a manifest: Offer::kind of a Flatpak)App-- (macOS) a whole app bundle: a JFA1 bundle of the files of NAME.app relative to it, which replaces the bundle the program runs from (its signature covers the bundle, not only the program); only offered to a program in an app bundle, which is offered nothing else
impl Kind
fn name(self) -> &'static str"exe", "bundle", "package", "appimage", "flatpak" or "app"fn parse(s: &str) -> Option<Kind>the kind of a name (name())struct Packageone file of a manifesttarget: String-- the system it is for (target())kind: Kindurl: String-- as written in the manifest: relative to update.json's address, or absolutesize: u64sha256: [u8; 32]
struct Manifesta parsed update.jsonapp: String-- the app it is for (Config::app)version: Stringdate: i64-- unix seconds (0: not given)expires: i64-- unix seconds after which the manifest is refused (0: never)notes: String-- release notes for the userfiles: Vec<Package>
impl Manifest
fn parse(bytes: &[u8]) -> Result<Manifest, String>parse update.json (format 1; the signature is not checked here) -> the reason when it is malformedfn package(&self, target: &str) -> Option<&Package>the package for a target (the first one)fn package_for(&self, target: &str, appimage: bool) -> Option<&Package>the package for a target and the way the program is installed: the first "appimage" entry for an AppImage (appimage = true), else the first entry of another kindfn verify(bytes: &[u8], sig_text: &[u8], keys: &[[u8; 32]]) -> boolwhether sig_text (update.json.sig: the Base64 Ed25519 signature, blanks around it ignored) signs bytes with one of keysfn target() -> &'static strthe system this program runs on, as the manifest names it: "windows-x86_64", "linux-x86_64", "linux-aarch64", "android-aarch64", "macos-aarch64", "ios-aarch64", "web-wasm32"fn newer(a: &str, b: &str) -> boola is newer than b: the numbers before a '-' compared part by part ("1.10" > "1.9", missing parts are 0, a leading 'v' is ignored); with equal numbers a release is newer than a pre-release ("2.0.0" > "2.0.0-rc1"), pre-releases compare by SemVer's rules (numeric parts as numbers, lower than text parts; more parts win); "+build" is ignored; a version that does not parse is never newer and nothing is newer than it