From 5edf792fa4582264c8d7a8a2dbcbc11cada45535 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Wed, 11 Nov 2026 03:21:17 -0500 Subject: [PATCH] fix(cli): retry setup's downloads and signing requests with backoff, bound stalled ranges and slow firmware downloads, and name the cause of a network failure or sign-in page --- crates/stela-cli/src/boot/ticket.rs | 96 +++++++++-- crates/stela-cli/src/lib.rs | 1 + crates/stela-cli/src/net.rs | 219 ++++++++++++++++++++++++ crates/stela-cli/src/restore.rs | 17 +- crates/stela-cli/src/restore/aea.rs | 3 +- crates/stela-cli/src/restore/history.rs | 42 ++++- crates/stela-cli/src/restore/remote.rs | 78 +++++++-- crates/stela-cli/src/setup/firmware.rs | 15 +- 8 files changed, 422 insertions(+), 49 deletions(-) create mode 100644 crates/stela-cli/src/net.rs diff --git a/crates/stela-cli/src/boot/ticket.rs b/crates/stela-cli/src/boot/ticket.rs index 86b9be6ab3..ba3a4bd909 100644 --- a/crates/stela-cli/src/boot/ticket.rs +++ b/crates/stela-cli/src/boot/ticket.rs @@ -30,29 +30,55 @@ impl tss::Transport for Apple { content_type: &str, body: &[u8], ) -> restore::Result>> { - let failed = |error: reqwest::Error| { - restore::Error::Transport(refuse!("TSS request: {error}", %error)) - }; - let mut request = self - .0 - .post(format!("http://{host}{path}")) - .header(reqwest::header::CONTENT_TYPE, content_type) - .body(body.to_vec()); - for (name, value) in headers { - request = request.header(*name, *value); - } - let response = request.send().map_err(failed)?; + let failed = |error: String| restore::Error::Transport(refuse!("{error}", %error)); + // The same body asks for the same ticket, so a lost request is + // asked again. + let response = crate::net::send(&format!("Apple's signing server ({host})"), || { + let mut request = self + .0 + .post(format!("http://{host}{path}")) + .header(reqwest::header::CONTENT_TYPE, content_type) + .body(body.to_vec()); + for (name, value) in headers { + request = request.header(*name, *value); + } + request + }) + .map_err(|error| failed(format!("{error:#}")))?; let status = response.status(); if !status.is_success() { - return Err(restore::Error::Transport(refuse!( - "HTTP status {as_u16}", - as_u16 = status.as_u16() + return Err(failed(format!( + "{host} answered HTTP status {}", + status.as_u16() ))); } - Ok(Some(response.bytes().map_err(failed)?.to_vec())) + let bytes = response + .bytes() + .map_err(|error| failed(crate::net::explain(&error)))?; + signing_answer(host, &bytes).map_err(failed)?; + Ok(Some(bytes.to_vec())) } } +/// Refuse an answer that is not the signing server's: a network that shows +/// its sign-in page answers every plain-HTTP request with that page. +fn signing_answer(host: &str, bytes: &[u8]) -> Result<(), String> { + if bytes.starts_with(b"STATUS=") { + return Ok(()); + } + Err(format!( + "the network answered for {host} with something other than Apple's signing server \ + ({} bytes{}). A network that wants a sign-in first does this: open a web page on this \ + computer, sign in to the network, and run setup again", + bytes.len(), + if bytes.windows(5).any(|w| w.eq_ignore_ascii_case(b" Result> { @@ -98,3 +124,41 @@ pub fn personalized(manifest: &[u8], index: u32, ecid: u64) -> Result> { .map_err(|error| anyhow!("Apple's root ticket: {error}"))?; Ok(bytes) } + +#[cfg(test)] +mod tests { + use super::*; + use stela_runtime::restore::tss::Transport as _; + + #[test] + fn signing_requests_are_asked_again_and_a_sign_in_page_is_named() { + let tss = "STATUS=0&MESSAGE=SUCCESS&REQUEST_STRING="; + let reply = |status: &str, body: &str| { + format!( + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + }; + let (url, _) = crate::net::tests::serve(vec![ + reply("502 Bad Gateway", ""), + reply("200 OK", tss), + reply("200 OK", "Sign in to Guest Wi-Fi"), + ]); + let host = url + .strip_prefix("http://") + .and_then(|rest| rest.split('/').next()) + .unwrap() + .to_owned(); + let mut apple = Apple(Client::new()); + let answer = apple + .exchange(&host, "/TSS/controller", &[], "text/xml", b"") + .unwrap(); + assert_eq!(answer.as_deref(), Some(tss.as_bytes())); + let error = apple + .exchange(&host, "/TSS/controller", &[], "text/xml", b"") + .unwrap_err() + .to_string(); + assert!(error.contains("sign in to the network"), "{error}"); + assert!(error.contains("a web page"), "{error}"); + } +} diff --git a/crates/stela-cli/src/lib.rs b/crates/stela-cli/src/lib.rs index e719d92f46..22c98768ff 100644 --- a/crates/stela-cli/src/lib.rs +++ b/crates/stela-cli/src/lib.rs @@ -10,6 +10,7 @@ pub mod boot; mod boot_log; pub mod efi; pub use stela_gpu_maintenance as gpu; +mod net; mod progress; pub mod restore; mod setup; diff --git a/crates/stela-cli/src/net.rs b/crates/stela-cli/src/net.rs new file mode 100644 index 0000000000..23bc3ea3cc --- /dev/null +++ b/crates/stela-cli/src/net.rs @@ -0,0 +1,219 @@ +//! What every HTTP request `stela` makes shares: a request that fails in +//! transit, or that a server refuses for now, is asked again with growing +//! waits, and a failure says its cause in words a user can act on (no +//! network, a name that does not resolve, a network that intercepts HTTPS). +use anyhow::{Result, anyhow}; +use reqwest::{ + StatusCode, + blocking::{RequestBuilder, Response}, +}; +use std::{error::Error as _, time::Duration}; + +/// Attempts per request: with waits of 1, 2, 4 and 8 s between them, a +/// network that drops for about 15 s costs a pause, not the setup. +pub(crate) const ATTEMPTS: u32 = 5; + +/// The first wait between attempts; each later one doubles. +fn first_wait() -> Duration { + if cfg!(test) { + Duration::from_millis(10) + } else { + Duration::from_secs(1) + } +} + +/// A server's answer that the same request may not get again: a server +/// error, a timeout answer, or a rate limit. +pub(crate) fn transient_status(status: StatusCode) -> bool { + status.is_server_error() + || status == StatusCode::REQUEST_TIMEOUT + || status == StatusCode::TOO_MANY_REQUESTS +} + +/// A failure the same request may not meet again: the connection, a +/// timeout, or the transfer, never a refused redirect or a bad request. +pub(crate) fn transient(error: &reqwest::Error) -> bool { + !error.is_redirect() + && !error.is_builder() + && (error.is_connect() || error.is_timeout() || error.is_request() || error.is_body()) +} + +/// Send the request `build` makes, asking again after a transient failure +/// ([`transient`], [`transient_status`]) up to [`ATTEMPTS`] times. Returns +/// the first answer that is not transient, whatever its status: callers +/// check it. `what` names the request in the error. +pub(crate) fn send(what: &str, build: impl Fn() -> RequestBuilder) -> Result { + let mut wait = first_wait(); + let mut attempt = 1; + loop { + let failure = match build().send() { + Ok(response) if transient_status(response.status()) && attempt < ATTEMPTS => { + format!("{} answered {}", host_of(response.url()), response.status()) + } + Ok(response) => return Ok(response), + Err(error) if transient(&error) && attempt < ATTEMPTS => explain(&error), + Err(error) => { + let tries = match attempt { + 1 => String::new(), + n => format!(" after {n} attempts"), + }; + return Err(anyhow!("{what} failed{tries}: {}", explain(&error))); + } + }; + eprintln!( + "note: {what}: {failure}; trying again in {} s", + wait.as_secs().max(1) + ); + std::thread::sleep(wait); + wait *= 2; + attempt += 1; + } +} + +fn host_of(url: &reqwest::Url) -> String { + url.host_str().unwrap_or("the server").to_owned() +} + +/// `error` with every cause under it, and what a user can do about the +/// kinds of failure a network causes. +pub(crate) fn explain(error: &reqwest::Error) -> String { + let mut text = error.to_string(); + let mut source = error.source(); + while let Some(cause) = source { + let cause_text = cause.to_string(); + if !text.contains(&cause_text) { + text.push_str(": "); + text.push_str(&cause_text); + } + source = cause.source(); + } + let lower = text.to_ascii_lowercase(); + let hint = if lower.contains("dns error") + || lower.contains("failed to lookup address") + || lower.contains("name or service not known") + || lower.contains("no such host") + || lower.contains("nodename nor servname") + { + Some("this computer cannot look up the server's name: check its network connection") + } else if lower.contains("certificate") || lower.contains("unknownissuer") { + Some( + "the server's HTTPS certificate is not one this computer trusts. A network that \ + intercepts HTTPS does this: sign in to the network (a hotel or guest network's \ + page), or set HTTPS_PROXY to the proxy that network requires", + ) + } else if error.is_timeout() { + Some("the server did not answer in time: check the network connection, or try again later") + } else if lower.contains("connection refused") || lower.contains("network is unreachable") { + Some("this computer cannot reach the server: check its network connection and proxy") + } else { + None + }; + match hint { + Some(hint) => format!("{text} ({hint})"), + None => text, + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use reqwest::blocking::Client; + use std::{ + io::{Read, Write}, + net::TcpListener, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + }; + + /// Serve `replies` in order, one connection each, then close; returns + /// the URL and how many requests arrived. + pub(crate) fn serve(replies: Vec) -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let served = Arc::new(AtomicUsize::new(0)); + let count = served.clone(); + std::thread::spawn(move || { + for reply in replies { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let mut request = Vec::new(); + let mut buffer = [0; 4096]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") { + match stream.read(&mut buffer) { + Ok(0) | Err(_) => break, + Ok(n) => request.extend_from_slice(&buffer[..n]), + } + } + count.fetch_add(1, Ordering::SeqCst); + let _ = stream.write_all(reply.as_bytes()); + } + }); + (format!("http://{address}/file"), served) + } + + fn reply(status: &str, body: &str) -> String { + format!( + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + } + + #[test] + fn server_errors_and_rate_limits_are_asked_again() { + let (url, served) = serve(vec![ + reply("503 Service Unavailable", ""), + reply("429 Too Many Requests", ""), + reply("200 OK", "done"), + ]); + let client = Client::new(); + let response = send("the test request", || client.get(&url)).unwrap(); + assert_eq!(response.text().unwrap(), "done"); + assert_eq!(served.load(Ordering::SeqCst), 3); + } + + #[test] + fn a_refusal_is_returned_at_once_and_lasting_errors_stop() { + let (url, served) = serve(vec![reply("404 Not Found", "")]); + let client = Client::new(); + let response = send("the test request", || client.get(&url)).unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!(served.load(Ordering::SeqCst), 1); + // Every attempt answered 500: the last answer is returned. + let (url, served) = serve(vec![reply("500 Internal Server Error", ""); 5]); + let response = send("the test request", || client.get(&url)).unwrap(); + assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!(served.load(Ordering::SeqCst), ATTEMPTS as usize); + } + + #[test] + fn a_dropped_connection_is_asked_again_and_a_dead_server_named() { + // The first connection closes without an answer. + let (url, served) = serve(vec![String::new(), reply("200 OK", "done")]); + let client = Client::new(); + let response = send("the test request", || client.get(&url)).unwrap(); + assert_eq!(response.text().unwrap(), "done"); + assert_eq!(served.load(Ordering::SeqCst), 2); + // Nothing listens: every attempt fails, and the error says so. + let port = TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let error = send("the test request", || { + client.get(format!("http://127.0.0.1:{port}/file")) + }) + .unwrap_err() + .to_string(); + assert!( + error.starts_with("the test request failed after 5 attempts"), + "{error}" + ); + assert!(error.contains("cannot reach the server"), "{error}"); + } +} diff --git a/crates/stela-cli/src/restore.rs b/crates/stela-cli/src/restore.rs index c8b0a02b81..2fc8e655ad 100644 --- a/crates/stela-cli/src/restore.rs +++ b/crates/stela-cli/src/restore.rs @@ -386,13 +386,16 @@ fn download_with_client(image: &Image, output: &Path, client: &Client) -> Result return publish(image, output, &part, &metadata, offset); } } - let mut request = client - .get(&image.url) - .header(header::ACCEPT_ENCODING, "identity"); - if offset > 0 { - request = request.header(header::RANGE, format!("bytes={offset}-")); - } - let mut response = request.send()?.error_for_status()?; + let mut response = crate::net::send("downloading macOS", || { + let request = client + .get(&image.url) + .header(header::ACCEPT_ENCODING, "identity"); + match offset { + 0 => request, + _ => request.header(header::RANGE, format!("bytes={offset}-")), + } + })? + .error_for_status()?; let total; if response.status() == reqwest::StatusCode::PARTIAL_CONTENT { total = Some(range_total( diff --git a/crates/stela-cli/src/restore/aea.rs b/crates/stela-cli/src/restore/aea.rs index ebf0388aeb..5025ee15f1 100644 --- a/crates/stela-cli/src/restore/aea.rs +++ b/crates/stela-cli/src/restore/aea.rs @@ -279,7 +279,8 @@ pub fn fetch_public_key(metadata: &Metadata) -> Result { } })) .build()?; - let response = client.get(url.clone()).send()?.error_for_status()?; + let response = crate::net::send("fetching the public AEA key", || client.get(url.clone()))? + .error_for_status()?; let final_url = response.url().to_string(); let content_type = response .headers() diff --git a/crates/stela-cli/src/restore/history.rs b/crates/stela-cli/src/restore/history.rs index f06abc402d..76f07704ea 100644 --- a/crates/stela-cli/src/restore/history.rs +++ b/crates/stela-cli/src/restore/history.rs @@ -46,15 +46,18 @@ fn device_name(device: &Device) -> String { pub(super) fn load() -> Result { // One condensed request contains every model and historical release. // Avoid one request per model, or downloading any IPSW to discover versions. - let response = reqwest::blocking::Client::builder() - .connect_timeout(Duration::from_secs(5)) - .timeout(Duration::from_secs(25)) + // A connection may take a slow resolver, or a fallback from IPv6 to + // IPv4, beyond a few seconds. + let client = reqwest::blocking::Client::builder() + .connect_timeout(Duration::from_secs(15)) + .timeout(Duration::from_secs(60)) .redirect(reqwest::redirect::Policy::none()) .user_agent(concat!("stela/", env!("CARGO_PKG_VERSION"))) - .build()? - .get(URL) - .send()? - .error_for_status()?; + .build()?; + let response = crate::net::send("loading the list of macOS releases (api.ipsw.me)", || { + client.get(URL) + })? + .error_for_status()?; let mut bytes = Vec::new(); response .take(32 * 1024 * 1024 + 1) @@ -67,7 +70,19 @@ pub(super) fn load() -> Result { } fn parse(bytes: &[u8]) -> Result { - let catalog: Catalog = serde_json::from_slice(bytes)?; + let catalog: Catalog = serde_json::from_slice(bytes).map_err(|error| { + // A network that wants a sign-in first answers with its own page. + let page = bytes.trim_ascii_start().starts_with(b"<"); + anyhow::anyhow!( + "the list of macOS releases from api.ipsw.me cannot be read ({error}){}", + if page { + "; the network answered with a web page instead, as one that wants a sign-in \ + first does: sign in to the network and run setup again" + } else { + "" + } + ) + })?; let mut images: BTreeMap<(String, String), Image> = BTreeMap::new(); let mut models = BTreeMap::new(); for (model, device) in catalog.devices { @@ -146,6 +161,17 @@ mod tests { Ok(()) } + #[test] + fn a_web_page_instead_of_the_list_is_named() { + let error = parse(b"\nSign in") + .err() + .unwrap() + .to_string(); + assert!(error.contains("answered with a web page"), "{error}"); + let error = parse(b"{\"devices\": 1}").err().unwrap().to_string(); + assert!(!error.contains("web page"), "{error}"); + } + #[test] fn unsigned_releases_are_excluded() -> Result<()> { let mut catalog: serde_json::Value = diff --git a/crates/stela-cli/src/restore/remote.rs b/crates/stela-cli/src/restore/remote.rs index 856993e0ba..1de238797b 100644 --- a/crates/stela-cli/src/restore/remote.rs +++ b/crates/stela-cli/src/restore/remote.rs @@ -17,8 +17,18 @@ use std::{ /// Bytes fetched per request: large enough that a member streams at the /// connection's speed, small enough that a retry repeats little. const CHUNK: u64 = 16 * 1024 * 1024; -/// Attempts per range before the read fails. -const ATTEMPTS: u32 = 4; +/// Attempts per range before the read fails: with waits of 2, 4, 8, 16 and +/// 30 s between them, a connection that drops for about a minute, as Wi-Fi +/// changing access points does, pauses the download instead of ending it. +const ATTEMPTS: u32 = 6; +/// The longest wait between two attempts. +const MAX_WAIT: Duration = Duration::from_secs(30); +/// How long the first request, one byte, may take. +const OPEN_TIMEOUT: Duration = Duration::from_secs(60); +/// How long one range may take: a [`CHUNK`] at about 56 kB/s. A connection +/// that stalls is dropped and the range asked again, rather than waiting on +/// it for the client's whole-download limit. +const RANGE_TIMEOUT: Duration = Duration::from_secs(300); pub struct Remote { client: Client, @@ -34,12 +44,14 @@ pub struct Remote { impl Remote { /// Open `url`, pinning its ETag and length from a first range answer. pub fn open(client: Client, url: &str) -> Result { - let response = client - .get(url) - .header(header::ACCEPT_ENCODING, "identity") - .header(header::RANGE, "bytes=0-0") - .send()? - .error_for_status()?; + let response = crate::net::send(&format!("reading {url}"), || { + client + .get(url) + .header(header::ACCEPT_ENCODING, "identity") + .header(header::RANGE, "bytes=0-0") + .timeout(OPEN_TIMEOUT) + })? + .error_for_status()?; ensure!( response.status() == StatusCode::PARTIAL_CONTENT, "{url} does not serve byte ranges (status {}); download the whole image instead", @@ -83,7 +95,19 @@ impl Remote { let mut last = None; for attempt in 0..ATTEMPTS { if attempt > 0 { - std::thread::sleep(Duration::from_secs(1 << attempt)); + let wait = Duration::from_secs(1 << attempt).min(MAX_WAIT); + eprintln!( + "note: bytes {start}-{end} of {}: {}; trying again in {} s", + self.url, + last.as_ref() + .map_or(String::new(), |e: &anyhow::Error| format!("{e:#}")), + wait.as_secs() + ); + std::thread::sleep(if cfg!(test) { + Duration::from_millis(10) + } else { + wait + }); } match self.try_fetch(start, end) { Ok(chunk) => { @@ -108,10 +132,11 @@ impl Remote { .header(header::ACCEPT_ENCODING, "identity") .header(header::RANGE, format!("bytes={start}-{end}")) .header(header::IF_RANGE, &self.etag) + .timeout(RANGE_TIMEOUT) .send() - .map_err(|e| Retry::Again(e.into()))?; + .map_err(|e| Retry::Again(anyhow::anyhow!(crate::net::explain(&e))))?; let status = response.status(); - if status.is_server_error() { + if crate::net::transient_status(status) { return Err(Retry::Again(anyhow::anyhow!( "{} answered {status}", self.url @@ -138,7 +163,7 @@ impl Remote { let mut chunk = Vec::with_capacity((end - start + 1) as usize); response .read_to_end(&mut chunk) - .map_err(|e| Retry::Again(e.into()))?; + .map_err(|e| Retry::Again(anyhow::anyhow!("{} broke off: {e}", self.url)))?; if chunk.len() as u64 != end - start + 1 { return Err(Retry::Again(anyhow::anyhow!( "{} sent {} of {} bytes", @@ -322,6 +347,35 @@ mod tests { Ok(()) } + #[test] + fn a_failed_open_or_range_is_asked_again_from_the_same_offset() -> Result<()> { + let body: String = (0..100) + .map(|i| char::from(b'a' + (i % 26) as u8)) + .collect(); + let range = |span: &str, bytes: &str, length: usize| { + format!( + "HTTP/1.1 206 Partial Content\r\nETag: \"e\"\r\nContent-Range: bytes \ + {span}/100\r\nContent-Length: {length}\r\nConnection: close\r\n\r\n{bytes}" + ) + }; + let unavailable = + "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + let (url, served) = crate::net::tests::serve(vec![ + unavailable.into(), + range("0-0", &body[..1], 1), + unavailable.into(), + // A range that breaks off part way. + range("0-99", &body[..10], 100), + range("0-99", &body, 100), + ]); + let mut remote = Remote::open(Client::new(), &url)?; + let mut read = String::new(); + remote.read_to_string(&mut read)?; + assert_eq!(read, body); + assert_eq!(served.load(Ordering::SeqCst), 5); + Ok(()) + } + #[test] fn remote_server_requires_ranges_and_strong_etag() { let (url, _) = serve(body(), "\"pinned\"", 0); diff --git a/crates/stela-cli/src/setup/firmware.rs b/crates/stela-cli/src/setup/firmware.rs index cadb838d50..fa1d06f53c 100644 --- a/crates/stela-cli/src/setup/firmware.rs +++ b/crates/stela-cli/src/setup/firmware.rs @@ -48,11 +48,16 @@ fn read_cached(path: &Path, artifact: &Artifact) -> Result> { } fn download(client: &Client, artifact: &Artifact) -> Result> { - let mut response = client - .get(artifact.url()) - .header(header::ACCEPT_ENCODING, "identity") - .send()? - .error_for_status()?; + // A minute, and the file at 32 kB/s: a GPU's 64 MB firmware may take + // many minutes on a slow network. + let timeout = Duration::from_secs(60 + artifact.length as u64 / 32_000); + let mut response = crate::net::send(&format!("downloading {}", artifact.member), || { + client + .get(artifact.url()) + .header(header::ACCEPT_ENCODING, "identity") + .timeout(timeout) + })? + .error_for_status()?; ensure!( response.status() == reqwest::StatusCode::OK, "firmware source redirected or returned an unexpected status"