verify downloads before installing them

This commit is contained in:
2026-09-22 19:21:00 +03:00
parent 0da3691a1b
commit 730b8df0fe
3 changed files with 262 additions and 206 deletions
+188 -47
View File
@@ -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<Self> {
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<Option<UpdateInfo>> {
}
}
pub(crate) async fn download_to<F>(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<F>(url: &str, app_dir: &Path, mut on_progress: F) -> Result<()>
where
F: FnMut(u64, Option<u64>) + 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<PathBuf> {
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<u32>,
@@ -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() {