//! Updating Proxy Suite itself: the newest release on the project's Gitea, its setup program //! fetched, checked against the SHA-256 published beside it and run silently, as SYSTEM. The //! setup stops this service, puts the new files in place, and starts the service and the app //! (in the signed-in users' sessions) again. use std::cmp::Ordering; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::time::{Duration, Instant}; use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Value, json}; use crate::fetch::{self, Route}; /// The project's releases. `PROXY_SUITE_UPDATE_URL` in the service's own environment (which /// only an administrator sets) points it at another listing, for tests. const RELEASES: &str = "https://git.faumaray.com/api/v1/repos/faumaray/proxy-suite-flake/releases?limit=30"; /// The Windows port's tags, apart from upstream's `v0.x.0`. const TAG_PREFIX: &str = "windows-v"; /// A setup program is ~80 MB. const MAX_SETUP: usize = 512 << 20; /// One update at a time: when the one under way began. A setup that never stopped this /// service (it failed early) leaves the way open again after a while. static BUSY: Mutex> = Mutex::new(None); const GIVE_UP: Duration = Duration::from_secs(15 * 60); fn begin() -> bool { let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner()); if busy.is_some_and(|t| t.elapsed() < GIVE_UP) { return false; } *busy = Some(Instant::now()); true } fn end() { *BUSY.lock().unwrap_or_else(|e| e.into_inner()) = None; } fn releases_url() -> String { std::env::var("PROXY_SUITE_UPDATE_URL").unwrap_or_else(|_| RELEASES.into()) } /// A release's version: `major.minor.patch`, with `-pre.N` for a pre-release. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Version { major: u64, minor: u64, patch: u64, pre: Option, } impl Version { pub fn parse(s: &str) -> Option { let (core, pre) = match s.split_once('-') { Some((core, pre)) => (core, Some(pre.strip_prefix("pre.")?.parse().ok()?)), None => (s, None), }; let mut parts = core.split('.').map(|p| p.parse::().ok()); let v = Version { major: parts.next()??, minor: parts.next()??, patch: parts.next()??, pre }; parts.next().is_none().then_some(v) } pub fn current() -> Self { Self::parse(env!("CARGO_PKG_VERSION")).expect("the package's version reads") } } impl Ord for Version { fn cmp(&self, other: &Self) -> Ordering { (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch)).then(match (self.pre, other.pre) { (None, None) => Ordering::Equal, // A release is newer than its pre-releases. (None, Some(_)) => Ordering::Greater, (Some(_), None) => Ordering::Less, (Some(a), Some(b)) => a.cmp(&b), }) } } impl PartialOrd for Version { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl std::fmt::Display for Version { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?; match self.pre { Some(n) => write!(f, "-pre.{n}"), None => Ok(()), } } } /// A newer release, with its setup program. #[derive(Debug, Clone, PartialEq)] pub struct Release { pub version: Version, pub page: String, pub notes: String, pub published: String, pub setup: String, pub size: u64, pub checksum: String, } impl Release { pub fn to_json(&self) -> Value { json!({ "version": self.version.to_string(), "page": self.page, "notes": self.notes, "published": self.published, "size": self.size, }) } } /// `scheme://host[:port]` of a URL. fn origin(url: &str) -> Option<&str> { let start = url.find("://")? + 3; let end = url[start..].find(['/', '?', '#']).map_or(url.len(), |i| start + i); (end > start).then(|| &url[..end]) } /// The newest release newer than `current` in a Gitea releases listing. Drafts and other tags /// are left out, pre-releases unless `current` is one (who runs a release stays on releases), /// and a release without its setup program and checksum, or with them on another host than /// the listing's. pub fn newest(list: &Value, current: Version, listing: &str) -> Option { let home = origin(listing)?; list.as_array()? .iter() .filter_map(|r| { if r["draft"] == true { return None; } let version = Version::parse(r["tag_name"].as_str()?.strip_prefix(TAG_PREFIX)?)?; if version <= current || ((r["prerelease"] == true || version.pre.is_some()) && current.pre.is_none()) { return None; } let name = format!("ProxySuite-{version}-windows-x64-setup.exe"); let asset = |n: &str| r["assets"].as_array()?.iter().find(|a| a["name"] == n); let url = |a: &Value| a["browser_download_url"].as_str().filter(|u| origin(u) == Some(home)).map(str::to_owned); let setup = asset(&name)?; Some(Release { version, page: r["html_url"].as_str().unwrap_or_default().to_owned(), notes: r["body"].as_str().unwrap_or_default().to_owned(), published: r["published_at"].as_str().unwrap_or_default().to_owned(), setup: url(setup)?, size: setup["size"].as_u64().unwrap_or(0), checksum: url(asset(&format!("{name}.sha256"))?)?, }) }) .max_by_key(|r| r.version) } /// The first route's answer that comes. async fn first>>(routes: &[Route], each: impl Fn(Route) -> F) -> Result { let mut last = None; for route in routes { match each(route.clone()).await { Ok(v) => return Ok(v), Err(e) => last = Some(e), } } Err(last.unwrap_or_else(|| anyhow!("no way to reach the network"))) } /// The newest release, if there is one newer than this. pub async fn check(routes: &[Route]) -> Result> { let url = releases_url(); let body = first(routes, |r| { let url = url.clone(); async move { fetch::get(&url, &r, 4 << 20).await } }) .await .context("the releases")?; let list: Value = serde_json::from_slice(&body).context("the releases' listing")?; Ok(newest(&list, Version::current(), &url)) } /// The SHA-256 a `.sha256` file holds (`sha256sum`'s line). fn published_sum(text: &[u8]) -> Result { let text = std::str::from_utf8(text).unwrap_or_default(); match text.split_whitespace().next() { Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(h.to_ascii_lowercase()), _ => bail!("the published checksum does not read"), } } /// The release's setup program in `dir` (older ones gone), once its SHA-256 matches. `dir` is /// under the state root, whose protected DACL (SYSTEM and Administrators only, inherited) /// keeps anyone else from replacing the file between this check and its run as SYSTEM. async fn download(release: &Release, routes: &[Route], dir: &Path) -> Result { let sum = first(routes, |r| { let url = release.checksum.clone(); async move { fetch::get(&url, &r, 4096).await } }) .await .context("the setup program's checksum")?; let want = published_sum(&sum)?; let body = first(routes, |r| { let url = release.setup.clone(); async move { fetch::get_large(&url, &r, MAX_SETUP).await } }) .await .context("the setup program")?; if crate::install::hex(&body) != want { bail!("the setup program's SHA-256 is not the one published beside it"); } std::fs::create_dir_all(dir)?; for e in std::fs::read_dir(dir)?.flatten() { let _ = std::fs::remove_file(e.path()); } let path = dir.join(format!("ProxySuite-{}-windows-x64-setup.exe", release.version)); crate::paths::write_atomic(&path, &body).with_context(|| format!("writing {}", path.display()))?; Ok(path) } /// What `install` leaves for the service that the setup starts: the version it went for. const PENDING: &str = "pending"; /// Fetches the newest release's setup program and runs it, a moment after this returns (so /// the caller hears of it before the setup stops the service). pub async fn install(routes: &[Route], dir: &Path) -> Result { if !begin() { bail!("an update is under way already"); } let r = async { let release = check(routes).await?.ok_or_else(|| anyhow!("this is the newest release ({})", env!("CARGO_PKG_VERSION")))?; tracing::info!("update: fetching {}", release.version); let setup = download(&release, routes, dir).await?; std::fs::write(dir.join(PENDING), release.version.to_string())?; run_later(setup); Ok(release) } .await; if r.is_err() { end(); } r } fn run_later(setup: PathBuf) { tokio::spawn(async move { tokio::time::sleep(Duration::from_secs(1)).await; tracing::info!("update: running {}", setup.display()); if let Err(e) = run(&setup) { tracing::error!("update: {e:#}"); let _ = std::fs::remove_file(setup.with_file_name(PENDING)); end(); } }); } /// The setup, silent, on its own: out of any job this process is in, and of its console, as it /// outlives the service it stops. #[cfg(windows)] fn run(setup: &Path) -> Result<()> { use std::os::windows::process::CommandExt; const DETACHED_PROCESS: u32 = 0x8; const CREATE_NEW_PROCESS_GROUP: u32 = 0x200; const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000; let spawn = |flags: u32| { std::process::Command::new(setup) .arg("/S") .current_dir(setup.parent().unwrap_or(Path::new("."))) .creation_flags(flags) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .spawn() }; // A job that allows no breakaway refuses the flag; none to break away from ignores it. spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB) .or_else(|_| spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)) .context("starting the setup program")?; Ok(()) } #[cfg(not(windows))] fn run(setup: &Path) -> Result<()> { bail!("{} is a Windows setup program; not run here", setup.display()) } /// Said once in the log at start: whether the update `install` went for is the version now /// running. pub fn report(dir: &Path) { let path = dir.join(PENDING); let Ok(wanted) = std::fs::read_to_string(&path) else { return }; let _ = std::fs::remove_file(&path); if wanted.trim() == env!("CARGO_PKG_VERSION") { tracing::info!("updated to {}", env!("CARGO_PKG_VERSION")); // Done with: ~80 MB. for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { let _ = std::fs::remove_file(e.path()); } } else { tracing::warn!("the update to {} did not finish; this is still {}", wanted.trim(), env!("CARGO_PKG_VERSION")); } } #[cfg(test)] mod tests { use super::*; fn v(s: &str) -> Version { Version::parse(s).unwrap() } #[test] fn versions_order_as_releases() { assert!(v("0.3.0-pre.1") > v("0.2.0-pre.1")); assert!(v("0.3.0-pre.2") > v("0.3.0-pre.1")); assert!(v("0.3.0") > v("0.3.0-pre.9")); assert!(v("0.10.0") > v("0.9.1")); assert_eq!(v("1.2.3-pre.4").to_string(), "1.2.3-pre.4"); for bad in ["0.3", "0.3.0.1", "0.3.0-rc.1", "x.1.2", "0.3.0-pre."] { assert_eq!(Version::parse(bad), None, "{bad}"); } assert_eq!(Version::current().to_string(), env!("CARGO_PKG_VERSION")); } fn release(tag: &str, pre: bool, host: &str) -> Value { let v = tag.trim_start_matches(TAG_PREFIX); let name = format!("ProxySuite-{v}-windows-x64-setup.exe"); json!({ "tag_name": tag, "prerelease": pre, "draft": false, "body": "notes", "html_url": format!("{host}/r/{tag}"), "assets": [ { "name": name, "size": 5, "browser_download_url": format!("{host}/d/{tag}/{name}") }, { "name": format!("{name}.sha256"), "size": 1, "browser_download_url": format!("{host}/d/{tag}/{name}.sha256") }, ], }) } const HOME: &str = "https://git.example"; const LIST: &str = "https://git.example/api/v1/repos/o/r/releases?limit=30"; #[test] fn the_newest_release_with_a_setup_program() { let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.3.0-pre.1", true, HOME), release("v0.9.0", false, HOME)]); let r = newest(&list, v("0.3.0-pre.1"), LIST).unwrap(); assert_eq!(r.version, v("0.3.0-pre.2")); assert_eq!(r.setup, "https://git.example/d/windows-v0.3.0-pre.2/ProxySuite-0.3.0-pre.2-windows-x64-setup.exe"); assert!(r.checksum.ends_with(".exe.sha256")); // Nothing newer. assert_eq!(newest(&list, v("0.3.0-pre.2"), LIST), None); // Who runs a release is not offered pre-releases, but a newer release. assert_eq!(newest(&list, v("0.2.0"), LIST), None); let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.2.1", false, HOME)]); assert_eq!(newest(&list, v("0.2.0"), LIST).unwrap().version, v("0.2.1")); assert_eq!(newest(&list, v("0.2.0-pre.1"), LIST).unwrap().version, v("0.3.0-pre.2")); } #[test] fn drafts_strangers_and_releases_without_a_setup_are_passed_over() { let mut draft = release("windows-v0.4.0", false, HOME); draft["draft"] = true.into(); let elsewhere = release("windows-v0.5.0", false, "https://evil.example"); let mut zip_only = release("windows-v0.6.0", false, HOME); zip_only["assets"].as_array_mut().unwrap().remove(0); let mut no_sum = release("windows-v0.7.0", false, HOME); no_sum["assets"].as_array_mut().unwrap().remove(1); let list = json!([draft, elsewhere, zip_only, no_sum, release("windows-v0.3.1", false, HOME)]); assert_eq!(newest(&list, v("0.3.0"), LIST).unwrap().version, v("0.3.1")); // http is another origin than https. let list = json!([release("windows-v0.3.1", false, "http://git.example")]); assert_eq!(newest(&list, v("0.3.0"), LIST), None); } #[test] fn origins_and_checksums_read() { assert_eq!(origin("https://h.example:3000/a/b?c"), Some("https://h.example:3000")); assert_eq!(origin("https://h.example?x"), Some("https://h.example")); assert_eq!(origin("https://"), None); let h = "3ff31008aa1d9f4e".repeat(4); assert_eq!(published_sum(format!("{h} ProxySuite-0.2.0-pre.1-windows-x64-setup.exe\n").as_bytes()).unwrap(), h); assert!(published_sum(b"not a sum").is_err()); } }