JFLib

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 Config what the updater needs to know about the app
    • app: String -- the app's id as the manifest names it ("app")
    • version: String -- the running version
    • url: 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 CA
    • timeout_ms: u32 -- the longest wait for the server (ms; default 60000)

impl Config

  • fn new(app: &str, version: &str, url: &str, keys: &[&str]) -> Config the 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 defaults

  • enum Error why a step failed

    • Config(String) -- no channel, no valid key or an invalid address
    • Denied(String) -- the app's PERMISSIONS do not allow the host (net.connect)
    • Net(String) -- connection or protocol failure
    • Tls(String) -- the TLS layer refused: the certificate or the handshake
    • TooLarge(String) -- the answer is over the limit fetch::get was given
    • Http(u16) -- the server answered with another status than 200 / 206
    • Signature -- the signature of update.json matches no trusted key
    • Manifest(String) -- update.json is malformed or for another app
    • Expired -- the manifest's "expires" has passed
    • Replay(String) -- the manifest is older than one seen before (its version)
    • Size { expected: u64, got: u64 } -- the file has not the size of the manifest
    • Hash -- the file's SHA-256 is not the manifest's
    • Incomplete { done: u64, total: u64 } -- the connection ended early; what arrived is kept and the next download continues it
    • Cancelled -- stopped by cancel()
    • Busy -- another check, download or apply runs (this process or another one)
    • Nothing -- nothing to download or to apply
    • Unsupported(String) -- a package that is not put in place by the updater
    • Io(String) -- files could not be read or written
    • ReadOnly(String) -- the AppImage or the macOS app bundle lies in a folder the user cannot write (the folder): it is not replaced
    • Rejected(String) -- the downloaded package is not taken: not an AppImage, or its signature does not follow the running one's (why)
  • struct Offer a newer version the channel offers

    • version: String
    • notes: String
    • date: i64 -- unix seconds (0: not given)
    • size: u64 -- the package's size in bytes
    • kind: Kind
    • staged: bool -- it is downloaded already (staged)
  • enum Check the answer of a check

    • UpToDate -- 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 them
    • Available(Offer) -- a newer version to download
    • Managed(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 Manager who 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 it
    • Flatpak -- Flatpak (flatpak update, a software centre): the portal's update monitor is missing
    • Snap -- snapd
  • enum Startup what startup() did

    • Normal -- nothing to do
    • Applied(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 works
    • RollingBack(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 Phase what an Updater is doing

    • Idle
    • Checking
    • UpToDate -- the last check found nothing newer
    • Available -- a newer version can be downloaded (Status::version)
    • Downloading
    • Ready -- downloaded and checked: put in place at the next start or by apply()
    • Failed -- the last step failed (Status::error)
  • struct Status the state for a dialog or a status line

    • phase: Phase
    • version: String -- the offered or downloaded version
    • notes: String
    • done: u64 -- bytes downloaded and the file's size
    • total: u64
    • error: Option<Error>
  • struct Updater checks and downloads for one Config; clones share the same state

impl Updater

  • fn new(cfg: Config) -> Updater an updater for cfg; a downloaded update (stage Staged) starts it in Phase::Ready

  • fn config(&self) -> &Config the configuration it was made with

  • fn status(&self) -> Status the current phase, progress and last error

  • fn 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 version

  • fn start_check(&self) -> bool check() on a background thread; plat::wake() (UIC_WAKE / E_WAKE) when it is done -> false while another background step runs

  • fn start_download(&self) -> bool download() on a background thread; plat::wake() when it is done -> false while another background step runs

  • fn busy(&self) -> bool whether a background step runs

  • fn 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 one

  • fn install(cfg: &Config) -> Packaged how the running program is installed, which decides what an update is (cfg.exe set: Plain -- an explicit program file)

  • fn startup(cfg: &Config) -> Startup at 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) -> bool the 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 Signed what an AppImage's signature sections say

    • No -- not signed (no sections, or empty ones)
    • By { signer: [u8; 20], keys: Vec<[u8; 20]> } -- signed by signer (a key of the embedded block, whose fingerprints are keys)
  • 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 Stage where an update stands

    • None -- nothing pending
    • Staged -- 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 State the file cfg.dir/state

    • stage: Stage
    • version: String -- the staged, new or rolled-back version
    • from: String -- the version that was running before it
    • starts: u32 -- starts of the new version without healthy()
    • kind: String -- what the staged file is
    • file: String -- the staged file's name in staged/
    • bad: Vec<String> -- versions that were rolled back: never offered again
    • seen: String -- the newest version a signed manifest named (older manifests are refused: replay)
  • fn state(cfg: &Config) -> State the 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 it

    • done: &'a AtomicU64
    • total: &'a AtomicU64
    • cancel: &'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 folder

  • fn 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 bytes

  • fn 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 exactly size bytes 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 Kind what a package of the manifest is
    • Exe -- the program file itself
    • Bundle -- a JFA1 bundle (tools/assetpack.py) of files relative to the program's folder
    • Package -- an installer (.deb, setup): downloaded and checked, installed by the app or the user
    • AppImage -- a whole AppImage: replaces the running AppImage's file ($APPIMAGE); only offered to a program that runs as an AppImage, which is offered nothing else
    • Flatpak -- 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 Package one file of a manifest

    • target: String -- the system it is for (target())
    • kind: Kind
    • url: String -- as written in the manifest: relative to update.json's address, or absolute
    • size: u64
    • sha256: [u8; 32]
  • struct Manifest a parsed update.json

    • app: String -- the app it is for (Config::app)
    • version: String
    • date: i64 -- unix seconds (0: not given)
    • expires: i64 -- unix seconds after which the manifest is refused (0: never)
    • notes: String -- release notes for the user
    • files: 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 malformed

  • fn 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 kind

  • fn verify(bytes: &[u8], sig_text: &[u8], keys: &[[u8; 32]]) -> bool whether sig_text (update.json.sig: the Base64 Ed25519 signature, blanks around it ignored) signs bytes with one of keys

  • fn target() -> &'static str the 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) -> bool a 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

Source: docs/API.md in the JFLib repository.