From 7867384c0ab703b4c6aae36cbbb1a35fcffc8321 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 16:22:59 -0800 Subject: [PATCH] :new: Give OVMF's package a second source, and name each when all fail On 2026-11-21 archive.archlinux.org, the OVMF package's only source, answered nothing over IPv4, and a fresh install made no VM. The package now comes from the Arch Linux Archive, or else from its mirror at umea.archive.pkgbuild.com (Arch's infrastructure docs/servers.md, "Archive Mirrors"), which serves the same file, with the pinned SHA-256, and answers ranges. - A pinned file's sources are tried in order, and the pinned hash decides: a source that fails, or whose file has another hash, hands the download to the next, which goes on from the .part file the earlier one left. Stopping (Ctrl+C) stops; it doesn't hand over. - A source with another after it gives up after 2 failed requests in a row instead of 10 (Download::tries), so a host that answers nothing delays the download about a minute and a half, not nine minutes. The last source keeps all 10. - When every source fails, the error lists each source and what it answered, and says what to do: try again later, or put the file at its path in the cache, where it is used if its SHA-256 matches. The interactive interface prints it line by line. - OpenCore's release and OcBinaryData keep their one source and their own errors. - The tests fake the network with an HTTP server on 127.0.0.1: the order, the shorter handover, the error's text, a file put in the cache by hand, stopping, and a file with one source. - CHANGELOG.md starts here. With an empty cache and the archive down, `reims-util opencore` wrote OVMF from the mirror in 1 min 39 s. --- CHANGELOG.md | 13 ++ src/cache.rs | 364 ++++++++++++++++++++++++++++++++++++++++---- src/http.rs | 27 +++- src/opencore/mod.rs | 8 +- src/ovmf.rs | 32 +++- src/recovery.rs | 1 + src/tui.rs | 13 +- 7 files changed, 410 insertions(+), 48 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..95d26e3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +## Unreleased + +- OVMF's package, `edk2-ovmf-202608-1-any.pkg.tar.zst`, has a second source: the Arch Linux + Archive's mirror at `umea.archive.pkgbuild.com`, tried when `archive.archlinux.org` fails. On + 2026-11-21 the archive answered nothing over IPv4 and a fresh install made no OVMF; the mirror + served the same file, with the pinned SHA-256. The first source now gives up after 2 failed + requests in a row instead of 10, so a dead host delays the download by about a minute and a + half. +- When every source of the package fails, the error names each source and what it answered, and + says where to put the file by hand: in `~/.cache/reims-util`, where it is used if its SHA-256 + matches the pin. diff --git a/src/cache.rs b/src/cache.rs index bf016ee..c355254 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -1,10 +1,21 @@ //! Files fetched once and kept: the OpenCore release, OcBinaryData and the OVMF package, each //! pinned to its SHA-256, under `$XDG_CACHE_HOME/reims-util` (`~/.cache/reims-util`). +//! +//! A pinned file can have more than one source, each serving the same bytes. They are tried in +//! order, and the pinned SHA-256 decides: a source that fails, or whose file has another hash, +//! hands the download to the next one, which goes on from what the earlier one left. use crate::http::{self, Dest, Download, NoCheck}; -use crate::progress::Reporter; -use anyhow::{Context, Result, bail}; -use std::path::PathBuf; +use crate::progress::{self, Reporter}; +use anyhow::{Context, Result, anyhow, bail}; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use ureq::Agent; + +/// Failed requests in a row before a source hands the download to the next: a host that answers +/// nothing then costs about a minute and a half (three 30-second connects), not the nine or so +/// minutes of [`http::MAX_FAILURES`] tries. The last source gets all of those. +const FAILOVER_TRIES: u32 = 2; pub fn dir() -> Result { let base = match std::env::var_os("XDG_CACHE_HOME").filter(|v| !v.is_empty()) { @@ -17,7 +28,8 @@ pub fn dir() -> Result { pub struct Pinned { /// Its name in the cache. pub name: &'static str, - pub url: &'static str, + /// Where it is downloaded from, tried in this order. + pub urls: &'static [&'static str], pub sha256: &'static str, /// What it is, for the progress line: "OpenCore 1.0.8". pub what: &'static str, @@ -26,29 +38,325 @@ pub struct Pinned { /// The cached file, downloaded (or its download resumed) first if it is not there. pub fn fetch(p: &Pinned, r: &dyn Reporter) -> Result { let path = dir()?.join(p.name); - if path.exists() { - if http::sha256_file(&path)? == p.sha256 { - return Ok(path); - } - std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?; - } - let agent = http::agent(); - http::download( - &agent, - Download::new(p.url, format!("Downloading {}", p.what)), - Dest::File(&path), - &mut NoCheck, - r, - )?; - let got = http::sha256_file(&path)?; - if got != p.sha256 { - let _ = std::fs::remove_file(&path); - bail!( - "{} from {} has SHA-256 {got}, not the pinned {}", - p.what, - p.url, - p.sha256 - ); - } + fetch_to(p, &path, &http::agent(), r)?; Ok(path) } + +fn fetch_to(p: &Pinned, path: &Path, agent: &Agent, r: &dyn Reporter) -> Result<()> { + if path.exists() { + if http::sha256_file(path)? == p.sha256 { + return Ok(()); + } + std::fs::remove_file(path).with_context(|| format!("remove {}", path.display()))?; + } + // A file with one source (OpenCore's) fails with that source's own error. + let alone = p.urls.len() == 1; + let mut failed = Vec::new(); + for (i, url) in p.urls.iter().enumerate() { + let next = p.urls.get(i + 1); + let mut d = Download::new(url, format!("Downloading {}", p.what)); + if next.is_some() { + d.tries = FAILOVER_TRIES; + } + let answer = match http::download(agent, d, Dest::File(path), &mut NoCheck, r) { + Ok(()) => { + let got = http::sha256_file(path)?; + if got == p.sha256 { + return Ok(()); + } + let _ = std::fs::remove_file(path); + if alone { + bail!( + "{} from {url} has SHA-256 {got}, not the pinned {}", + p.what, + p.sha256 + ); + } + format!("served a file with SHA-256 {got}") + } + Err(e) if alone || e.is::() => return Err(e), + Err(e) => answer(url, &e), + }; + if let Some(next) = next { + r.note(&format!( + "{} did not serve it: trying {}", + host(url), + host(next) + )); + } + failed.push((*url, answer)); + } + Err(anyhow!(all_failed(p, path, &failed))) +} + +/// What a source answered: its error, without the URL the error starts with. +fn answer(url: &str, e: &anyhow::Error) -> String { + let s = format!("{e:#}"); + match s.strip_prefix(url) { + Some(rest) => rest.trim_start_matches(':').trim_start().to_string(), + None => s, + } +} + +fn host(url: &str) -> &str { + let rest = url.split_once("://").map_or(url, |(_, rest)| rest); + rest.split('/').next().unwrap_or(rest) +} + +/// The error once every source failed: each source and what it answered, and what to do. +fn all_failed(p: &Pinned, path: &Path, failed: &[(&str, String)]) -> String { + let mut s = format!( + "could not download {} from any of its {} sources:", + p.what, + failed.len() + ); + for (url, answer) in failed { + let _ = write!(s, "\n {url}\n {answer}"); + } + let _ = write!( + s, + "\nTry again later. Or download {} yourself, from any source that has it, and put it \ + at\n {}\nwhere reims-util uses it if its SHA-256 is {}.", + p.name, + path.display(), + p.sha256 + ); + s +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::progress::Event; + use std::io::{BufRead, BufReader, Write}; + use std::net::TcpListener; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Mutex}; + + const GOOD: &[u8] = b"the pinned file's bytes"; + const OTHER: &[u8] = b"some other bytes"; + + /// What the fake network answers for a path. + #[derive(Clone, Copy)] + enum Answer { + Status(u16), + /// The file, or the part of it from where a `Range` header starts. + File(&'static [u8]), + } + + /// The network, faked: an HTTP server on 127.0.0.1 that answers each path as its routes say + /// (404 for any other) and records the paths it was asked for, in order. + struct Server { + base: String, + asked: Arc>>, + } + + impl Server { + fn start(routes: &[(&'static str, Answer)]) -> Server { + let routes = routes.to_vec(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let asked = Arc::new(Mutex::new(Vec::new())); + let log = asked.clone(); + std::thread::spawn(move || { + for conn in listener.incoming() { + let Ok(mut conn) = conn else { continue }; + let mut req = BufReader::new(conn.try_clone().unwrap()); + let mut line = String::new(); + let _ = req.read_line(&mut line); + let path = line.split(' ').nth(1).unwrap_or("").to_string(); + let mut from = 0; + loop { + let mut h = String::new(); + if req.read_line(&mut h).unwrap_or(0) == 0 || h == "\r\n" { + break; + } + if let Some(v) = h.to_ascii_lowercase().strip_prefix("range: bytes=") { + from = v.split('-').next().unwrap().trim().parse().unwrap(); + } + } + log.lock().unwrap().push(path.clone()); + let answer = routes + .iter() + .find(|(p, _)| *p == path) + .map_or(Answer::Status(404), |(_, a)| *a); + let resp = match answer { + Answer::Status(s) => format!( + "HTTP/1.1 {s} Fake\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" + ) + .into_bytes(), + Answer::File(data) => { + let from = from.min(data.len()); + let mut v = format!( + "HTTP/1.1 206 Partial Content\r\ncontent-range: bytes {from}-{}/{}\r\n\ + content-length: {}\r\nconnection: close\r\n\r\n", + data.len() - 1, + data.len(), + data.len() - from + ) + .into_bytes(); + v.extend_from_slice(&data[from..]); + v + } + }; + let _ = conn.write_all(&resp); + } + }); + Server { base, asked } + } + + fn url(&self, path: &str) -> &'static str { + Box::leak(format!("{}{path}", self.base).into_boxed_str()) + } + + fn asked(&self) -> Vec { + self.asked.lock().unwrap().clone() + } + } + + #[derive(Default)] + struct Log { + notes: Mutex>, + cancel: AtomicBool, + } + + impl Reporter for Log { + fn event(&self, e: Event) { + if let Event::Note { message } = e { + self.notes.lock().unwrap().push(message); + } + } + fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) + } + } + + fn sha(data: &[u8]) -> String { + use sha2::{Digest, Sha256}; + http::hex(&Sha256::digest(data)) + } + + fn pinned(urls: Vec<&'static str>) -> Pinned { + Pinned { + name: "file.pkg", + urls: Box::leak(urls.into_boxed_slice()), + sha256: Box::leak(sha(GOOD).into_boxed_str()), + what: "the test file", + } + } + + /// Where the test's file is cached: in an empty folder of its own. + fn cache_path(test: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("reims-util-cache-{}-{test}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.join("file.pkg") + } + + #[test] + fn tries_the_sources_in_order_and_keeps_the_first_with_the_pinned_hash() { + let s = Server::start(&[ + ("/missing", Answer::Status(404)), + ("/other", Answer::File(OTHER)), + ("/good", Answer::File(GOOD)), + ("/also-good", Answer::File(GOOD)), + ]); + let p = pinned(vec![ + s.url("/missing"), + s.url("/other"), + s.url("/good"), + s.url("/also-good"), + ]); + let path = cache_path("order"); + let r = Log::default(); + fetch_to(&p, &path, &http::agent(), &r).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), GOOD); + assert_eq!(s.asked(), ["/missing", "/other", "/good"]); + let host = host(&s.base).to_string(); + assert_eq!( + *r.notes.lock().unwrap(), + [ + format!("{host} did not serve it: trying {host}"), + format!("{host} did not serve it: trying {host}"), + ] + ); + } + + #[test] + fn a_failing_source_hands_over_sooner_when_another_follows() { + let s = Server::start(&[ + ("/busy", Answer::Status(503)), + ("/good", Answer::File(GOOD)), + ]); + let p = pinned(vec![s.url("/busy"), s.url("/good")]); + let path = cache_path("failover"); + fetch_to(&p, &path, &http::agent(), &Log::default()).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), GOOD); + // The first request and FAILOVER_TRIES more. + assert_eq!(s.asked(), ["/busy", "/busy", "/busy", "/good"]); + } + + #[test] + fn names_each_source_and_its_answer_when_every_source_fails() { + let s = Server::start(&[ + ("/missing", Answer::Status(404)), + ("/other", Answer::File(OTHER)), + ]); + let (missing, other) = (s.url("/missing"), s.url("/other")); + let p = pinned(vec![missing, other]); + let path = cache_path("all-fail"); + let e = fetch_to(&p, &path, &http::agent(), &Log::default()).unwrap_err(); + assert_eq!( + format!("{e:#}"), + format!( + "could not download the test file from any of its 2 sources:\n \ + {missing}\n answered HTTP 404\n \ + {other}\n served a file with SHA-256 {}\n\ + Try again later. Or download file.pkg yourself, from any source that has it, \ + and put it at\n {}\nwhere reims-util uses it if its SHA-256 is {}.", + sha(OTHER), + path.display(), + sha(GOOD) + ) + ); + assert!(!path.exists()); + assert_eq!(s.asked(), ["/missing", "/other"]); + } + + #[test] + fn uses_a_file_put_where_the_cache_looks() { + let s = Server::start(&[]); + let p = pinned(vec![s.url("/missing"), s.url("/missing-too")]); + let path = cache_path("placed"); + std::fs::write(&path, GOOD).unwrap(); + fetch_to(&p, &path, &http::agent(), &Log::default()).unwrap(); + assert!(s.asked().is_empty()); + } + + #[test] + fn stopping_does_not_hand_over_to_the_next_source() { + let s = Server::start(&[("/good", Answer::File(GOOD))]); + let p = pinned(vec![s.url("/good"), s.url("/good")]); + let path = cache_path("stop"); + let r = Log::default(); + r.cancel.store(true, Ordering::Relaxed); + let e = fetch_to(&p, &path, &http::agent(), &r).unwrap_err(); + assert!(e.is::()); + assert!(s.asked().is_empty()); + } + + #[test] + fn a_file_with_one_source_fails_with_its_own_error() { + let s = Server::start(&[]); + let url = s.url("/missing"); + let e = fetch_to( + &pinned(vec![url]), + &cache_path("alone"), + &http::agent(), + &Log::default(), + ) + .unwrap_err(); + assert_eq!(format!("{e:#}"), format!("{url} answered HTTP 404")); + } +} diff --git a/src/http.rs b/src/http.rs index 1f6e440..69aeb81 100644 --- a/src/http.rs +++ b/src/http.rs @@ -23,8 +23,9 @@ pub const SEGMENT: u64 = 64 << 20; /// How long a request may take to send its range: a stall is noticed within this. (On a /// connection too slow to send a whole range in it, each request sends what it can.) pub const SEGMENT_BUDGET: Duration = Duration::from_secs(180); -/// Failed requests in a row, with no byte received between them, before a download gives up. -const MAX_FAILURES: u32 = 10; +/// Failed requests in a row, with no byte received between them, before a download gives up +/// (unless its [`Download::tries`] says otherwise). +pub const MAX_FAILURES: u32 = 10; pub type Headers = Vec<(String, String)>; @@ -123,6 +124,9 @@ pub struct Download<'a> { /// For requests the server refuses (401, 403): new headers, such as a fresh asset token. pub refresh: Option<&'a mut dyn FnMut() -> Result>, pub user_agent: Option<&'static str>, + /// Failed requests in a row, with no byte received between them, before it gives up: + /// [`MAX_FAILURES`], or fewer when there is another place to download the file from. + pub tries: u32, } impl Download<'_> { @@ -134,6 +138,7 @@ impl Download<'_> { size: None, refresh: None, user_agent: None, + tries: MAX_FAILURES, } } } @@ -249,7 +254,7 @@ pub fn download( Ok(resp) => resp, Err(e) => { failures += 1; - retry_or_fail(&mut failures, &format!("{e}"), &d.url, r)?; + retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?; continue; } }; @@ -315,7 +320,7 @@ pub fn download( } 408 | 429 | 500..=599 => { failures += 1; - retry_or_fail(&mut failures, &format!("HTTP {status}"), &d.url, r)?; + retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?; continue; } _ => bail!("{} answered HTTP {status}", d.url), @@ -341,7 +346,7 @@ pub fn download( continue 'requests; } failures += 1; - retry_or_fail(&mut failures, &format!("{e}"), &d.url, r)?; + retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?; continue 'requests; } }; @@ -384,9 +389,15 @@ pub fn download( Ok(()) } -fn retry_or_fail(failures: &mut u32, why: &str, url: &str, r: &dyn Reporter) -> Result<()> { - if *failures > MAX_FAILURES { - bail!("{url}: {why} (gave up after {MAX_FAILURES} tries; run again to resume)"); +fn retry_or_fail( + failures: &mut u32, + tries: u32, + why: &str, + url: &str, + r: &dyn Reporter, +) -> Result<()> { + if *failures > tries { + bail!("{url}: {why} (gave up after {tries} tries; run again to resume)"); } let wait = Duration::from_secs((1u64 << (*failures).min(5)).min(30)); r.note(&format!( diff --git a/src/opencore/mod.rs b/src/opencore/mod.rs index 9827377..4131ad9 100644 --- a/src/opencore/mod.rs +++ b/src/opencore/mod.rs @@ -20,7 +20,9 @@ pub const VERSION: &str = "1.0.8"; const RELEASE: Pinned = Pinned { name: "OpenCore-1.0.8-RELEASE.zip", - url: "https://github.com/acidanthera/OpenCorePkg/releases/download/1.0.8/OpenCore-1.0.8-RELEASE.zip", + urls: &[ + "https://github.com/acidanthera/OpenCorePkg/releases/download/1.0.8/OpenCore-1.0.8-RELEASE.zip", + ], sha256: "2011e8b7216ecb2645d97ea710df965947edd406846e92050b9bc4190be6d27b", what: "OpenCore 1.0.8", }; @@ -28,7 +30,9 @@ const RELEASE: Pinned = Pinned { /// OcBinaryData, which has no releases: GitHub's archive of a commit. const RESOURCES: Pinned = Pinned { name: "OcBinaryData-32500d5e3313f11cad00351ba1c6f9a4aa6cb0f7.zip", - url: "https://github.com/acidanthera/OcBinaryData/archive/32500d5e3313f11cad00351ba1c6f9a4aa6cb0f7.zip", + urls: &[ + "https://github.com/acidanthera/OcBinaryData/archive/32500d5e3313f11cad00351ba1c6f9a4aa6cb0f7.zip", + ], sha256: "1ced15b42352a3a6c1b76ca95951f337fa79899acfb4ed80f329191716623741", what: "OpenCore's picker icons and boot chime", }; diff --git a/src/ovmf.rs b/src/ovmf.rs index 7be0f77..a6b782e 100644 --- a/src/ovmf.rs +++ b/src/ovmf.rs @@ -1,5 +1,6 @@ //! OVMF, the UEFI firmware an x86-64 VM boots OpenCore with: its code and its variable store, -//! from Arch Linux's `edk2-ovmf` package, pinned. +//! from Arch Linux's `edk2-ovmf` package, pinned. The package comes from the Arch Linux Archive, +//! or, when that fails, from the archive's mirror in UmeƄ, which serves the same file. //! //! The pinned build is the one the reims-vgpu macOS 26 guest on homelab-ms01 boots: its //! `OVMF_CODE.4m.fd` and `OVMF_VARS.4m.fd` are those files' bytes. It is built without SMM and @@ -17,7 +18,12 @@ pub const VERSION: &str = "edk2-ovmf 202608-1"; const PACKAGE: Pinned = Pinned { name: "edk2-ovmf-202608-1-any.pkg.tar.zst", - url: "https://archive.archlinux.org/packages/e/edk2-ovmf/edk2-ovmf-202608-1-any.pkg.tar.zst", + // The Arch Linux Archive, then its mirror (Arch's infrastructure docs/servers.md, "Archive + // Mirrors"). + urls: &[ + "https://archive.archlinux.org/packages/e/edk2-ovmf/edk2-ovmf-202608-1-any.pkg.tar.zst", + "https://umea.archive.pkgbuild.com/packages/e/edk2-ovmf/edk2-ovmf-202608-1-any.pkg.tar.zst", + ], sha256: "bee34c6036ebd0e96562b7330d2d3ddf75e240cfc44a6d506a5ccb6390eafb91", what: "OVMF (Arch Linux's edk2-ovmf 202608-1)", }; @@ -88,3 +94,25 @@ pub fn write(dir: &Path, r: &dyn Reporter) -> Result { vars: dir.join("OVMF_VARS.fd"), }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_source_is_the_archives_path_to_the_package() { + let path = format!("/packages/e/edk2-ovmf/{}", PACKAGE.name); + let hosts: Vec<&str> = PACKAGE + .urls + .iter() + .map(|u| u.strip_suffix(path.as_str()).unwrap()) + .collect(); + assert_eq!( + hosts, + [ + "https://archive.archlinux.org", + "https://umea.archive.pkgbuild.com" + ] + ); + } +} diff --git a/src/recovery.rs b/src/recovery.rs index 3a69a77..fe4eadc 100644 --- a/src/recovery.rs +++ b/src/recovery.rs @@ -311,6 +311,7 @@ impl Image { size: Some(self.size()), refresh: Some(&mut refresh), user_agent: Some(USER_AGENT), + tries: http::MAX_FAILURES, }; http::download(&self.agent, d, dest, check, r) } diff --git a/src/tui.rs b/src/tui.rs index 2d50aca..38a4aca 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -171,15 +171,12 @@ impl App { if r.cancel.load(Ordering::Relaxed) { self.status = Some(("Stopped. Start it again to resume.".into(), false)); } else { - // Above, where it's wrapped whole: an error often starts with a long URL. + // Above, where it's wrapped whole: an error often starts with a long URL. An + // error of several lines (every source of a download failing) keeps them. let red = Style::new().fg(Color::Red); - print_above( - t, - vec![ - Line::styled(format!("Failed: {}", r.title), red.bold()), - Line::styled(format!(" {e}"), red), - ], - )?; + let mut lines = vec![Line::styled(format!("Failed: {}", r.title), red.bold())]; + lines.extend(e.lines().map(|l| Line::styled(format!(" {l}"), red))); + print_above(t, lines)?; self.status = Some(("Failed: why is above.".into(), true)); } self.screen = Screen::Menu(0);