Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

An add-on download that breaks off goes on from where it stopped (1042)

gelenmedya75af60427253
diff --git a/crates/rf-app/src/addons.rs b/crates/rf-app/src/addons.rs
index 4b259506..da769f14 100644
--- a/crates/rf-app/src/addons.rs
+++ b/crates/rf-app/src/addons.rs
@@ -122,36 +122,121 @@ pub fn fetch_manifest() -> Result<Manifest, String> {
serde_json::from_slice(&bytes).map_err(|e| e.to_string())
}
-/// The bytes of `url` (a URL, or for testing a file path) into `to`, with the bytes so far told to `progress`; the SHA-256 of what
-/// was written.
-fn download(url: &str, to: &Path, progress: &dyn Fn(u64), cancelled: &dyn Fn() -> bool) -> Result<String, String> {
- let mut reader: Box<dyn Read> = if url.starts_with("http://") || url.starts_with("https://") {
- let resp = agent().get(url).call().map_err(|e| e.to_string())?;
- if resp.status().as_u16() != 200 {
- return Err(format!("HTTP {}", resp.status().as_u16()));
- }
- Box::new(resp.into_body().into_reader())
- } else {
- Box::new(std::fs::File::open(url).map_err(|e| format!("{url}: {e}"))?)
+/// Where a download is written: the file, the hash of what is in it and how much that is.
+struct Sink<'a> {
+ out: std::fs::File,
+ hash: Sha256,
+ done: u64,
+ progress: &'a dyn Fn(u64),
+}
+
+impl Sink<'_> {
+ fn take(&mut self, bytes: &[u8]) -> Result<(), String> {
+ std::io::Write::write_all(&mut self.out, bytes).map_err(|e| e.to_string())?;
+ self.hash.update(bytes);
+ self.done += bytes.len() as u64;
+ (self.progress)(self.done);
+ Ok(())
+ }
+
+ /// From the file's start again (a server that does not continue a file sends it whole).
+ fn restart(&mut self) -> Result<(), String> {
+ use std::io::Seek;
+ self.out.set_len(0).map_err(|e| e.to_string())?;
+ self.out.rewind().map_err(|e| e.to_string())?;
+ self.hash = Sha256::new();
+ self.done = 0;
+ (self.progress)(0);
+ Ok(())
+ }
+}
+
+/// How one request for a file ended: the server sent all it had, or the transfer broke off (with the reason).
+enum Got {
+ All,
+ Cut(String),
+}
+
+/// One request for `url` from the byte the sink stands at. A transfer that breaks off is not an error here: the caller asks again
+/// from where it stopped.
+fn fetch(url: &str, sink: &mut Sink, cancelled: &dyn Fn() -> bool) -> Result<Got, String> {
+ let from = sink.done;
+ let mut req = agent().get(url);
+ if from > 0 {
+ req = req.header("Range", format!("bytes={from}-"));
+ }
+ let resp = match req.call() {
+ Ok(r) => r,
+ Err(e) => return Ok(Got::Cut(e.to_string())),
};
- let mut out = std::fs::File::create(to).map_err(|e| format!("{}: {e}", to.display()))?;
- let mut hash = Sha256::new();
+ match (resp.status().as_u16(), from) {
+ (200, 0) | (206, _) => {}
+ (200, _) => sink.restart()?,
+ (status, _) => return Err(format!("HTTP {status}")),
+ }
+ let mut reader = resp.into_body().into_reader();
let mut buf = vec![0u8; 256 * 1024];
- let mut done = 0u64;
loop {
if cancelled() {
return Err("cancelled".into());
}
- let n = reader.read(&mut buf).map_err(|e| e.to_string())?;
- if n == 0 {
- break;
+ match reader.read(&mut buf) {
+ Ok(0) => return Ok(Got::All),
+ Ok(n) => sink.take(&buf[..n])?,
+ Err(e) => return Ok(Got::Cut(e.to_string())),
}
- std::io::Write::write_all(&mut out, &buf[..n]).map_err(|e| e.to_string())?;
- hash.update(&buf[..n]);
- done += n as u64;
- progress(done);
}
- Ok(hash.finalize().iter().map(|b| format!("{b:02x}")).collect())
+}
+
+/// How many requests in a row may bring nothing new before a download is given up.
+const DRY_TRIES: u32 = 3;
+
+/// The bytes of `url` (a URL, or for testing a file path) into `to`, with the bytes so far told to `progress`; the SHA-256 of what
+/// was written. `total` is the size the list names (0: not known).
+///
+/// A TRANSFER THAT BREAKS OFF IS CONTINUED (issue 1042: "timeout: receive body" at every try, on a connection that brings 50 to
+/// 300 KB/s). The time limit of a request covers its whole body, so a 7 MB file never arrived within it, and each try began again
+/// from nothing. Now the next request asks for the rest (`Range`), the file and its hash go on from where they stood, and the
+/// download is given up only when [`DRY_TRIES`] requests in a row bring nothing. The SHA-256 check afterwards is unchanged, so a
+/// file put together wrongly is still refused.
+fn download(url: &str, to: &Path, total: u64, progress: &dyn Fn(u64), cancelled: &dyn Fn() -> bool) -> Result<String, String> {
+ let out = std::fs::File::create(to).map_err(|e| format!("{}: {e}", to.display()))?;
+ let mut sink = Sink { out, hash: Sha256::new(), done: 0, progress };
+ if !(url.starts_with("http://") || url.starts_with("https://")) {
+ let mut reader = std::fs::File::open(url).map_err(|e| format!("{url}: {e}"))?;
+ let mut buf = vec![0u8; 256 * 1024];
+ loop {
+ if cancelled() {
+ return Err("cancelled".into());
+ }
+ let n = reader.read(&mut buf).map_err(|e| e.to_string())?;
+ if n == 0 {
+ break;
+ }
+ sink.take(&buf[..n])?;
+ }
+ } else {
+ let mut dry = 0u32;
+ while total == 0 || sink.done < total {
+ let before = sink.done;
+ let why = match fetch(url, &mut sink, cancelled)? {
+ Got::All if total == 0 || sink.done >= total => break,
+ Got::All => "the connection closed before the file was complete".to_string(),
+ Got::Cut(e) => e,
+ };
+ if sink.done > before {
+ dry = 0;
+ } else {
+ dry += 1;
+ if dry >= DRY_TRIES {
+ return Err(why);
+ }
+ std::thread::sleep(std::time::Duration::from_millis(400 * u64::from(dry)));
+ }
+ log::info!("add-on download: broke off at {} of {total} bytes ({why}); asking for the rest", sink.done);
+ }
+ }
+ Ok(sink.hash.finalize().iter().map(|b| format!("{b:02x}")).collect())
}
/// Installs (or updates to) `info`'s version for this machine: download, SHA-256 check, unpack beside any older version, switch
@@ -162,11 +247,14 @@ pub fn install(info: &AddonInfo, progress: &dyn Fn(u64, u64), cancelled: &dyn Fn
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let zip = dir.join(".download.zip");
let total = file.size;
- let got = download(&file.url, &zip, &|n| progress(n, total), cancelled);
+ let got = download(&file.url, &zip, total, &|n| progress(n, total), cancelled);
let sha = match got {
Ok(s) => s,
Err(e) => {
let _ = std::fs::remove_file(&zip);
+ // (nothing of an add-on that never arrived stays behind: an empty folder looked like a half install, issue 1042.
+ // `remove_dir` takes an empty folder only, so an installed version is safe)
+ let _ = std::fs::remove_dir(&dir);
return Err(e);
}
};
@@ -229,6 +317,83 @@ mod tests {
assert!(newer("v0.2.0", "0.1.9"));
}
+ /// A server on this machine that sends at most `chunk` bytes of `body` per request and then closes the connection, as a
+ /// transfer that breaks off; with `continues` it goes on from the `Range` asked for, without it it always starts again.
+ /// Returns its address and the count of requests it got.
+ fn breaking_server(body: Vec<u8>, chunk: usize, continues: bool) -> (String, std::sync::Arc<std::sync::atomic::AtomicU32>) {
+ use std::io::{BufRead, BufReader, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}/addon.zip", listener.local_addr().unwrap());
+ let hits = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
+ let counted = hits.clone();
+ std::thread::spawn(move || {
+ for stream in listener.incoming() {
+ let Ok(mut stream) = stream else { break };
+ counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let mut asked = 0usize;
+ let mut lines = BufReader::new(stream.try_clone().unwrap());
+ let mut line = String::new();
+ while lines.read_line(&mut line).is_ok_and(|n| n > 2) {
+ if let Some(v) = line.to_ascii_lowercase().strip_prefix("range: bytes=") {
+ asked = v.trim().trim_end_matches('-').parse().unwrap_or(0);
+ }
+ line.clear();
+ }
+ let from = if continues { asked.min(body.len()) } else { 0 };
+ let rest = &body[from..];
+ let status = if from > 0 { "206 Partial Content" } else { "200 OK" };
+ let _ = write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", rest.len());
+ let _ = stream.write_all(&rest[..rest.len().min(chunk)]);
+ }
+ });
+ (url, hits)
+ }
+
+ fn sha_of(bytes: &[u8]) -> String {
+ Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
+ }
+
+ fn scratch_file(name: &str) -> std::path::PathBuf {
+ std::env::temp_dir().join(format!("rf-addon-{}-{name}", std::process::id()))
+ }
+
+ /// Issue 1042: a connection that drops after every 300 KB still brings the whole megabyte, in four requests, and it is the
+ /// same file.
+ #[test]
+ fn a_download_that_breaks_off_goes_on_from_where_it_stopped() {
+ let body: Vec<u8> = (0..1_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();
+ let (url, hits) = breaking_server(body.clone(), 300_000, true);
+ let to = scratch_file("resume.zip");
+ let told = std::cell::Cell::new(0u64);
+ let sha = download(&url, &to, body.len() as u64, &|n| told.set(n), &|| false).unwrap();
+ assert_eq!(sha, sha_of(&body));
+ assert_eq!(std::fs::read(&to).unwrap(), body);
+ assert_eq!(told.get(), body.len() as u64);
+ assert_eq!(hits.load(std::sync::atomic::Ordering::Relaxed), 4);
+ let _ = std::fs::remove_file(&to);
+ }
+
+ /// A server that brings nothing is given up after a few requests, with an error.
+ #[test]
+ fn a_download_that_brings_nothing_is_given_up() {
+ let (url, hits) = breaking_server(vec![7u8; 50_000], 0, true);
+ let to = scratch_file("dry.zip");
+ assert!(download(&url, &to, 50_000, &|_| {}, &|| false).is_err());
+ assert_eq!(hits.load(std::sync::atomic::Ordering::Relaxed), DRY_TRIES);
+ let _ = std::fs::remove_file(&to);
+ }
+
+ /// A server that cannot continue a file starts it again each time: the file never grows past the first part, and that ends
+ /// too (no endless asking), with nothing wrong left as if it were whole.
+ #[test]
+ fn a_server_that_always_starts_again_does_not_keep_the_download_going_for_ever() {
+ let (url, hits) = breaking_server(vec![9u8; 100_000], 30_000, false);
+ let to = scratch_file("again.zip");
+ assert!(download(&url, &to, 100_000, &|_| {}, &|| false).is_err());
+ assert_eq!(hits.load(std::sync::atomic::Ordering::Relaxed), 1 + DRY_TRIES);
+ let _ = std::fs::remove_file(&to);
+ }
+
#[test]
fn a_list_is_read_and_the_machines_file_is_picked() {
let m: Manifest = serde_json::from_str(