diff --git a/src-tauri/src/bootstrap.rs b/src-tauri/src/bootstrap.rs index 40bd30e..cff0d36 100644 --- a/src-tauri/src/bootstrap.rs +++ b/src-tauri/src/bootstrap.rs @@ -41,37 +41,26 @@ struct Source { release_api_url: &'static str, asset_name_suffix: &'static str, kind: ArchiveKind, - /// Release download directory, used to fetch the sibling `.sha256`. None - /// when the project publishes no checksums at all. - download_base: Option<&'static str>, + } -// `releases/latest` rather than `releases/tags/latest` for both: the latter -// only resolves for a repo that happens to have a tag literally named "latest", -// which GyanD does not - its tag is the version, so that URL 404s. -// -// BtbN is first because its zip is the path that actually installs today; the -// 7z branch below is the fallback. const SOURCES: &[Source] = &[ - Source { - name: "BtbN", - release_api_url: "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/latest", - asset_name_suffix: "win64-gpl.zip", - kind: ArchiveKind::Zip, - download_base: None, - }, Source { name: "GyanD", release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/latest", asset_name_suffix: "full_build.7z", kind: ArchiveKind::SevenZ, - download_base: Some("https://github.com/GyanD/codexffmpeg/releases/download"), + }, + Source { + name: "FFmpeg Builds", + release_api_url: "https://api.github.com/repos/FFmpeg-Builds/FFmpeg-Builds/releases/latest", + asset_name_suffix: "win64-gpl.zip", + kind: ArchiveKind::Zip, }, ]; #[derive(Debug, Deserialize)] struct GithubRelease { - tag_name: String, assets: Vec, } @@ -79,6 +68,7 @@ struct GithubRelease { struct GithubAsset { name: String, browser_download_url: String, + digest: Option, } pub(crate) async fn download(app_dir: &Path, mut on_progress: F) -> Result<()> @@ -110,36 +100,13 @@ where F: FnMut(u64, Option), { let client = reqwest::Client::builder() + .https_only(true) .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; - let (asset, version) = pick_asset(&client, source).await?; - - // Verify against the published checksum when there is one. GyanD used to - // ship a .sha256 next to each asset and no longer does, so a missing - // checksum downgrades to a logged warning rather than failing the source - - // aborting on it would just push the user onto the unverified build anyway. - let expected = if let Some(base) = source.download_base { - let checksum_url = format!("{base}/{version}/{}.sha256", asset.name); - match fetch_sha256(&client, &checksum_url).await { - Ok(hash) => Some(hash), - Err(e) => { - tracing::warn!( - "{} publishes no usable checksum for {} ({e:#}), continuing unverified", - source.name, - asset.name - ); - None - } - } - } else { - tracing::warn!( - "{} publishes no checksums, downloading {} unverified", - source.name, - asset.name - ); - None - }; + let asset = pick_asset(&client, source).await?; + let expected = parse_sha256(asset.digest.as_deref()) + .with_context(|| format!("no valid published SHA-256 for {}", asset.name))?; let app_dir = dest .parent() @@ -150,96 +117,28 @@ where let archive_path = scratch_dir.join(format!("ffmpeg-archive-{}.tmp", source.name.to_lowercase())); - if let Some(ref hash) = expected { - download_verified( - &client, - &asset.browser_download_url, - hash, - &archive_path, - on_progress, - ) - .await - .with_context(|| format!("downloading {}", asset.browser_download_url))?; - } else { - download_plain( - &client, - &asset.browser_download_url, - &archive_path, - on_progress, - ) - .await - .with_context(|| format!("downloading {}", asset.browser_download_url))?; - } - - let result = match source.kind { + let result = download_verified( + &client, &asset.browser_download_url, &expected, &archive_path, on_progress, + ) + .await + .with_context(|| format!("downloading {}", asset.browser_download_url)) + .and_then(|()| match source.kind { ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest), ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest), - }; + }); drop(fs::remove_file(&archive_path)); result } -/// Fetch and parse a SHA-256 checksums file from `GyanD`. -/// The file contains a line like: -/// abc123def456... ffmpeg-8.1.1-full_build.7z -async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> { - let resp = client.get(url).send().await?.error_for_status()?; - let text = resp.text().await?; - // Each line is: " " - find the line with our filename - let hash_str = text - .lines() - .find_map(|line| { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - return None; - } - // SHA-256 hex is 64 chars, followed by spaces and the filename - if line.len() < 64 { - return None; - } - let (hash, file) = line.split_at(64); - let remainder = file.trim_start(); - // Must be followed by two spaces and a filename - if !remainder.starts_with(" ") { - return None; - } - Some(hash) - }) - .ok_or_else(|| anyhow!("SHA-256 for this build not found in checksums file"))?; - let bytes = hex::decode(hash_str).context("checksum is not valid hex")?; - if bytes.len() != 32 { - bail!("checksum length is {} bytes, expected 32", bytes.len()); - } - let mut sha = [0u8; 32]; - sha.copy_from_slice(&bytes); - Ok(sha) +fn parse_sha256(digest: Option<&str>) -> Result<[u8; 32]> { + let hash = digest.and_then(|value| value.strip_prefix("sha256:")) + .context("release metadata does not contain a SHA-256 digest")?; + let mut bytes = [0; 32]; + hex::decode_to_slice(hash, &mut bytes).context("invalid SHA-256 digest")?; + Ok(bytes) } -async fn download_plain( - client: &reqwest::Client, - url: &str, - dest: &Path, - mut on_progress: F, -) -> Result<()> -where - F: FnMut(u64, Option), -{ - let resp = client.get(url).send().await?.error_for_status()?; - let total = resp.content_length(); - let mut file = File::create(dest).context("creating archive temp file")?; - let mut downloaded = 0u64; - let mut stream = resp.bytes_stream(); - while let Some(chunk) = stream.next().await { - let chunk = chunk?; - file.write_all(&chunk)?; - downloaded += chunk.len() as u64; - on_progress(downloaded, total); - } - file.flush()?; - Ok(()) -} - -async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> { +async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result { let resp = client .get(source.release_api_url) .header("Accept", "application/vnd.github+json") @@ -248,8 +147,7 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(Github .error_for_status()?; let body = resp.text().await?; let release: GithubRelease = serde_json::from_str(&body).context("parsing release metadata")?; - let version = release.tag_name.trim_start_matches('v').to_string(); - let asset = release + release .assets .into_iter() .find(|a| a.name.ends_with(source.asset_name_suffix)) @@ -258,8 +156,7 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(Github "no asset matching '*{}' in release", source.asset_name_suffix ) - })?; - Ok((asset, version)) + }) } async fn download_verified( @@ -288,7 +185,6 @@ where file.flush()?; let got: [u8; 32] = hasher.finalize().into(); if &got != expected { - drop(fs::remove_file(dest)); bail!( "sha256 mismatch: expected {} got {}", hex::encode(expected), @@ -333,13 +229,8 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> { let _guard = DirGuard(scratch.clone()); let file = File::open(archive_path).context("opening 7z archive")?; - let extract_result = - sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true)) - .map_err(|e| anyhow!("7z extraction failed: {e}")); - let found = find_ffmpeg_in(&scratch); - - extract_result?; - let Some(src) = found else { + sevenz_rust2::decompress(file, &scratch).map_err(|e| anyhow!("7z extraction failed: {e}"))?; + let Some(src) = find_ffmpeg_in(&scratch) else { bail!("ffmpeg.exe not found inside the 7z archive"); }; install_from(dest, |staging| { @@ -407,6 +298,16 @@ fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> { mod tests { use super::*; + #[test] + fn sha256_digest_must_be_present_complete_and_valid() -> Result<()> { + let hex = "ab".repeat(32); + assert_eq!(parse_sha256(Some(&format!("sha256:{hex}")))?, [0xab; 32]); + assert!(parse_sha256(Some("sha256:abcd")).is_err()); + assert!(parse_sha256(Some(&hex)).is_err()); + assert!(parse_sha256(None).is_err()); + Ok(()) + } + /// Stands in for the body of `extract_ffmpeg_from_7z`: it builds a scratch /// directory, arms the guard, then leaves through the `?` the way a failed /// extraction does. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d6d93f3..29ac4c0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -275,9 +275,8 @@ async fn download_update( state: State<'_, AppState>, url: String, ) -> Result<(), String> { - let dest = updates::pending_update_path(&state.app_dir); let app_handle = app.clone(); - updates::download_to(&url, &dest, move |downloaded, total| { + updates::download(&url, &state.app_dir, move |downloaded, total| { drop(app_handle.emit( "update-download-progress", UpdateDownloadProgress { downloaded, total }, @@ -295,17 +294,12 @@ async fn download_update( )] #[tauri::command] fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { - use std::os::windows::process::CommandExt; - use std::process::Command; - if !updates::has_pending_update(&state.app_dir) { - return Err("no pending update to apply".to_string()); + if lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst) + { + return Err("finish or discard the current recording before applying the update".to_string()); } - let bat = updates::write_apply_script(&state.app_dir).map_err(|e| format!("{e:#}"))?; - Command::new("cmd") - .args(["/c", "start", "", ""]) - .raw_arg(format!("\"{}\"", bat.to_string_lossy())) - .spawn() - .map_err(|e| format!("spawning apply script: {e:#}"))?; + let _operation = updates::UpdateOperation::begin().map_err(|e| format!("{e:#}"))?; + updates::start_install(&state.app_dir).map_err(|e| format!("{e:#}"))?; app.exit(0); Ok(()) } @@ -1925,18 +1919,38 @@ fn reveal_in_explorer(path: String) -> Result<(), String> { Ok(()) } +fn open_shell_target(target: &std::ffi::OsStr) -> Result<(), String> { + use windows::core::{w, HSTRING, PCWSTR}; + use windows::Win32::UI::Shell::ShellExecuteW; + use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; + + let target = HSTRING::from(target); + // SAFETY: Both NUL-terminated strings outlive the call. + let result = unsafe { + ShellExecuteW( + None, + w!("open"), + &target, + PCWSTR::null(), + PCWSTR::null(), + SW_SHOWNORMAL, + ) + }; + // ShellExecuteW returns an error code when the result is 32 or lower. + let code = result.0 as isize; + if code <= 32 { + return Err(format!("opening the target failed (Windows shell error {code})")); + } + Ok(()) +} + #[tauri::command] fn open_url(url: String) -> Result<(), String> { - use std::os::windows::process::CommandExt; - - if !url.starts_with("http://") && !url.starts_with("https://") { + let url = reqwest::Url::parse(&url).map_err(|e| format!("invalid URL: {e}"))?; + if !matches!(url.scheme(), "http" | "https") || !url.has_host() { return Err("only http/https URLs are supported".to_string()); } - std::process::Command::new("cmd") - .raw_arg(format!("/C start \"\" \"{url}\"")) - .spawn() - .map_err(|e| format!("opening url: {e:#}"))?; - Ok(()) + open_shell_target(std::ffi::OsStr::new(url.as_str())) } #[derive(Debug, Serialize)] diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index 06887d1..7a259ab 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -1,4 +1,7 @@ +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; @@ -6,10 +9,25 @@ use serde::{Deserialize, Serialize}; const GITEA_LATEST: &str = "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest"; -/// Everything the updater will fetch has to live under this prefix. The download -/// URL arrives from the frontend, and an unconstrained one there would let -/// anything that can reach the webview hand the app a new executable to install. -const UPDATE_ORIGIN: &str = "https://git.lashman.live/"; +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 { @@ -79,40 +97,96 @@ pub(crate) async fn check_for_update() -> Result> { } } -pub(crate) async fn download_to(url: &str, dest: &Path, mut on_progress: F) -> Result<()> +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, { - use std::io::Write; - - if !url.starts_with(UPDATE_ORIGIN) { + 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}"); } - if let Some(parent) = dest.parent() { - std::fs::create_dir_all(parent).context("creating update parent dir")?; - } 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 mut file = std::fs::File::create(dest).context("creating update file")?; + 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); } - file.flush()?; + 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(()) } -pub(crate) fn pending_update_path(app_dir: &Path) -> PathBuf { - app_dir.join("ByteSize.new.exe") +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 { @@ -123,7 +197,7 @@ fn last_check_path(app_dir: &Path) -> PathBuf { /// 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) = std::fs::metadata(&path) else { + let Ok(meta) = fs::metadata(&path) else { return true; }; let Ok(modified) = meta.modified() else { @@ -138,44 +212,86 @@ pub(crate) fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool { pub(crate) fn stamp_check(app_dir: &Path) { let path = last_check_path(app_dir); if let Some(parent) = path.parent() { - drop(std::fs::create_dir_all(parent)); + drop(fs::create_dir_all(parent)); } - drop(std::fs::write(&path, b"")); + drop(fs::write(&path, b"")); } pub(crate) fn has_pending_update(app_dir: &Path) -> bool { - pending_update_path(app_dir).is_file() + validate_executable(&pending_update_path(app_dir)).is_ok() } -pub(crate) fn write_apply_script(app_dir: &Path) -> Result { - let bat_path = app_dir.join("bytesize-apply-update.bat"); - let exe_name = std::env::current_exe() - .ok() - .and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned())) - .unwrap_or_else(|| "ByteSize.exe".to_string()); - let body = format!( - "@echo off\r\n\ - timeout /t 3 /nobreak >nul\r\n\ - :retry\r\n\ - del \"%~dp0{exe_name}\" 2>nul\r\n\ - if exist \"%~dp0{exe_name}\" (\r\n\ - timeout /t 2 /nobreak >nul\r\n\ - goto retry\r\n\ - )\r\n\ - move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe_name}\" >nul\r\n\ - if errorlevel 1 (\r\n\ - echo Failed to replace executable\r\n\ - pause\r\n\ - del \"%~f0\"\r\n\ - exit /b 1\r\n\ - )\r\n\ - start \"\" \"%~dp0{exe_name}\"\r\n\ - del \"%~f0\"\r\n" - ); - std::fs::write(&bat_path, body).context("writing apply script")?; - Ok(bat_path) +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, @@ -214,7 +330,32 @@ fn is_newer(latest: &str, current: &str) -> bool { #[cfg(test)] mod tests { - use super::is_newer; + 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() {