verify downloads before installing them
This commit is contained in:
+40
-139
@@ -41,37 +41,26 @@ struct Source {
|
|||||||
release_api_url: &'static str,
|
release_api_url: &'static str,
|
||||||
asset_name_suffix: &'static str,
|
asset_name_suffix: &'static str,
|
||||||
kind: ArchiveKind,
|
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] = &[
|
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 {
|
Source {
|
||||||
name: "GyanD",
|
name: "GyanD",
|
||||||
release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/latest",
|
release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/latest",
|
||||||
asset_name_suffix: "full_build.7z",
|
asset_name_suffix: "full_build.7z",
|
||||||
kind: ArchiveKind::SevenZ,
|
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)]
|
#[derive(Debug, Deserialize)]
|
||||||
struct GithubRelease {
|
struct GithubRelease {
|
||||||
tag_name: String,
|
|
||||||
assets: Vec<GithubAsset>,
|
assets: Vec<GithubAsset>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,6 +68,7 @@ struct GithubRelease {
|
|||||||
struct GithubAsset {
|
struct GithubAsset {
|
||||||
name: String,
|
name: String,
|
||||||
browser_download_url: String,
|
browser_download_url: String,
|
||||||
|
digest: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn download<F>(app_dir: &Path, mut on_progress: F) -> Result<()>
|
pub(crate) async fn download<F>(app_dir: &Path, mut on_progress: F) -> Result<()>
|
||||||
@@ -110,36 +100,13 @@ where
|
|||||||
F: FnMut(u64, Option<u64>),
|
F: FnMut(u64, Option<u64>),
|
||||||
{
|
{
|
||||||
let client = reqwest::Client::builder()
|
let client = reqwest::Client::builder()
|
||||||
|
.https_only(true)
|
||||||
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
|
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
|
||||||
.build()?;
|
.build()?;
|
||||||
|
|
||||||
let (asset, version) = pick_asset(&client, source).await?;
|
let asset = pick_asset(&client, source).await?;
|
||||||
|
let expected = parse_sha256(asset.digest.as_deref())
|
||||||
// Verify against the published checksum when there is one. GyanD used to
|
.with_context(|| format!("no valid published SHA-256 for {}", asset.name))?;
|
||||||
// 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 app_dir = dest
|
let app_dir = dest
|
||||||
.parent()
|
.parent()
|
||||||
@@ -150,96 +117,28 @@ where
|
|||||||
let archive_path =
|
let archive_path =
|
||||||
scratch_dir.join(format!("ffmpeg-archive-{}.tmp", source.name.to_lowercase()));
|
scratch_dir.join(format!("ffmpeg-archive-{}.tmp", source.name.to_lowercase()));
|
||||||
|
|
||||||
if let Some(ref hash) = expected {
|
let result = download_verified(
|
||||||
download_verified(
|
&client, &asset.browser_download_url, &expected, &archive_path, on_progress,
|
||||||
&client,
|
)
|
||||||
&asset.browser_download_url,
|
.await
|
||||||
hash,
|
.with_context(|| format!("downloading {}", asset.browser_download_url))
|
||||||
&archive_path,
|
.and_then(|()| match source.kind {
|
||||||
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 {
|
|
||||||
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest),
|
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest),
|
||||||
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest),
|
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest),
|
||||||
};
|
});
|
||||||
drop(fs::remove_file(&archive_path));
|
drop(fs::remove_file(&archive_path));
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch and parse a SHA-256 checksums file from `GyanD`.
|
fn parse_sha256(digest: Option<&str>) -> Result<[u8; 32]> {
|
||||||
/// The file contains a line like:
|
let hash = digest.and_then(|value| value.strip_prefix("sha256:"))
|
||||||
/// abc123def456... ffmpeg-8.1.1-full_build.7z
|
.context("release metadata does not contain a SHA-256 digest")?;
|
||||||
async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> {
|
let mut bytes = [0; 32];
|
||||||
let resp = client.get(url).send().await?.error_for_status()?;
|
hex::decode_to_slice(hash, &mut bytes).context("invalid SHA-256 digest")?;
|
||||||
let text = resp.text().await?;
|
Ok(bytes)
|
||||||
// Each line is: "<hex> <filename>" - 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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn download_plain<F>(
|
async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<GithubAsset> {
|
||||||
client: &reqwest::Client,
|
|
||||||
url: &str,
|
|
||||||
dest: &Path,
|
|
||||||
mut on_progress: F,
|
|
||||||
) -> Result<()>
|
|
||||||
where
|
|
||||||
F: FnMut(u64, Option<u64>),
|
|
||||||
{
|
|
||||||
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)> {
|
|
||||||
let resp = client
|
let resp = client
|
||||||
.get(source.release_api_url)
|
.get(source.release_api_url)
|
||||||
.header("Accept", "application/vnd.github+json")
|
.header("Accept", "application/vnd.github+json")
|
||||||
@@ -248,8 +147,7 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(Github
|
|||||||
.error_for_status()?;
|
.error_for_status()?;
|
||||||
let body = resp.text().await?;
|
let body = resp.text().await?;
|
||||||
let release: GithubRelease = serde_json::from_str(&body).context("parsing release metadata")?;
|
let release: GithubRelease = serde_json::from_str(&body).context("parsing release metadata")?;
|
||||||
let version = release.tag_name.trim_start_matches('v').to_string();
|
release
|
||||||
let asset = release
|
|
||||||
.assets
|
.assets
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|a| a.name.ends_with(source.asset_name_suffix))
|
.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",
|
"no asset matching '*{}' in release",
|
||||||
source.asset_name_suffix
|
source.asset_name_suffix
|
||||||
)
|
)
|
||||||
})?;
|
})
|
||||||
Ok((asset, version))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn download_verified<F>(
|
async fn download_verified<F>(
|
||||||
@@ -288,7 +185,6 @@ where
|
|||||||
file.flush()?;
|
file.flush()?;
|
||||||
let got: [u8; 32] = hasher.finalize().into();
|
let got: [u8; 32] = hasher.finalize().into();
|
||||||
if &got != expected {
|
if &got != expected {
|
||||||
drop(fs::remove_file(dest));
|
|
||||||
bail!(
|
bail!(
|
||||||
"sha256 mismatch: expected {} got {}",
|
"sha256 mismatch: expected {} got {}",
|
||||||
hex::encode(expected),
|
hex::encode(expected),
|
||||||
@@ -333,13 +229,8 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> {
|
|||||||
let _guard = DirGuard(scratch.clone());
|
let _guard = DirGuard(scratch.clone());
|
||||||
|
|
||||||
let file = File::open(archive_path).context("opening 7z archive")?;
|
let file = File::open(archive_path).context("opening 7z archive")?;
|
||||||
let extract_result =
|
sevenz_rust2::decompress(file, &scratch).map_err(|e| anyhow!("7z extraction failed: {e}"))?;
|
||||||
sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true))
|
let Some(src) = find_ffmpeg_in(&scratch) else {
|
||||||
.map_err(|e| anyhow!("7z extraction failed: {e}"));
|
|
||||||
let found = find_ffmpeg_in(&scratch);
|
|
||||||
|
|
||||||
extract_result?;
|
|
||||||
let Some(src) = found else {
|
|
||||||
bail!("ffmpeg.exe not found inside the 7z archive");
|
bail!("ffmpeg.exe not found inside the 7z archive");
|
||||||
};
|
};
|
||||||
install_from(dest, |staging| {
|
install_from(dest, |staging| {
|
||||||
@@ -407,6 +298,16 @@ fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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
|
/// 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
|
/// directory, arms the guard, then leaves through the `?` the way a failed
|
||||||
/// extraction does.
|
/// extraction does.
|
||||||
|
|||||||
+34
-20
@@ -275,9 +275,8 @@ async fn download_update(
|
|||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
url: String,
|
url: String,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let dest = updates::pending_update_path(&state.app_dir);
|
|
||||||
let app_handle = app.clone();
|
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(
|
drop(app_handle.emit(
|
||||||
"update-download-progress",
|
"update-download-progress",
|
||||||
UpdateDownloadProgress { downloaded, total },
|
UpdateDownloadProgress { downloaded, total },
|
||||||
@@ -295,17 +294,12 @@ async fn download_update(
|
|||||||
)]
|
)]
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
use std::os::windows::process::CommandExt;
|
if lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst)
|
||||||
use std::process::Command;
|
{
|
||||||
if !updates::has_pending_update(&state.app_dir) {
|
return Err("finish or discard the current recording before applying the update".to_string());
|
||||||
return Err("no pending update to apply".to_string());
|
|
||||||
}
|
}
|
||||||
let bat = updates::write_apply_script(&state.app_dir).map_err(|e| format!("{e:#}"))?;
|
let _operation = updates::UpdateOperation::begin().map_err(|e| format!("{e:#}"))?;
|
||||||
Command::new("cmd")
|
updates::start_install(&state.app_dir).map_err(|e| format!("{e:#}"))?;
|
||||||
.args(["/c", "start", "", ""])
|
|
||||||
.raw_arg(format!("\"{}\"", bat.to_string_lossy()))
|
|
||||||
.spawn()
|
|
||||||
.map_err(|e| format!("spawning apply script: {e:#}"))?;
|
|
||||||
app.exit(0);
|
app.exit(0);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -1925,18 +1919,38 @@ fn reveal_in_explorer(path: String) -> Result<(), String> {
|
|||||||
Ok(())
|
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]
|
#[tauri::command]
|
||||||
fn open_url(url: String) -> Result<(), String> {
|
fn open_url(url: String) -> Result<(), String> {
|
||||||
use std::os::windows::process::CommandExt;
|
let url = reqwest::Url::parse(&url).map_err(|e| format!("invalid URL: {e}"))?;
|
||||||
|
if !matches!(url.scheme(), "http" | "https") || !url.has_host() {
|
||||||
if !url.starts_with("http://") && !url.starts_with("https://") {
|
|
||||||
return Err("only http/https URLs are supported".to_string());
|
return Err("only http/https URLs are supported".to_string());
|
||||||
}
|
}
|
||||||
std::process::Command::new("cmd")
|
open_shell_target(std::ffi::OsStr::new(url.as_str()))
|
||||||
.raw_arg(format!("/C start \"\" \"{url}\""))
|
|
||||||
.spawn()
|
|
||||||
.map_err(|e| format!("opening url: {e:#}"))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
|
|||||||
+188
-47
@@ -1,4 +1,7 @@
|
|||||||
|
use std::fs::{self, File};
|
||||||
|
use std::io::{Read, Seek, SeekFrom, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
use anyhow::{bail, Context, Result};
|
use anyhow::{bail, Context, Result};
|
||||||
use futures_util::StreamExt;
|
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";
|
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
|
const UPDATE_HOST: &str = "git.lashman.live";
|
||||||
/// URL arrives from the frontend, and an unconstrained one there would let
|
static UPDATE_BUSY: AtomicBool = AtomicBool::new(false);
|
||||||
/// anything that can reach the webview hand the app a new executable to install.
|
|
||||||
const UPDATE_ORIGIN: &str = "https://git.lashman.live/";
|
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)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub(crate) struct UpdateInfo {
|
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
|
where
|
||||||
F: FnMut(u64, Option<u64>) + Send,
|
F: FnMut(u64, Option<u64>) + Send,
|
||||||
{
|
{
|
||||||
use std::io::Write;
|
let _operation = UpdateOperation::begin()?;
|
||||||
|
let url = reqwest::Url::parse(url).context("parsing update URL")?;
|
||||||
if !url.starts_with(UPDATE_ORIGIN) {
|
if !is_update_url(&url) {
|
||||||
bail!("refusing to download an update from {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()
|
let client = reqwest::Client::builder()
|
||||||
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
|
.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()?;
|
.build()?;
|
||||||
|
|
||||||
let resp = client.get(url).send().await?.error_for_status()?;
|
let resp = client.get(url).send().await?.error_for_status()?;
|
||||||
let total = resp.content_length();
|
let total = resp.content_length();
|
||||||
let mut downloaded = 0u64;
|
let mut downloaded = 0u64;
|
||||||
let mut stream = resp.bytes_stream();
|
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 {
|
while let Some(chunk) = stream.next().await {
|
||||||
let chunk = chunk?;
|
let chunk = chunk?;
|
||||||
file.write_all(&chunk)?;
|
file.write_all(&chunk)?;
|
||||||
downloaded += chunk.len() as u64;
|
downloaded += chunk.len() as u64;
|
||||||
on_progress(downloaded, total);
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn pending_update_path(app_dir: &Path) -> PathBuf {
|
struct StagedUpdate(PathBuf);
|
||||||
app_dir.join("ByteSize.new.exe")
|
|
||||||
|
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 {
|
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.
|
/// 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 {
|
pub(crate) fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool {
|
||||||
let path = last_check_path(app_dir);
|
let path = last_check_path(app_dir);
|
||||||
let Ok(meta) = std::fs::metadata(&path) else {
|
let Ok(meta) = fs::metadata(&path) else {
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
let Ok(modified) = meta.modified() else {
|
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) {
|
pub(crate) fn stamp_check(app_dir: &Path) {
|
||||||
let path = last_check_path(app_dir);
|
let path = last_check_path(app_dir);
|
||||||
if let Some(parent) = path.parent() {
|
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 {
|
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> {
|
pub(crate) fn start_install(app_dir: &Path) -> Result<()> {
|
||||||
let bat_path = app_dir.join("bytesize-apply-update.bat");
|
use std::os::windows::{ffi::OsStringExt, process::CommandExt};
|
||||||
let exe_name = std::env::current_exe()
|
use windows::Win32::System::SystemInformation::GetSystemDirectoryW;
|
||||||
.ok()
|
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
|
||||||
.and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned()))
|
|
||||||
.unwrap_or_else(|| "ByteSize.exe".to_string());
|
let update = pending_update_path(app_dir);
|
||||||
let body = format!(
|
validate_executable(&update).context("no usable pending update")?;
|
||||||
"@echo off\r\n\
|
let installed = std::env::current_exe().context("finding the running executable")?;
|
||||||
timeout /t 3 /nobreak >nul\r\n\
|
let mut system_dir = [0; 512];
|
||||||
:retry\r\n\
|
// SAFETY: The supplied buffer remains writable through the call.
|
||||||
del \"%~dp0{exe_name}\" 2>nul\r\n\
|
let len = unsafe { GetSystemDirectoryW(Some(&mut system_dir)) };
|
||||||
if exist \"%~dp0{exe_name}\" (\r\n\
|
let system_dir = system_dir
|
||||||
timeout /t 2 /nobreak >nul\r\n\
|
.get(..usize::try_from(len)?)
|
||||||
goto retry\r\n\
|
.filter(|path| !path.is_empty() && path.len() < system_dir.len())
|
||||||
)\r\n\
|
.context("finding the Windows system directory")?;
|
||||||
move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe_name}\" >nul\r\n\
|
let powershell = PathBuf::from(std::ffi::OsString::from_wide(system_dir))
|
||||||
if errorlevel 1 (\r\n\
|
.join(r"WindowsPowerShell\v1.0\powershell.exe");
|
||||||
echo Failed to replace executable\r\n\
|
|
||||||
pause\r\n\
|
std::process::Command::new(powershell)
|
||||||
del \"%~f0\"\r\n\
|
.args(["-NoProfile", "-NonInteractive", "-Command", APPLY_SCRIPT])
|
||||||
exit /b 1\r\n\
|
.env("BYTESIZE_UPDATE_PID", std::process::id().to_string())
|
||||||
)\r\n\
|
.env("BYTESIZE_UPDATE_ACTIVE", &installed)
|
||||||
start \"\" \"%~dp0{exe_name}\"\r\n\
|
.env("BYTESIZE_UPDATE_REPLACEMENT", update)
|
||||||
del \"%~f0\"\r\n"
|
.env(
|
||||||
);
|
"BYTESIZE_UPDATE_BACKUP",
|
||||||
std::fs::write(&bat_path, body).context("writing apply script")?;
|
app_dir.join(format!("ByteSize.{}.update-backup.exe", std::process::id())),
|
||||||
Ok(bat_path)
|
)
|
||||||
|
.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)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
struct VersionParts {
|
struct VersionParts {
|
||||||
nums: Vec<u32>,
|
nums: Vec<u32>,
|
||||||
@@ -214,7 +330,32 @@ fn is_newer(latest: &str, current: &str) -> bool {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
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]
|
#[test]
|
||||||
fn version_major_bump() {
|
fn version_major_bump() {
|
||||||
|
|||||||
Reference in New Issue
Block a user