use std::fs::{self, File}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use anyhow::{bail, Context, Result}; use futures_util::StreamExt; use serde::{Deserialize, Serialize}; const GITEA_LATEST: &str = "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest"; const UPDATE_HOST: &str = "git.lashman.live"; static UPDATE_BUSY: AtomicBool = AtomicBool::new(false); pub(crate) struct UpdateOperation; impl UpdateOperation { pub(crate) fn begin() -> Result { if UPDATE_BUSY.swap(true, Ordering::AcqRel) { bail!("another update operation is in progress"); } Ok(Self) } } impl Drop for UpdateOperation { fn drop(&mut self) { UPDATE_BUSY.store(false, Ordering::Release); } } #[derive(Debug, Clone, Serialize)] pub(crate) struct UpdateInfo { pub version: String, pub current_version: String, pub release_url: String, pub body: String, pub download_url: Option, } #[derive(Debug, Deserialize)] struct GiteaRelease { tag_name: String, body: Option, html_url: String, #[serde(default)] assets: Vec, } #[derive(Debug, Deserialize)] struct GiteaAsset { name: String, browser_download_url: String, } pub(crate) async fn check_for_update() -> Result> { let client = reqwest::Client::builder() .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; let resp = client.get(GITEA_LATEST).send().await?; if !resp.status().is_success() { // A 404 means the endpoint itself is wrong or the repo has no releases - // not that the app is up to date, which is how it reads if this is only // ever a debug line. if resp.status() == reqwest::StatusCode::NOT_FOUND { tracing::warn!("no release published at {GITEA_LATEST}"); } else { tracing::warn!("update check returned status {}", resp.status()); } return Ok(None); } let body = resp.text().await?; let release: GiteaRelease = serde_json::from_str(&body)?; let latest = release.tag_name.trim_start_matches('v').to_string(); let current = env!("CARGO_PKG_VERSION").to_string(); if is_newer(&latest, ¤t) { let download_url = release .assets .iter() .find(|a| a.name.eq_ignore_ascii_case("ByteSize.exe")) .or_else(|| { release .assets .iter() .find(|a| a.name.to_lowercase().ends_with(".exe")) }) .map(|a| a.browser_download_url.clone()); Ok(Some(UpdateInfo { version: latest, current_version: current, release_url: release.html_url, body: release.body.unwrap_or_default(), download_url, })) } else { Ok(None) } } fn is_update_url(url: &reqwest::Url) -> bool { url.scheme() == "https" && url.host_str() == Some(UPDATE_HOST) && url.port_or_known_default() == Some(443) && url.username().is_empty() && url.password().is_none() } pub(crate) async fn download(url: &str, app_dir: &Path, mut on_progress: F) -> Result<()> where F: FnMut(u64, Option) + Send, { let _operation = UpdateOperation::begin()?; let url = reqwest::Url::parse(url).context("parsing update URL")?; if !is_update_url(&url) { bail!("refusing to download an update from {url}"); } let client = reqwest::Client::builder() .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .redirect(reqwest::redirect::Policy::custom(|attempt| { if attempt.previous().len() >= 10 || !is_update_url(attempt.url()) { attempt.error("update redirect left the trusted origin or exceeded the redirect limit") } else { attempt.follow() } })) .build()?; let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); let dest = pending_update_path(app_dir); let staging = StagedUpdate(staged_update_path(&dest)); let mut file = File::create(&staging.0).context("creating staged update file")?; while let Some(chunk) = stream.next().await { let chunk = chunk?; file.write_all(&chunk)?; downloaded += chunk.len() as u64; on_progress(downloaded, total); } if total.is_some_and(|expected| expected != downloaded) { bail!("update download size did not match the response"); } file.sync_all().context("flushing the staged update")?; drop(file); validate_executable(&staging.0).context("checking the staged update")?; fs::rename(&staging.0, dest).context("marking the update ready")?; Ok(()) } struct StagedUpdate(PathBuf); impl Drop for StagedUpdate { fn drop(&mut self) { drop(fs::remove_file(&self.0)); } } fn pending_update_path(app_dir: &Path) -> PathBuf { // The old filename may still hold an incomplete download. app_dir.join("ByteSize.update-ready.exe") } fn staged_update_path(ready: &Path) -> PathBuf { ready.with_extension(format!("exe.{}.part", std::process::id())) } fn validate_executable(path: &Path) -> Result<()> { let mut file = File::open(path)?; let mut magic = [0; 2]; file.read_exact(&mut magic)?; if &magic != b"MZ" { bail!("update is not a Windows executable"); } let mut offset = [0; 4]; file.seek(SeekFrom::Start(0x3c))?; file.read_exact(&mut offset)?; let offset = u32::from_le_bytes(offset); if offset < 64 { bail!("invalid executable header offset"); } file.seek(SeekFrom::Start(u64::from(offset)))?; let mut signature = [0; 4]; file.read_exact(&mut signature)?; if &signature != b"PE\0\0" { bail!("invalid Windows executable signature"); } Ok(()) } fn last_check_path(app_dir: &Path) -> PathBuf { app_dir.join("temp").join("last-update-check") } /// Returns true if the last successful update check happened more than `ttl` /// ago, or never. The stamp file's mtime is the source of truth. pub(crate) fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool { let path = last_check_path(app_dir); let Ok(meta) = fs::metadata(&path) else { return true; }; let Ok(modified) = meta.modified() else { return true; }; let Ok(elapsed) = modified.elapsed() else { return true; }; elapsed > ttl } pub(crate) fn stamp_check(app_dir: &Path) { let path = last_check_path(app_dir); if let Some(parent) = path.parent() { drop(fs::create_dir_all(parent)); } drop(fs::write(&path, b"")); } pub(crate) fn has_pending_update(app_dir: &Path) -> bool { validate_executable(&pending_update_path(app_dir)).is_ok() } pub(crate) fn start_install(app_dir: &Path) -> Result<()> { use std::os::windows::{ffi::OsStringExt, process::CommandExt}; use windows::Win32::System::SystemInformation::GetSystemDirectoryW; use windows::Win32::System::Threading::CREATE_NO_WINDOW; let update = pending_update_path(app_dir); validate_executable(&update).context("no usable pending update")?; let installed = std::env::current_exe().context("finding the running executable")?; let mut system_dir = [0; 512]; // SAFETY: The supplied buffer remains writable through the call. let len = unsafe { GetSystemDirectoryW(Some(&mut system_dir)) }; let system_dir = system_dir .get(..usize::try_from(len)?) .filter(|path| !path.is_empty() && path.len() < system_dir.len()) .context("finding the Windows system directory")?; let powershell = PathBuf::from(std::ffi::OsString::from_wide(system_dir)) .join(r"WindowsPowerShell\v1.0\powershell.exe"); std::process::Command::new(powershell) .args(["-NoProfile", "-NonInteractive", "-Command", APPLY_SCRIPT]) .env("BYTESIZE_UPDATE_PID", std::process::id().to_string()) .env("BYTESIZE_UPDATE_ACTIVE", &installed) .env("BYTESIZE_UPDATE_REPLACEMENT", update) .env( "BYTESIZE_UPDATE_BACKUP", app_dir.join(format!("ByteSize.{}.update-backup.exe", std::process::id())), ) .env("BYTESIZE_UPDATE_LOG", app_dir.join("logs").join("update-apply.log")) .creation_flags(CREATE_NO_WINDOW.0) .spawn() .context("starting update installer")?; Ok(()) } // Pass paths through the environment so they stay out of the script source. // File.Replace keeps a backup until Windows starts the replacement process. const APPLY_SCRIPT: &str = r" $ErrorActionPreference = 'Stop' $active = $env:BYTESIZE_UPDATE_ACTIVE $replacement = $env:BYTESIZE_UPDATE_REPLACEMENT $backup = $env:BYTESIZE_UPDATE_BACKUP $log = $env:BYTESIZE_UPDATE_LOG $replaced = $false try { $previous = Get-Process -Id ([int]$env:BYTESIZE_UPDATE_PID) -ErrorAction SilentlyContinue if ($previous) { Wait-Process -InputObject $previous -Timeout 30 } [IO.File]::Replace($replacement, $active, $backup) $replaced = $true $start = New-Object System.Diagnostics.ProcessStartInfo $start.FileName = $active $start.WorkingDirectory = [IO.Path]::GetDirectoryName($active) $start.UseShellExecute = $false [Diagnostics.Process]::Start($start).Dispose() } catch { $failure = $_ try { if ($replaced) { [IO.File]::Replace($backup, $active, $replacement) Remove-Item -LiteralPath $replacement -ErrorAction SilentlyContinue } elseif (![IO.File]::Exists($active) -and [IO.File]::Exists($backup)) { [IO.File]::Move($backup, $active) } } catch { Add-Content -LiteralPath $log -Value $_ } Add-Content -LiteralPath $log -Value $failure exit 1 } Remove-Item -LiteralPath $backup -ErrorAction SilentlyContinue "; #[derive(Debug, PartialEq, Eq)] struct VersionParts { nums: Vec, pre: Option, } fn parse_version(v: &str) -> VersionParts { let trimmed = v.trim().trim_start_matches('v'); let (core, pre) = trimmed .split_once('-') .map(|(core, pre)| (core, Some(pre.to_ascii_lowercase()))) .unwrap_or((trimmed, None)); let nums = core .split('.') .map(|s| s.parse::().unwrap_or(0)) .collect(); VersionParts { nums, pre } } fn is_newer(latest: &str, current: &str) -> bool { let mut l = parse_version(latest); let mut c = parse_version(current); let max = l.nums.len().max(c.nums.len()); l.nums.resize(max, 0); c.nums.resize(max, 0); if l.nums != c.nums { return l.nums > c.nums; } match (&l.pre, &c.pre) { (None, Some(_)) => true, (Some(a), Some(b)) => a > b, // A prerelease never outranks a stable tag of the same version. (Some(_) | None, None) => false, } } #[cfg(test)] mod tests { use super::{ has_pending_update, is_newer, pending_update_path, staged_update_path, StagedUpdate, }; #[test] fn pending_update_ignores_legacy_and_incomplete_downloads() -> anyhow::Result<()> { let dir = std::env::temp_dir().join(format!("bytesize-update-test-{}", std::process::id())); std::fs::create_dir_all(&dir)?; let staged = StagedUpdate(staged_update_path(&pending_update_path(&dir))); let legacy = StagedUpdate(dir.join("ByteSize.new.exe")); let ready = StagedUpdate(pending_update_path(&dir)); let mut exe = Vec::from(*b"MZ"); exe.resize(60, 0); exe.extend_from_slice(&64u32.to_le_bytes()); exe.extend_from_slice(b"PE\0\0"); std::fs::write(&legacy.0, &exe)?; std::fs::write(&staged.0, &exe)?; assert!(!has_pending_update(&dir)); std::fs::write(&ready.0, b"MZ")?; assert!(!has_pending_update(&dir)); std::fs::rename(&staged.0, &ready.0)?; assert!(has_pending_update(&dir)); drop((staged, legacy, ready)); std::fs::remove_dir(dir)?; Ok(()) } #[test] fn version_major_bump() { assert!(is_newer("2.0.0", "1.9.9")); assert!(!is_newer("1.9.9", "2.0.0")); } #[test] fn version_minor_bump() { assert!(is_newer("1.1.0", "1.0.0")); assert!(!is_newer("1.0.0", "1.1.0")); } #[test] fn version_patch_bump() { assert!(is_newer("1.0.1", "1.0.0")); assert!(!is_newer("1.0.0", "1.0.1")); } #[test] fn version_equal() { assert!(!is_newer("1.0.0", "1.0.0")); } #[test] fn version_different_lengths() { assert!(is_newer("1.0.1", "1.0")); assert!(!is_newer("1.0", "1.0.1")); assert!(is_newer("1.1", "1.0.9")); } #[test] fn version_ignores_extra_text() { assert!(is_newer("1.0.0-beta", "0.9.0")); } #[test] fn stable_is_newer_than_matching_prerelease() { assert!(is_newer("1.0.0", "1.0.0-beta")); assert!(!is_newer("1.0.0-beta", "1.0.0")); } #[test] fn prerelease_compares_when_core_matches() { assert!(is_newer("1.0.0-rc", "1.0.0-beta")); assert!(!is_newer("1.0.0-beta", "1.0.0-rc")); } }