use std::fs::{self, File}; use std::io::{self, Read}; use std::ops::ControlFlow; use std::path::{Path, PathBuf}; use std::time::Duration; use base64::prelude::{BASE64_STANDARD, Engine}; use ring::{digest, signature}; use serde::Deserialize; use ureq::Agent; use crate::{Error, SourceError, UpdateChannel}; /// Bounds what a source can write to disk: a full package is a few tens of MiB. const MAX_DOWNLOAD: u64 = 256 << 20; /// A connection or a read that stalls this long fails; a slow download does not. const STALL: Duration = Duration::from_secs(30); /// Suffix of the file `-.attempt`, written next to a kept package's folder when /// the package is handed to the installer. It holds the installer's process id, `REPORTED` once /// a failure was shown, or anything else when the launch stopped before knowing the process. /// It outlives a new download of the same version (Velopack deletes a package it cannot open): /// no launch retries that version on its own, only « Redémarrer » does. const ATTEMPT: &str = ".attempt"; const REPORTED: &str = "reported"; #[derive(Deserialize)] struct Manifest { app: String, target: String, channel: String, version: String, commit: String, package: String, sha256: String, } /// Verifies a release folder: the signed manifest, then the digest of the package read as a plain /// byte stream, never as an archive. Returns the authenticated source commit. /// Callers must keep these bytes isolated until success, then apply exactly these bytes. pub fn verify_release( dir: &Path, public_key: &[u8], channel: &str, version: &str, ) -> Result { let rejected = |why: String| Error::InvalidUpdate(why); let open = |name: &str| { File::open(dir.join(name)).map_err(|e| rejected(format!("{name} illisible ({e})"))) }; let read = |name: &str, limit: u64| { let mut bytes = Vec::new(); open(name)? .take(limit + 1) .read_to_end(&mut bytes) .map_err(|e| rejected(format!("{name} illisible ({e})")))?; if bytes.len() as u64 > limit { return Err(rejected(format!("{name} trop volumineux"))); } Ok(bytes) }; let manifest = read(&format!("release-{channel}.json"), 4096)?; let signed = read(&format!("release-{channel}.sig"), 64)?; signature::UnparsedPublicKey::new(&signature::ED25519, public_key) .verify(&manifest, &signed) .map_err(|_| rejected("signature invalide".into()))?; let release: Manifest = serde_json::from_slice(&manifest) .map_err(|e| rejected(format!("manifeste illisible ({e})")))?; let package = format!("ArenaTracker-{version}-{channel}-full.nupkg"); if release.app != "ArenaTracker" || release.target != "win-x64" || release.channel != channel || release.version != version || release.package != package { return Err(rejected("identité inattendue".into())); } let mut file = open(&package)?; let mut hash = digest::Context::new(&digest::SHA256); let mut buffer = [0; 64 * 1024]; loop { let n = file .read(&mut buffer) .map_err(|e| rejected(format!("{package} illisible ({e})")))?; if n == 0 { break; } hash.update(&buffer[..n]); } if release.sha256 != BASE64_STANDARD.encode(hash.finish().as_ref()) { return Err(rejected("condensat du paquet différent".into())); } Ok(release.commit) } #[derive(Deserialize)] struct Release { assets: Vec, } #[derive(Deserialize)] struct Asset { name: String, browser_download_url: String, } /// Orders `X.Y.Z` after its betas and `beta.2` before `beta.10`; `None` for any other form. fn version_order(version: &str) -> Option<[u64; 4]> { let number = |text: &str| text.parse::().ok().filter(|n| n.to_string() == text); let (core, beta) = match version.split_once("-beta.") { Some((core, n)) => (core, number(n).filter(|n| (1..u64::MAX).contains(n))?), None => (version, u64::MAX), }; let mut parts = core.split('.').map(number); let order = [parts.next()??, parts.next()??, parts.next()??, beta]; parts.next().is_none().then_some(order) } /// The order of `version` when `channel` takes it over `installed`: above it, and of its kind. fn newer(version: &str, installed: [u64; 4], channel: UpdateChannel) -> Option<[u64; 4]> { let order = version_order(version)?; // Betas end below u64::MAX, stables at it: a channel only takes its own versions. let beta = channel == UpdateChannel::Beta; (order > installed && (order[3] < u64::MAX) == beta).then_some(order) } /// The newest package folder of `channel` kept in `dir` above `installed`, with its version. /// Another channel's folder, which a check may not have removed yet, never counts. fn kept_update(dir: &Path, channel: UpdateChannel, installed: &str) -> Option<(String, PathBuf)> { let installed = version_order(installed)?; let prefix = format!("{}-", channel.name()); fs::read_dir(dir) .ok()? .flatten() .filter_map(|entry| { let name = entry.file_name().into_string().ok()?; let version = name.strip_prefix(&prefix)?; Some(( newer(version, installed, channel)?, version.to_owned(), entry.path(), )) }) .max_by_key(|(order, ..)| *order) .map(|(_, version, folder)| (version, folder)) } /// The attempt record of the kept package folder `folder` (see `ATTEMPT`). fn attempt_file(folder: &Path) -> PathBuf { let mut path = folder.as_os_str().to_owned(); path.push(ATTEMPT); path.into() } /// Authenticates the kept package in `folder` again, then hands exactly that file to `start`, /// which starts the installer on it and returns the installer's process id. fn hand_over( folder: &Path, public_key: &[u8], channel: UpdateChannel, version: &str, start: impl FnOnce(&Path) -> io::Result, ) -> Result<(), Error> { let name = channel.name(); verify_release(folder, public_key, name, version)?; let attempt = attempt_file(folder); // Written first: whatever happens next, no launch retries this package on its own. fs::write(&attempt, "").map_err(storage)?; let package = folder.join(format!("ArenaTracker-{version}-{name}-full.nupkg")); let installer = start(&package).map_err(|_| { let _ = fs::write(&attempt, REPORTED); Error::UpdateFailed(version.into()) })?; // Lets a launch during the installation wait for it rather than report a failure. let _ = fs::write(&attempt, installer.to_string()); Ok(()) } /// Runs before the app loads, by the single instance only. Hands the kept package of `channel` /// above `installed` to the installer once, through `start` (see `hand_over`). `outcome` waits /// for the installer process with the given id and returns its exit code, or `None` when no such /// installer runs any more. `Break`: the installer replaces this version and opens the app. /// `Continue`: load the app, showing the error if there is one. A failed attempt is reported /// once and never retried from here, so a failing update cannot keep the app from opening. pub fn update_at_launch( dir: &Path, public_key: &[u8], channel: UpdateChannel, installed: &str, start: impl FnOnce(&Path) -> io::Result, outcome: impl FnOnce(u32) -> Option, ) -> ControlFlow<(), Option> { let Some((version, folder)) = kept_update(dir, channel, installed) else { return ControlFlow::Continue(None); }; let attempt = attempt_file(&folder); let text = match fs::read_to_string(&attempt) { Err(error) if error.kind() == io::ErrorKind::NotFound => { return match hand_over(&folder, public_key, channel, &version, start) { Ok(()) => ControlFlow::Break(()), Err(error) => ControlFlow::Continue(Some(error)), }; } // Unreadable: never retried from here, and nothing more is known. Err(_) => return ControlFlow::Continue(None), Ok(text) => text, }; if text == REPORTED { return ControlFlow::Continue(None); } // Launched during the installation, or by the installer itself once it is over. if let Ok(installer) = text.parse() && outcome(installer) == Some(0) { return ControlFlow::Break(()); } let _ = fs::write(&attempt, REPORTED); ControlFlow::Continue(Some(Error::UpdateFailed(version))) } /// « Redémarrer »: hands the kept package of `channel` above `installed` to the installer like /// `update_at_launch`, even after a failed attempt. The app must then quit for the installer. pub fn restart_to_update( dir: &Path, public_key: &[u8], channel: UpdateChannel, installed: &str, start: impl FnOnce(&Path) -> io::Result, ) -> Result<(), Error> { let (version, folder) = kept_update(dir, channel, installed) .ok_or_else(|| Error::InvalidUpdate("paquet introuvable".into()))?; hand_over(&folder, public_key, channel, &version, start) } /// Removes the entries of `dir` whose name `matches`, as far as it can: an entry another program /// holds open stays until a later check, and must not hide an authenticated package. fn remove_entries(dir: &Path, matches: impl Fn(&str) -> bool) { for entry in fs::read_dir(dir).into_iter().flatten().flatten() { if matches(&entry.file_name().to_string_lossy()) { let _ = if entry.file_type().is_ok_and(|kind| kind.is_dir()) { fs::remove_dir_all(entry.path()) } else { fs::remove_file(entry.path()) }; } } } /// Keeps the newest release of `channel` above `installed` downloaded and authenticated in /// `dir/-` and returns its version, or `None` when there is none. Anything /// else in `dir` but that version's attempt record is removed; another channel's package goes /// before any network access, so it can /// never be taken for this channel's. Bytes are downloaded into `dir/partial` and renamed only /// once `verify_release` accepts them. A kept package is verified again instead of downloaded. /// `releases_url` is a Gitea releases API endpoint, where betas are pre-releases. /// One call at a time per `dir`. pub fn download_update( releases_url: &str, dir: &Path, public_key: &[u8], channel: UpdateChannel, installed: &str, ) -> Result, Error> { let installed = version_order(installed) .ok_or_else(|| Error::InvalidUpdate("version installée illisible".into()))?; let name = channel.name(); fs::create_dir_all(dir).map_err(storage)?; remove_entries(dir, |entry| !entry.starts_with(&format!("{name}-"))); let agent: Agent = Agent::config_builder() .http_status_as_error(false) .user_agent("arena-tracker") .timeout_connect(Some(STALL)) .timeout_per_read(Some(STALL)) .build() .into(); let get = |url: &str| { let response = agent.get(url).call().map_err(network)?; match response.status().as_u16() { 200..=299 => Ok(response), status => Err(network(format!("HTTP {status}"))), } }; let beta = channel == UpdateChannel::Beta; let list = get(&format!( "{releases_url}?draft=false&pre-release={beta}&limit=10" ))? .into_body() .read_to_string() .map_err(network)?; let releases: Vec = serde_json::from_str(&list) .map_err(|e| Error::InvalidUpdate(format!("liste des versions illisible ({e})")))?; let manifest_files = [ format!("release-{name}.json"), format!("release-{name}.sig"), ]; let newest = releases .iter() .filter_map(|release| { let has = |file: &str| release.assets.iter().any(|asset| asset.name == file); let version = release.assets.iter().find_map(|asset| { let rest = asset.name.strip_prefix("ArenaTracker-")?; rest.strip_suffix(&format!("-{name}-full.nupkg")) })?; let order = newer(version, installed, channel)?; let complete = manifest_files.iter().all(|file| has(file)); complete.then_some((order, version, release)) }) .max_by_key(|(order, ..)| *order); let Some((_, version, release)) = newest else { remove_entries(dir, |_| true); return Ok(None); }; let kept = format!("{name}-{version}"); let attempt = format!("{kept}{ATTEMPT}"); let others = |entry: &str| entry != kept && entry != attempt; if verify_release(&dir.join(&kept), public_key, name, version).is_ok() { remove_entries(dir, others); return Ok(Some(version.into())); } // An older package of this channel stays until the newer one is ready. remove_entries(dir, |entry| entry == kept); let partial = dir.join("partial"); fs::create_dir(&partial).map_err(storage)?; let package = format!("ArenaTracker-{version}-{name}-full.nupkg"); let downloaded = manifest_files .iter() .chain([&package]) .try_for_each(|file| { let asset = release.assets.iter().find(|asset| &asset.name == file); let asset = asset.ok_or_else(|| Error::InvalidUpdate(format!("{file} absent")))?; // verify_release reads at most 4 KiB of manifest and 64 bytes of signature. let limit = if file == &package { MAX_DOWNLOAD } else { 4096 }; let mut body = get(&asset.browser_download_url)?.into_body(); let mut reader = body.with_config().limit(limit).reader(); let mut target = File::create(partial.join(file)).map_err(storage)?; std::io::copy(&mut reader, &mut target) .map_err(|e| Error::InvalidUpdate(format!("{file} incomplet ({e})")))?; Ok(()) }); if let Err(error) = downloaded.and_then(|()| verify_release(&partial, public_key, name, version)) { let _ = fs::remove_dir_all(&partial); return Err(error); } fs::rename(&partial, dir.join(&kept)).map_err(storage)?; remove_entries(dir, others); Ok(Some(version.into())) } fn network(error: impl ToString) -> Error { Error::Source(SourceError::Network(error.to_string())) } fn storage(error: std::io::Error) -> Error { Error::Storage(error.to_string()) }