diff --git a/Cargo.lock b/Cargo.lock index e62fe95..3cae3be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -583,6 +583,19 @@ dependencies = [ "digest", ] +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -853,6 +866,12 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "core-foundation" version = "0.9.4" @@ -2771,6 +2790,7 @@ dependencies = [ "aes", "arc-swap", "base64 0.23.1", + "blake3", "bytes", "cbc", "chrono", @@ -2784,6 +2804,7 @@ dependencies = [ "md-5", "medlar-testserver", "percent-encoding", + "quick-xml", "rcgen", "regex", "reqwest", @@ -2796,6 +2817,7 @@ dependencies = [ "rustls-platform-verifier", "serde", "serde_json", + "sha1", "sha2", "tempfile", "tokio", diff --git a/Plans/02 Engine/S009-mirrors-checksums.md b/Plans/02 Engine/S009-mirrors-checksums.md index b82e210..1eb44e2 100644 --- a/Plans/02 Engine/S009-mirrors-checksums.md +++ b/Plans/02 Engine/S009-mirrors-checksums.md @@ -10,12 +10,12 @@ FEATURES 1.8, 1.13. - crates/core/src/{segment,host,relink}* ## Steps -- [ ] Several sources per file: each checked with S008's comparison before its bytes are used; parts spread by measured speed; a bad mirror is dropped alone -- [ ] Metalink 3 and 4 files and the `Link`/`Digest` headers; piece hashes repair single pieces -- [ ] Checksums MD5, SHA-1, SHA-256, SHA-512, BLAKE3, hashed off the download threads; sources: metalink, sidecar files, headers, pasted text (type detected by length) -- [ ] Verify state and progress in the snapshot; mismatch offers repair (piece hashes), other mirror or restart -- [ ] XML parsing hardened: size and depth limits, no entities -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S009: …`, push +- [x] Several sources per file: each checked with S008's comparison before its bytes are used; parts spread by measured speed; a bad mirror is dropped alone +- [x] Metalink 3 and 4 files and the `Link`/`Digest` headers; piece hashes repair single pieces +- [x] Checksums MD5, SHA-1, SHA-256, SHA-512, BLAKE3, hashed off the download threads; sources: metalink, sidecar files, headers, pasted text (type detected by length) +- [x] Verify state and progress in the snapshot; mismatch offers repair (piece hashes), other mirror or restart +- [x] XML parsing hardened: size and depth limits, no entities +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S009: …`, push ## End criteria - `nice cargo test -j 2 -p medlar-core --test mirror` green: fast plus slow mirror, lying mirror, corrupt piece repaired diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 178245a..35f8867 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -17,7 +17,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S006](02%20Engine/S006-manager.md) Download manager, events and snapshots - [x] [S007](02%20Engine/S007-error-recovery.md) Error recovery - [x] [S008](02%20Engine/S008-continue-links.md) Continue from a new link -- [ ] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums +- [x] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums - [x] [S010](02%20Engine/S010-logins-proxies.md) Logins, cookies and proxies - [x] [S011](02%20Engine/S011-ftp-sftp.md) FTP, FTPS and SFTP - [ ] [S012](02%20Engine/S012-streams.md) HLS, DASH, RTSP and MMS diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index d3deb28..05379bf 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -9,6 +9,8 @@ description = "Medlar's engine, store and settings" aes = "0.9" arc-swap = "1.9.5" base64 = "0.23" +# In Rust alone, so that no C compiler is needed. +blake3 = { version = "1", default-features = false, features = ["pure", "std"] } bytes = "1.10" cbc = "0.2" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } @@ -21,6 +23,8 @@ log = { workspace = true, features = ["std"] } md-5 = "0.11.0" percent-encoding = "2.3.2" regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] } +# The one wayland-scanner has. +quick-xml = "0.41" roxmltree = "0.21" # Pinned: D-017. reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider", "socks"] } @@ -34,6 +38,7 @@ rustls = { version = "0.23.46", default-features = false, features = ["ring", "s rustls-platform-verifier = "0.7.1" serde.workspace = true serde_json.workspace = true +sha1 = "0.11" sha2 = "0.11.1" tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "process"] } tokio-rustls = { version = "0.26", default-features = false } diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 5a652cc..02528b4 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -319,6 +319,19 @@ "error.full": "{what}. {why}", "error.no_server": "The server", + "error.checksum": "File is damaged", + "error.checksum.why": "The complete file is not what its checksum says. It was kept under its unfinished name, or where it was.", + "verify.nothing": "No checksum", + "verify.open": "Not checked yet", + "verify.checking": "Checking", + "verify.good": "Matches its checksum", + "verify.bad": "Does not match its checksum", + "verify.repair": "Download the damaged pieces again", + "verify.other_mirror": "Start over from another mirror", + "verify.restart": "Start over", + "metalink.form": "This is not a metalink file, or it is broken.", + "metalink.unsafe": "This metalink file is larger or deeper than a sensible one, or defines things of its own. It was not read.", + "metalink.empty": "This metalink file has nothing that can be downloaded.", "log.retry": {"one": "Next try in {n} second", "other": "Next try in {n} seconds"}, "dialog.cancel": "Cancel", diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index 7017aee..79a0003 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -97,7 +97,7 @@ impl ErrorKind { Login => (Blocked, Retry::Never, Fix::SignIn), Forbidden | Expired | WrongContent | Link => (Blocked, Retry::Never, Fix::NewLink), NotFound | Rejected | BadLink => (Blocked, Retry::Never, Fix::EditLink), - Changed | NoResume => (Blocked, Retry::Never, Fix::Choose), + Changed | NoResume | Checksum => (Blocked, Retry::Never, Fix::Choose), Killed => (Passing, Retry::Never, Fix::Resume), Tls => (Serious, Retry::Never, Fix::TryAgain), Disk => (Serious, later(30, 600), Fix::ChangeFolder), @@ -201,6 +201,7 @@ impl Failure { E::Encoded(_) | E::BadReply(_) => ErrorKind::BadReply, // Stopped is no failure. E::Cut { .. } | E::Stopped => ErrorKind::Cut, + E::Checksum => ErrorKind::Checksum, E::Missing => ErrorKind::FileGone, E::Disk(e) => of_disk(e, place.folder), E::Store(_) => ErrorKind::List, diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index fe7a2f2..ed17d27 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -1,17 +1,22 @@ //! One file from link to disk. use super::fetch::compare; -use super::parts::Run; +use super::parts::{Ended, Run}; use super::*; use crate::adapt::{self, Timing}; use crate::disk::{PartialFile, blocking}; use crate::host::{self, Hosts}; use crate::limit::Group; +use crate::metalink; +use crate::mirror; use crate::model::{self, Part, Task, TaskId}; use crate::part::LivePart; +use crate::relink::{self, NewLink}; use crate::segment::Rules; use crate::store::Store; -use std::path::PathBuf; +use crate::verify::{Found, Wanted}; +use std::ops::Range; +use std::path::{Path, PathBuf}; use std::sync::Arc; /// What all downloads have in common. @@ -58,10 +63,87 @@ impl Default for Options { } } -/// Starts or continues the task and returns the finished file. Doesn't touch the task's state. +/// Times that wrong pieces come again before the download fails. +const REPAIRS: u32 = 3; +/// Waited for a metalink that the server tells of. +const ASIDE: Duration = Duration::from_secs(5); + +/// The file with all its bytes. +enum Whole { + /// Under its unfinished name. + Partial(PartialFile, u64), + Finished(PathBuf), +} + +impl Whole { + fn path(&self) -> &Path { + match self { + Whole::Partial(file, _) => file.path(), + Whole::Finished(path) => path, + } + } +} + +type Gave = Vec<(String, Vec>)>; + +/// Starts or continues the task and returns the finished file, compared with its checksum if it has one. Wrong pieces come again +/// if it has hashes of them. Doesn't touch the task's state. pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Options, monitor: &Monitor, mut stop: Stop) -> Result { - let (client, store) = (&shared.client, &shared.store); - let job = Job { store: store.clone(), id }; + let job = Job { store: shared.store.clone(), id }; + // Links that brought wrong bytes. + let (mut out, mut doubted) = (vec![], vec![]); + for round in 0.. { + let (whole, gave) = fetch_whole(shared, &job, &source, &out, options, monitor, &mut stop).await?; + let task = job.task().await?; + let wanted = Wanted { checksum: task.checksum.as_ref().and_then(|c| c.parse().ok()), pieces: task.pieces.clone() }; + let checked = monitor.checked(); + if !wanted.nothing() { + *checked.lock().unwrap() = Some(0.0); + } + let share = checked.clone(); + let found = wanted.compare(whole.path().to_path_buf(), move |x| *share.lock().unwrap() = Some(x), &stop).await; + *checked.lock().unwrap() = None; + let verified = match found? { + Found::Good(by) => Some(by), + Found::Nothing => None, + Found::Bad(ranges) if ranges.is_empty() || round == REPAIRS => return Err(Error::Checksum), + Found::Bad(ranges) => { + log::debug!("task {id}: {} wrong ranges come again", ranges.len()); + for (i, (url, gave)) in gave.into_iter().enumerate() { + let wrong = gave.iter().any(|g| ranges.iter().any(|r| r.start < g.end && g.start < r.end)); + // The base gets a second chance. + if wrong && (i > 0 || doubted.contains(&url)) { + out.push(url); + } else if wrong { + doubted.push(url); + } + } + job.forget(whole, ranges).await?; + continue; + } + }; + if task.verified != verified { + job.run(move |s| Ok(s.edit_task(id, move |t| t.verified = verified)?)).await?; + } + return match whole { + Whole::Partial(file, size) => job.finish(file, size).await, + Whole::Finished(path) => Ok(path), + }; + } + unreachable!("the last round returns") +} + +/// Until all bytes are here. +async fn fetch_whole( + shared: &Shared, + job: &Job, + source: &Source, + out: &[String], + options: &Options, + monitor: &Monitor, + stop: &mut Stop, +) -> Result<(Whole, Gave)> { + let (client, id) = (&shared.client, job.id); let (task, parts) = job.run(move |s| Ok((s.task(id)?, s.parts(id)?))).await?; let file = if parts.is_empty() { None @@ -72,12 +154,12 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt if !parts.is_empty() && parts.iter().all(finished) { let size = parts.iter().map(|p| p.done).sum(); match file { - Some(file) => return job.finish(file, size).await, - // Killed between the rename and the end. + Some(file) => return Ok((Whole::Partial(file, size), vec![])), + // Killed between the rename and the end, or done before. None => { let path = task.folder.join(&task.name); if path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == size) { - return Ok(path); + return Ok((Whole::Finished(path), vec![])); } } } @@ -87,15 +169,14 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt return Err(Error::Missing); } - let mut probe = probe(client, &source, &mut stop).await?; - if is_page(&task, &source, &probe) { - return Err(Error::Page); - } + let Opened { url, mut probe, compared } = open(client, &task, &parts, source, out, stop).await?; let body = probe.body.take(); - let link = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version.clone() }; + // Once on a mirror, its redirects are its own. + let here = if url == task.url { source.at(&probe.url) } else { source.mirror(&url)?.at(&probe.url) }; + let link = Link { client: client.clone(), source: here, ranges: probe.ranges, version: probe.version.clone() }; let (file, parts) = match file { - Some(file) => resume(&job, &task, file, parts, &link, &mut stop).await?, - None => start(&job, &task, probe).await?, + Some(file) => resume(job, &task, file, parts, &link, compared, stop).await?, + None => start(shared, job, &task, probe, &link, stop).await?, }; if let Some(size) = link.version.size { let reserving = file.clone(); @@ -107,10 +188,14 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt let known = job.run(move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default(); shared.hosts.set_host_cap(&host, link.source.max_connections().or(known.max_connections)); monitor.flow().put_limited(Group::Host(host.clone()), link.source.speed_limit().or(known.speed_limit)); - let start = host::tolerated(&known, model::now()).unwrap_or(adapt::START); - let mut run = Run::new(shared, link, file.clone(), parts, body, host.clone(), start, task.max_parts, options, monitor); - let result = run.go(&job, &mut stop).await; - let (live, learned) = run.end(); + let begin = host::tolerated(&known, model::now()).unwrap_or(adapt::START); + // Its name and more are known now. + let task = Arc::new(job.task().await?); + let mirrors = links(&task).into_iter().filter(|u| *u != url && !out.contains(u)).filter_map(|u| Some((u.clone(), source.mirror(&u).ok()?))); + let mirrors = if link.ranges { mirrors.collect() } else { vec![] }; + let mut run = Run::new(shared, task, (url, link), mirrors, file.clone(), parts, body, host.clone(), begin, options, monitor); + let result = run.go(job, stop).await; + let Ended { live, learned, gave } = run.end(); let saved = job.checkpoint(&live, &file).await; if let Some(n) = learned { job.run(move |s| Ok(host::remember(s, &host, n, model::now())?)).await?; @@ -119,7 +204,78 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt saved?; let size = live.iter().map(|p| p.get().done).sum(); let file = Arc::into_inner(file).expect("the parts have ended"); - job.finish(file, size).await + Ok((Whole::Partial(file, size), gave)) +} + +/// All links of the task, each once. +fn links(task: &Task) -> Vec { + let mut all = vec![task.url.clone()]; + for m in &task.mirrors { + if !all.contains(m) { + all.push(m.clone()); + } + } + all.truncate(metalink::MAX_URLS); + all +} + +struct Opened { + url: String, + probe: Probe, + /// What is here was compared with it. + compared: bool, +} + +/// The first link that works and has the file that is here. +async fn open(client: &Client, task: &Task, parts: &[Part], source: &Source, out: &[String], stop: &mut Stop) -> Result { + let mut failed = None; + for (i, url) in links(task).into_iter().enumerate() { + if out.contains(&url) { + continue; + } + let from = match if i == 0 { Ok(source.clone()) } else { source.mirror(&url) } { + Ok(from) => from, + Err(e) => { + failed.get_or_insert(e); + continue; + } + }; + match open_one(client, task, parts, from, i == 0, stop).await { + Ok((probe, compared)) => return Ok(Opened { url, probe, compared }), + Err(e @ (Error::Stopped | Error::Disk(_) | Error::Store(_) | Error::Missing)) => return Err(e), + Err(e) => { + log::debug!("link {i} of task {}: {e:?}", task.id); + failed.get_or_insert(e); + } + } + } + Err(failed.unwrap_or(Error::Checksum)) +} + +async fn open_one(client: &Client, task: &Task, parts: &[Part], source: Source, first: bool, stop: &mut Stop) -> Result<(Probe, bool)> { + let probe = probe(client, &source, stop).await?; + if is_page(task, &source, &probe) { + return Err(Error::Page); + } + let fits = |size| task.pieces.as_ref().is_none_or(|p| p.fit(size)); + if !probe.version.size.is_none_or(fits) { + return Err(Error::Changed); + } + if parts.is_empty() { + return Ok((probe, false)); + } + if first { + return if old(task).same_file(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) }; + } + let link = NewLink { url: source.url.to_string(), ..NewLink::default() }; + let checked = relink::check(client, task, parts, link, source, stop).await?; + let nothing = checked.reason == relink::Reason::Nothing && checked.ranges; + if mirror::usable(&checked) || nothing { Ok((probe, true)) } else { Err(Error::Changed) } +} + +/// The version the bytes here are of. +fn old(task: &Task) -> Validators { + Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() } } /// The server sent a web page, and the task is for something else. @@ -134,7 +290,8 @@ fn finished(p: &Part) -> bool { p.end == Some(p.start + p.done) } -async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc, Vec)> { +async fn start(shared: &Shared, job: &Job, task: &Task, probe: Probe, link: &Link, stop: &mut Stop) -> Result<(Arc, Vec)> { + let hints = hints(shared, task, &probe, link, stop).await?; let parts = vec![Part { start: 0, end: probe.version.size.filter(|_| probe.ranges), done: 0 }]; let wanted = safe_name(&task.name).unwrap_or(probe.name); let (id, saved, folder) = (job.id, parts.clone(), task.folder.clone()); @@ -148,6 +305,8 @@ async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc task.etag = probe.version.etag; task.last_modified = probe.version.last_modified; task.mime = probe.mime; + task.verified = None; + hints.put_in(task); })?; store.save_parts(id, saved)?; Ok(file) @@ -156,10 +315,42 @@ async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc Ok((Arc::new(file), parts)) } +/// What the server tells about the file, and the metalink it points to. Only what the task doesn't know yet counts. +async fn hints(shared: &Shared, task: &Task, probe: &Probe, link: &Link, stop: &mut Stop) -> Result { + let mut known = metalink::File { + checksum: probe.hints.checksum.clone(), + urls: probe.hints.mirrors.clone(), + ..metalink::File::default() + }; + let same = |f: &metalink::File| f.checksum.is_some() && f.checksum == known.checksum; + if let Some(url) = probe.hints.metalink.as_ref().filter(|_| task.pieces.is_none() && probe.ranges && known.checksum.is_some()) { + let source = link.source.mirror(url.as_str())?; + match tokio::time::timeout(ASIDE, metalink::read(&shared.client, &source, stop)).await { + Ok(Err(Error::Stopped)) => return Err(Error::Stopped), + Ok(Ok(files)) => { + if let Some(f) = files.into_iter().find(same) { + known.pieces = f.pieces; + known.urls.extend(f.urls); + } + } + // It would have been nice to have. + _ => {} + } + } + Ok(known) +} + /// Checks that the server still has the file the parts came from. -async fn resume(job: &Job, task: &Task, file: PartialFile, mut parts: Vec, link: &Link, stop: &mut Stop) -> Result<(Arc, Vec)> { - let old = Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() }; - if !old.same_file(&link.version) { +async fn resume( + job: &Job, + task: &Task, + file: PartialFile, + mut parts: Vec, + link: &Link, + compared: bool, + stop: &mut Stop, +) -> Result<(Arc, Vec)> { + if !compared && !old(task).same_file(&link.version) { return Err(Error::Changed); } let file = Arc::new(file); @@ -202,6 +393,27 @@ pub(super) struct Job { } impl Job { + async fn task(&self) -> Result { + let id = self.id; + self.run(move |s| Ok(s.task(id)?)).await + } + + /// Ranges of the file that have to come again. A finished file becomes an unfinished one. + async fn forget(&self, whole: Whole, ranges: Vec>) -> Result<()> { + let id = self.id; + self.run(move |store| { + let task = store.task(id)?; + let parts = mirror::without(&store.parts(id)?, &ranges); + if let Whole::Finished(path) = &whole { + let _names = disk::names(); + disk::rename_new(path, &disk::partial_path(&task.folder, &task.name)).map_err(disk::Error::Io)?; + } + store.save_parts(id, parts)?; + Ok(()) + }) + .await + } + pub(super) async fn run(&self, work: impl FnOnce(&Store) -> Result + Send + 'static) -> Result { let store = self.store.clone(); blocking(move || work(&store)).await diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index d31ece9..87f7e91 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -211,6 +211,42 @@ pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> same_body(&link.client, send_range(link, at, Some(at + len), stop).await?, known, stop).await } +/// `len` bytes at `at`. +pub(crate) async fn bytes_at(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result> { + let response = send_range(link, at, Some(at + len), stop).await?; + let data = all(&link.client, response, len, stop).await?; + if data.len() as u64 == len { Ok(data) } else { Err(Error::Cut { got: data.len() as u64, expected: Some(len) }) } +} + +/// A whole file of at most `max` bytes that is no web page. +pub(crate) async fn small(client: &Client, source: &Source, max: u64, stop: &mut Stop) -> Result> { + let response = source.get(client, None, None, stop).await?; + let headers = response.headers(); + if response.status() != StatusCode::OK { + return Err(status_error(&response)); + } + if page(name::mime(headers).as_deref()) { + return Err(Error::Page); + } + check_encoding(headers, response.url())?; + all(client, response, max, stop).await +} + +async fn all(client: &Client, mut response: Response, max: u64, stop: &mut Stop) -> Result> { + let mut data = vec![]; + loop { + let chunk = tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + chunk = client.wait(response.chunk()) => chunk?, + }; + let Some(chunk) = chunk else { return Ok(data) }; + if data.len() as u64 + chunk.len() as u64 > max { + return Err(Error::BadReply("more than there should be".into())); + } + data.extend_from_slice(&chunk); + } +} + /// Whether the body begins with `known`. pub(crate) async fn same_body(client: &Client, mut response: Response, known: &[u8], stop: &mut Stop) -> Result { let mut rest = known; diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 272180c..0983793 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -10,9 +10,9 @@ mod probe; pub use download::{Options, Shared, download}; pub(crate) use download::is_page; -pub(crate) use fetch::same_body; +pub(crate) use fetch::{bytes_at, same_body, small}; pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes}; -pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot}; +pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot}; pub use name::safe as safe_name; pub(crate) use piece::piece; pub use probe::{Probe, probe}; @@ -66,6 +66,8 @@ pub enum Error { Cut { got: u64, expected: Option }, /// Finished bytes are recorded, but their file is gone. Missing, + /// The whole file isn't what its checksum says. + Checksum, Disk(disk::Error), Store(store::Error), } @@ -249,6 +251,12 @@ impl Source { Source { url: url.clone(), headers, access: self.access.clone(), remote: self.remote.clone() } } + /// Another link to the same file. What was given for one site stays with it. + pub fn mirror(&self, url: &str) -> Result { + let url = Source::new(url)?.url; + Ok(Source { remote: Remote::of(&url).map(Arc::new), ..self.at(&url) }) + } + pub(crate) fn remote(&self) -> Option<&Remote> { self.remote.as_deref() } diff --git a/crates/core/src/http/monitor.rs b/crates/core/src/http/monitor.rs index 7e32173..d7ab27b 100644 --- a/crates/core/src/http/monitor.rs +++ b/crates/core/src/http/monitor.rs @@ -45,6 +45,27 @@ pub struct PartView { pub fails: u32, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServerState { + /// Not compared yet. + Waiting, + Checking, + Ready, + /// Another file, or it failed. + Out, +} + +/// A link that the download uses, or would like to. +#[derive(Debug, Clone, PartialEq)] +pub struct ServerView { + /// Name and port. Empty until it was reached. + pub host: String, + pub state: ServerState, + pub connections: u32, + /// Bytes per second of one connection. + pub speed: f64, +} + #[derive(Debug, Clone, Default, PartialEq)] pub struct Snapshot { pub size: Option, @@ -57,6 +78,10 @@ pub struct Snapshot { pub received: u64, /// Bytes per second. pub speed: f64, + /// The one the others are compared with first. + pub servers: Vec, + /// Share of the file that was compared with its checksum, while that goes on. + pub checked: Option, } /// One per download; outlives its runs. @@ -67,6 +92,7 @@ pub struct Monitor { state: Mutex<(Snapshot, Vec>)>, flow: Arc, finish: watch::Sender, + checked: Arc>>, } impl Monitor { @@ -76,7 +102,7 @@ impl Monitor { } pub fn with_flow(cap: u32, flow: Flow) -> Monitor { - Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow), finish: watch::Sender::new(false) } + Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow), finish: watch::Sender::new(false), checked: Arc::default() } } /// The limits that count for it. @@ -110,9 +136,15 @@ impl Monitor { let p = part.get(); (view.start, view.end, view.done) = (p.start, p.end, part.pos() - p.start); } + shot.checked = *self.checked.lock().unwrap(); shot } + /// Where the comparison with the checksum says how far it is. + pub(super) fn checked(&self) -> Arc>> { + self.checked.clone() + } + pub(crate) fn cap(&self) -> watch::Receiver { self.cap.subscribe() } diff --git a/crates/core/src/http/parts.rs b/crates/core/src/http/parts.rs index df5ccd2..3127b57 100644 --- a/crates/core/src/http/parts.rs +++ b/crates/core/src/http/parts.rs @@ -2,15 +2,17 @@ use super::download::Job; use super::fetch::fetch_within; -use super::monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot}; +use super::monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot}; use super::*; use crate::adapt::Adapt; use crate::disk::PartialFile; -use crate::host::{Hosts, Member, Permit}; -use crate::model::{ErrorKind, Part}; +use crate::host::{self, Hosts, Member, Permit}; +use crate::mirror::{self, NEEDED}; +use crate::model::{ErrorKind, Part, Task}; use crate::part::LivePart; use crate::segment::{self, Pick, View}; use std::hash::{BuildHasher, RandomState}; +use std::ops::Range; use std::sync::Arc; use std::time::Instant; use tokio::task::JoinSet; @@ -19,13 +21,22 @@ use tokio::time::{MissedTickBehavior, interval}; /// Speeds are averaged over about this many ticks. const SMOOTH: u32 = 8; +/// The server the others are compared with. +const BASE: usize = 0; + pub(super) struct Run<'a> { - link: Arc, + shared: &'a Shared, + task: Arc, + /// The base first, then the mirrors. + servers: Vec, + checks: JoinSet<(usize, Result>)>, + /// Why the last server that was given up failed. + gave_up: Option, + /// Servers whose bytes have to come again. Nothing runs meanwhile. + distrusted: Vec, file: Arc, body: Option, - host: String, hosts: Arc, - member: Member, /// Its speed had a limit, so it says nothing about the host. limited: bool, max_parts: Option, @@ -47,6 +58,49 @@ pub(super) struct Run<'a> { worked: u32, } +/// One link to the file. +struct Server { + /// As the task has it. + url: String, + source: Source, + state: ServerState, + ready: Option, + /// Bytes per second of one of its connections. + speed: Option, + /// No connection before this. + rest_until: Option, + /// In a row, without a byte. + fails: u32, + /// Connections it stands, as far as it said so. Counts only beside others. + cap: u32, + used: bool, + /// What came from it. + gave: Vec>, +} + +struct Ready { + link: Arc, + host: String, + member: Member, +} + +impl Server { + fn new(url: String, source: Source) -> Server { + Server { url, source, state: ServerState::Waiting, ready: None, speed: None, rest_until: None, fails: 0, cap: u32::MAX, used: false, gave: vec![] } + } + + fn open(&self, now: Instant) -> bool { + self.state == ServerState::Ready && self.rest_until.is_none_or(|until| now >= until) + } + + fn got(&mut self, range: Range) { + match self.gave.iter_mut().find(|r| r.end == range.start) { + Some(r) => r.end = range.end, + None => self.gave.push(range), + } + } +} + struct Slot { id: PartId, part: Arc, @@ -59,9 +113,14 @@ struct Slot { swaps: u32, /// Had a connection before. used: bool, + /// The server its last bytes came from. + last: Option, } struct Worker { + server: usize, + /// Where it began. + from: u64, stop: watch::Sender, permit: Permit, leaving: bool, @@ -87,6 +146,15 @@ impl Slot { } } +/// What is left of a run. +pub(super) struct Ended { + pub live: Vec>, + /// The number of connections to remember for the base's host. + pub learned: Option, + /// The links, the base's first, and what came from each. + pub gave: Vec<(String, Vec>)>, +} + /// What an error of one part means for the download. enum Weight { Fatal, @@ -113,24 +181,33 @@ fn weigh(e: &Error) -> Weight { impl<'a> Run<'a> { #[allow(clippy::too_many_arguments)] pub(super) fn new( - shared: &Shared, - link: Link, + shared: &'a Shared, + task: Arc, + base: (String, Link), + mirrors: Vec<(String, Source)>, file: Arc, parts: Vec, body: Option, host: String, start: u32, - max_parts: Option, options: &'a Options, monitor: &'a Monitor, ) -> Run<'a> { let cap = *monitor.cap().borrow(); + let max_parts = task.max_parts; + let (url, link) = base; + let mut base = Server::new(url, link.source.clone()); + base.ready = Some(Ready { member: shared.hosts.join(&host), link: Arc::new(link), host }); + base.state = ServerState::Ready; let mut run = Run { - link: Arc::new(link), + shared, + task, + servers: std::iter::once(base).chain(mirrors.into_iter().map(|(url, source)| Server::new(url, source))).collect(), + checks: JoinSet::new(), + gave_up: None, + distrusted: vec![], file, body, - member: shared.hosts.join(&host), - host, hosts: shared.hosts.clone(), limited: false, max_parts, @@ -167,12 +244,18 @@ impl<'a> Run<'a> { } let mut saving = JoinSet::new(); loop { - if self.failed.is_none() { + if !self.distrusted.is_empty() && self.workers.is_empty() && self.failed.is_none() { + self.take_back(); + checkpoint.reset_immediately(); + } + if self.failed.is_none() && self.distrusted.is_empty() { let flow = self.monitor.flow(); self.limited |= flow.limited(); let cap = *cap.borrow_and_update(); self.adapt.set_cap(cap.min(self.max_parts.unwrap_or(u32::MAX)).min(flow.connections())); - self.schedule(Instant::now()); + let now = Instant::now(); + self.look_at_mirrors(); + self.schedule(now); } self.publish(); if self.workers.is_empty() && (self.failed.is_some() || self.slots.iter().all(|s| s.part.finished())) { @@ -183,6 +266,10 @@ impl<'a> Run<'a> { Ok((id, result)) => self.ended(id, result, Instant::now()), Err(e) => std::panic::resume_unwind(e.into_panic()), }, + Some(checked) = self.checks.join_next() => match checked { + Ok((server, result)) => self.checked(server, result), + Err(e) => std::panic::resume_unwind(e.into_panic()), + }, _ = tick.tick() => self.measure(Instant::now()), _ = checkpoint.tick(), if saving.is_empty() => { let (job, live, file) = (job.clone(), self.live(), self.file.clone()); @@ -207,9 +294,187 @@ impl<'a> Run<'a> { self.failed.take().map_or(Ok(()), Err) } - /// The parts, and the number of connections to remember for the host. Lets go of the file. - pub(super) fn end(self) -> (Vec>, Option) { - (self.live(), self.adapt.learned().filter(|_| self.link.ranges && !self.limited)) + /// Lets go of the file. + pub(super) fn end(self) -> Ended { + let alone = self.servers.iter().filter(|s| s.used).count() == 1; + let learned = self.adapt.learned().filter(|_| self.base().ranges && !self.limited && alone); + let live = self.live(); + Ended { live, learned, gave: self.servers.into_iter().map(|s| (s.url, s.gave)).collect() } + } + + fn base(&self) -> &Arc { + &self.servers[BASE].ready.as_ref().expect("the base is always ready").link + } + + // Mirrors. + + /// Compares the next one, when enough is here for that. + fn look_at_mirrors(&mut self) { + let Some(i) = self.servers.iter().position(|s| s.state == ServerState::Waiting) else { return }; + if !self.checks.is_empty() || !self.can_check() { + return; + } + let parts: Vec = self.slots.iter().map(|s| s.part.get()).collect(); + self.servers[i].state = ServerState::Checking; + let (shared, task, base, source) = (self.shared.clone(), self.task.clone(), self.base().clone(), self.servers[i].source.clone()); + self.checks.spawn(async move { + let (_keep, stop) = watch::channel(false); + let check = async { + let Some(link) = mirror::check(shared.client, (*task).clone(), parts, (*base).clone(), source, stop).await? else { return Ok(None) }; + let host = host::key(&link.source.url); + let (store, asked) = (shared.store.clone(), host.clone()); + let known = crate::disk::blocking(move || store.host(&asked)).await?.unwrap_or_default(); + // The limit of a host counts for a whole download; that is the base's. + let limited = link.source.speed_limit().or(known.speed_limit).is_some(); + if limited && host != host::key(&base.source.url) { + return Ok(None); + } + shared.hosts.set_host_cap(&host, link.source.max_connections().or(known.max_connections)); + Ok(Some(link)) + }; + (i, check.await) + }); + } + + fn can_check(&self) -> bool { + self.base().ranges && self.slots.iter().map(|s| s.part.get().done).sum::() >= NEEDED + } + + fn checked(&mut self, i: usize, result: Result>) { + let s = &mut self.servers[i]; + match result { + Ok(Some(link)) => { + let host = host::key(&link.source.url); + s.ready = Some(Ready { member: self.hosts.join(&host), link: Arc::new(link), host }); + s.state = ServerState::Ready; + } + other => { + log::debug!("mirror {i} not used: {:?}", other.err()); + s.state = ServerState::Out; + self.any_left(); + } + } + } + + /// Whether another one than `i` can go on, now or after its comparison. + fn others_than(&self, i: usize) -> bool { + let can_check = self.can_check(); + self.servers.iter().enumerate().any(|(j, s)| { + j != i + && match s.state { + ServerState::Ready | ServerState::Checking => true, + ServerState::Waiting => can_check, + ServerState::Out => false, + } + }) + } + + /// Gives a server up. Its bytes come again if it is not trusted any more. + fn expel(&mut self, i: usize, e: Error, trusted: bool) { + log::debug!("server {i} given up: {e:?}"); + self.servers[i].state = ServerState::Out; + self.gave_up = Some(e); + for s in self.slots.iter_mut().filter(|s| s.worker.as_ref().is_some_and(|w| w.server == i)) { + s.send_away(); + } + if !trusted { + self.distrusted.push(i); + self.slots.iter_mut().for_each(Slot::send_away); + } + self.any_left(); + } + + fn any_left(&mut self) { + if !self.others_than(usize::MAX) + && let Some(e) = self.gave_up.take() + { + self.fail(e); + } + } + + /// Nothing runs: the parts lose what came from the distrusted ones. + fn take_back(&mut self) { + let bad: Vec<_> = self.distrusted.drain(..).flat_map(|i| std::mem::take(&mut self.servers[i].gave)).collect(); + let parts: Vec = self.slots.iter().map(|s| s.part.get()).collect(); + self.slots.clear(); + for p in mirror::without(&parts, &bad) { + let slot = self.slot(p); + self.events.push(PartEvent::Born { id: slot.id, start: p.start, end: p.end }); + self.slots.push(slot); + } + self.merge(); + } + + fn running_on(&self, i: usize) -> u32 { + self.slots.iter().filter_map(Slot::running).filter(|w| w.server == i).count() as u32 + } + + fn many(&self) -> bool { + self.servers.iter().filter(|s| s.state == ServerState::Ready).count() > 1 + } + + /// A place for one more connection at the server that brings the most; one that wasn't tried comes first. + fn place(&self, weight: f64, now: Instant) -> Option<(usize, Permit)> { + let many = self.many(); + let mut open: Vec = (0..self.servers.len()).filter(|i| self.servers[*i].open(now)).collect(); + // One that has just begun is taken for an average one. + let speed = |i: &usize| { + let s = &self.servers[*i]; + if s.used { s.speed.unwrap_or(self.usual) } else { f64::INFINITY } + }; + open.sort_by(|a, b| speed(b).total_cmp(&speed(a))); + open.into_iter().find_map(|i| { + let running = self.running_on(i); + if many && running >= self.servers[i].cap { + return None; + } + let wanted = if many { running + 1 } else { self.wanted() }; + Some((i, self.servers[i].ready.as_ref()?.member.open(wanted, weight, now)?)) + }) + } + + /// Others on the host get what isn't used. + fn tell_hosts(&self, wanted: u32, weight: f64) { + let many = self.many(); + for (i, s) in self.servers.iter().enumerate() { + let Some(r) = &s.ready else { continue }; + let wanted = match s.state { + ServerState::Ready if many => self.running_on(i) + 1, + ServerState::Ready => wanted, + _ => 0, + }; + r.member.wants(wanted, weight); + } + } + + /// Moves one connection to a server that is far faster, or that wasn't tried. + fn balance(&mut self, now: Instant) { + let idle = |s: &Slot| s.worker.as_ref().is_none_or(|w| !w.leaving); + if !self.many() || self.running() < 2 || self.running() < self.wanted() || !self.slots.iter().all(idle) { + return; + } + let untried = self.servers.iter().any(|s| s.open(now) && !s.used); + let best = (0..self.servers.len()).filter(|i| self.servers[*i].open(now) && self.running_on(*i) < self.servers[*i].cap); + let best = best.filter_map(|i| Some((i, self.servers[i].speed?))).max_by(|a, b| a.1.total_cmp(&b.1)); + let (usual, options) = (self.usual, self.options); + let speed = |w: &Worker| w.speed.unwrap_or(usual); + // Within limits the slow ones only wait for their turn. + let limited = self.monitor.flow().limited(); + let slowest = self.slots.iter_mut().filter(|s| s.running().is_some()).min_by(|a, b| { + let of = |s: &Slot| s.running().map_or(f64::INFINITY, speed); + of(a).total_cmp(&of(b)) + }); + let Some(s) = slowest else { return }; + let patience = options.patience * (1 << s.swaps.min(8)); + let Some(w) = s.running() else { return }; + let long = w.delivers.is_some_and(|since| now - since >= patience); + let far = best.is_some_and(|(i, best)| i != w.server && speed(w) < best / 4.0); + if untried { + s.send_away(); + } else if long && far && !limited { + s.swaps += 1; + s.send_away(); + } } fn live(&self) -> Vec> { @@ -218,7 +483,7 @@ impl<'a> Run<'a> { fn slot(&mut self, part: Part) -> Slot { self.next_id += 1; - Slot { id: self.next_id, part: LivePart::new(part), worker: None, rest_until: None, fails: 0, swaps: 0, used: false } + Slot { id: self.next_id, part: LivePart::new(part), worker: None, rest_until: None, fails: 0, swaps: 0, used: false, last: None } } fn fail(&mut self, e: Error) { @@ -235,17 +500,17 @@ impl<'a> Run<'a> { } fn wanted(&self) -> u32 { - if self.link.ranges { self.adapt.target() } else { 1 } + if self.base().ranges { self.adapt.target() } else { 1 } } fn schedule(&mut self, now: Instant) { - if !self.link.ranges { + if !self.base().ranges { // One part without resume: no cuts, no second connection. let i = self.slots.iter().position(|s| !s.part.finished()); if let Some(i) = i.filter(|i| self.slots[*i].worker.is_none()) - && let Some(permit) = self.member.open(1, self.monitor.flow().weight(), now) + && let Some(permit) = self.servers[BASE].ready.as_ref().and_then(|r| r.member.open(1, self.monitor.flow().weight(), now)) { - self.begin(i, permit, now); + self.begin(i, BASE, permit, now); } return; } @@ -262,6 +527,7 @@ impl<'a> Run<'a> { slowest.map(Slot::send_away); } self.drop_stalled(now); + self.balance(now); let weight = self.monitor.flow().weight(); // How many it could use. let mut use_of = self.wanted(); @@ -276,9 +542,9 @@ impl<'a> Run<'a> { self.drop_crawling(&views, now); break; }; - let Some(permit) = self.member.open(self.wanted(), weight, now) else { break }; + let Some((server, permit)) = self.place(weight, now) else { break }; match pick { - Pick::Take(i) => self.begin(i, permit, now), + Pick::Take(i) => self.begin(i, server, permit, now), Pick::Split { part, at } => { let end = views[part].end; // False when it got beyond `at` in the meantime. @@ -288,11 +554,11 @@ impl<'a> Run<'a> { let slot = self.slot(Part { start: at, end: Some(end), done: 0 }); self.events.push(PartEvent::Split { from: self.slots[part].id, id: slot.id, at, end }); self.slots.insert(part + 1, slot); - self.begin(part + 1, permit, now); + self.begin(part + 1, server, permit, now); } } } - self.member.wants(use_of, weight); + self.tell_hosts(use_of, weight); } /// A connection that brings nothing is replaced. One that never did only while others do: the server may be slow to answer. @@ -327,16 +593,21 @@ impl<'a> Run<'a> { } } - fn begin(&mut self, i: usize, permit: Permit, now: Instant) { + fn begin(&mut self, i: usize, server: usize, permit: Permit, now: Instant) { + let from = &mut self.servers[server]; + from.used = true; + let link = from.ready.as_ref().expect("only ready ones are used").link.clone(); let s = &mut self.slots[i]; if s.used { self.events.push(PartEvent::Stolen { id: s.id }); } let (stop, stopping) = watch::channel(false); let first = s.part.received(); - s.worker = Some(Worker { stop, permit, leaving: false, first, seen: first, quiet_since: now, delivers: None, speed: None }); + let p = s.part.get(); + s.worker = Some(Worker { server, from: p.start + p.done, stop, permit, leaving: false, first, seen: first, quiet_since: now, delivers: None, speed: None }); (s.used, s.rest_until) = (true, None); - let (id, link, part, file, body) = (s.id, self.link.clone(), s.part.clone(), self.file.clone(), self.body.take()); + let (id, part, file) = (s.id, s.part.clone(), self.file.clone()); + let body = if server == BASE { self.body.take() } else { None }; let flow = self.monitor.flow().clone(); self.workers.spawn(async move { (id, fetch_within(&link, &part, &file, body, &flow, stopping).await) }); } @@ -347,10 +618,17 @@ impl<'a> Run<'a> { let w = s.worker.take().expect("it just ended"); let got = s.part.received(); self.received += got - w.seen; + let before = s.last; + let (p, server) = (s.part.get(), &mut self.servers[w.server]); + if p.start + p.done > w.from { + server.got(w.from..p.start + p.done); + s.last = Some(w.server); + } if got > w.first { - s.fails = 0; + (s.fails, server.fails) = (0, 0); } else if result.is_err() && !w.leaving { s.fails += 1; + server.fails += 1; } match result { Ok(()) => { @@ -363,14 +641,25 @@ impl<'a> Run<'a> { self.merge(); } Err(Error::Stopped) if w.leaving => {} - Err(e) if self.failed.is_some() || !self.link.ranges => self.fail(e), - Err(e) => self.broken(i, e, now), + Err(e) if self.failed.is_some() || !self.base().ranges => self.fail(e), + // Its server was given up for the same. + Err(_) if self.servers[w.server].state == ServerState::Out => {} + Err(e) => self.broken(i, w.server, before, e, now), } } /// One part failed. The others go on. - fn broken(&mut self, i: usize, e: Error, now: Instant) { - let (others, running) = (self.delivering(), self.running()); + fn broken(&mut self, i: usize, server: usize, before: Option, e: Error, now: Instant) { + // It compared what another one brought. + let liar = before.filter(|b| matches!(e, Error::Changed) && server == BASE && *b != BASE).unwrap_or(server); + let local = matches!(e, Error::Disk(_) | Error::Store(_) | Error::Missing); + if !local && self.others_than(liar) { + return self.broken_beside_others(i, liar, e, now); + } + if liar != server { + return self.expel(liar, e, false); + } + let (others, running, host) = (self.delivering(), self.running(), self.host(server).to_string()); let retry_after = if let Error::Status { retry_after, .. } = &e { *retry_after } else { None }; let s = &mut self.slots[i]; let wait = backoff(self.options, s.fails).max(retry_after.unwrap_or_default()); @@ -379,7 +668,8 @@ impl<'a> Run<'a> { if matches!(weight, Weight::Refused { again: true }) && others == 0 && running > 0 { // Maybe too many at once, though none got anywhere: for now fewer, also if this run ends. let pause = retry_after.unwrap_or_default().min(self.options.timing.refused); - self.hosts.refused(&self.host, now + pause + self.options.timing.window * 3); + let until = now + pause + self.options.timing.window * 3; + self.hosts.refused(&host, until); } match weight { Weight::Fatal => return self.fail(e), @@ -391,18 +681,48 @@ impl<'a> Run<'a> { self.worked = running; self.adapt.refused(now, running, others > 0); if others > 0 { - self.hosts.refused(&self.host, now + self.options.timing.refused); + self.hosts.refused(&host, now + self.options.timing.refused); } } Weight::Broken => {} } if let Some(pause) = retry_after { - self.hosts.rest(&self.host, now + pause); + self.hosts.rest(&host, now + pause); } self.slots[i].rest_until = Some(now + wait); log::debug!("part {} failed, again in {wait:?}: {e:?}", self.slots[i].id); } + /// The same where another server can go on. + fn broken_beside_others(&mut self, i: usize, server: usize, e: Error, now: Instant) { + // The base's bytes are what the others were compared with. + let trusted = !matches!(e, Error::Changed) || server == BASE; + let weight = weigh(&e); + if matches!(weight, Weight::Fatal | Weight::Refused { again: false }) || self.servers[server].fails >= self.options.tries { + return self.expel(server, e, trusted); + } + let retry_after = if let Error::Status { retry_after, .. } = &e { retry_after.unwrap_or_default() } else { Duration::ZERO }; + let running = self.running_on(server); + if matches!(weight, Weight::Refused { .. }) { + self.hosts.refused(self.host(server), now + self.options.timing.refused); + self.servers[server].cap = running.max(1); + } + let wait = backoff(self.options, self.servers[server].fails).max(retry_after); + let s = &mut self.servers[server]; + // Those that still run show that it isn't down. + if running == 0 || !retry_after.is_zero() { + s.rest_until = Some(now + wait); + } + if !self.servers.iter().any(|s| s.open(now)) { + self.slots[i].rest_until = Some(now + wait); + } + log::debug!("part {} failed at server {server}, again in {wait:?}: {e:?}", self.slots[i].id); + } + + fn host(&self, server: usize) -> &str { + self.servers[server].ready.as_ref().map_or("", |r| &r.host) + } + /// Neighbours that are whole become one. fn merge(&mut self) { let whole = |s: &Slot| s.worker.is_none() && s.part.finished(); @@ -449,6 +769,12 @@ impl<'a> Run<'a> { speeds.push(speed); } } + for (i, server) in self.servers.iter_mut().enumerate() { + let own: Vec = self.slots.iter().filter_map(Slot::running).filter(|w| w.server == i).filter_map(|w| w.speed).collect(); + if !own.is_empty() { + server.speed = Some(own.iter().sum::() / own.len() as f64); + } + } self.speed = smooth(self.speed, (self.received - before) as f64 / secs); // The last one left is compared with what others brought before. if speeds.len() > 1 { @@ -476,8 +802,15 @@ impl<'a> Run<'a> { PartView { id: s.id, start: p.start, end: p.end, done: s.part.pos() - p.start, state, speed, fails: s.fails } }); let shot = Snapshot { - size: self.link.version.size, + size: self.base().version.size, parts: parts.collect(), + servers: (0..self.servers.len()) + .map(|i| { + let s = &self.servers[i]; + ServerView { host: self.host(i).into(), state: s.state, connections: self.running_on(i), speed: s.speed.unwrap_or(0.0) } + }) + .collect(), + checked: None, connections: self.running(), wanted: self.wanted(), received: self.received, diff --git a/crates/core/src/http/probe.rs b/crates/core/src/http/probe.rs index f77bf3f..31bc06d 100644 --- a/crates/core/src/http/probe.rs +++ b/crates/core/src/http/probe.rs @@ -1,6 +1,7 @@ //! What a link leads to. use super::*; +use crate::metalink::{self, Hints}; #[derive(Debug)] pub struct Probe { @@ -12,6 +13,8 @@ pub struct Probe { /// Safe to use as a file name. pub name: String, pub mime: Option, + /// Checksum and mirrors the headers tell of. + pub hints: Hints, /// The whole file, already on its way: the server sent it instead of a range. Use it, or drop it to hang up. pub body: Option, } @@ -44,6 +47,7 @@ pub async fn probe(client: &Client, source: &Source, stop: &mut Stop) -> Result< version: Validators::of(headers, size), name: name::pick(source, &url, headers), mime: name::mime(headers), + hints: metalink::hints(headers, &url), body: None, url, }; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 415ae11..0cd25cd 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,6 +14,8 @@ pub mod limit; pub mod listing; pub mod logging; pub mod manager; +pub mod metalink; +pub mod mirror; pub mod model; pub mod net_state; pub mod part; @@ -34,5 +36,6 @@ pub mod stream; pub mod strings; pub mod tls; mod transport; +pub mod verify; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 603a84b..6248354 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -21,7 +21,8 @@ use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals}; use crate::speed::{History, Meter}; use crate::store::{self, Store}; use crate::stream::{self, Tools}; -use crate::{adopt, disk, host, redact, site, strings, tr}; +use crate::verify::Checksum; +use crate::{adopt, disk, host, metalink, redact, site, strings, tr, verify}; use arc_swap::ArcSwap; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::path::{Path, PathBuf}; @@ -72,6 +73,8 @@ struct Run { known: bool, /// What was on disk before it began. had: u64, + /// It was done before: only compares it again. + again: bool, } /// What a waiting download waits for. @@ -111,6 +114,7 @@ struct Entry { resumable: Option, /// Its next run ends a stream at once. finish: bool, + checked: f32, meter: Meter, history: Arc, /// Bytes of the second that isn't over. @@ -139,6 +143,7 @@ impl Entry { wanted: 0, resumable: None, finish: false, + checked: 0.0, meter: Meter::default(), history: Arc::default(), second: 0, @@ -191,7 +196,7 @@ impl Entry { connections: self.connections, wanted: self.wanted, resumable: self.resumable, - checked: 0.0, + checked: if self.task.state == State::Checking { self.checked } else { 0.0 }, retry_at: if let Some(Hold::Until(_, at)) = self.hold { Some(at) } else { None }, fails: self.fails, server: self.host.clone(), @@ -381,6 +386,8 @@ impl Actor { Msg::Command(command, answer) => self.command(command, answer), Msg::Check(id, link, answer) => self.check(id, link, answer), Msg::CheckPartial(path, link, answer) => self.check_partial(path, link, answer), + Msg::FindChecksum(id, answer) => self.find_checksum(id, answer), + Msg::ReadMetalink(link, answer) => self.read_metalink(link, answer), Msg::Limits(limits) => self.set_limits(limits), Msg::OnChange(call) => self.on_change.push(call), Msg::Ended(id, result) => self.ended(id, result), @@ -511,7 +518,7 @@ impl Actor { fn must_wait(&self, id: TaskId, command: &Command) -> bool { use Command::*; let e = &self.entries[&id]; - let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | Restore(_) | Continue { .. }); + let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | OtherMirror(_) | Restore(_) | Continue { .. }); !e.todo.is_empty() || match e.work { None => false, @@ -607,6 +614,20 @@ impl Actor { None => result = Err(Error::Name), }, Command::Edit { edit, .. } => result = self.change(id, edit), + Command::Verify(_) if state == Done => return self.verify(id, answer), + Command::Verify(_) => {} + Command::OtherMirror(_) => { + let Some(next) = self.entries[&id].task.mirrors.first().cloned() else { return self.answer(answer, Ok(id)) }; + // The link of now becomes the last one. + result = self.change(id, |t| { + let old = std::mem::replace(&mut t.url, next); + t.mirrors.remove(0); + t.mirrors.push(old); + }); + if result.is_ok() { + return self.apply(id, Command::Redownload(id), answer); + } + } Command::AwaitLink(_) => result = self.await_link(id), Command::Continue { checked, .. } => return self.go_on(id, *checked, answer), Command::Remove { .. } | Command::KeepBoth(_) => {} @@ -623,6 +644,8 @@ impl Actor { task.state = State::Queued; } task.name = safe_name(&task.name).unwrap_or_default(); + task.checksum = task.checksum.map(verify::plain); + task.verified = None; (task.error, task.downloaded, task.finished_at, task.removed_at) = (None, 0, None, None); if task.position == 0.0 { task.position = self.last_position + 1.0; @@ -669,6 +692,30 @@ impl Actor { }); } + fn find_checksum(&self, id: TaskId, answer: oneshot::Sender>>) { + let Some(e) = self.entries.get(&id).filter(|e| !e.removed()) else { + let _ = answer.send(Err(store::Error::NotFound.into())); + return; + }; + let (task, shared, sites) = (e.task.clone(), self.config.shared.clone(), self.config.sites.clone()); + self.look(answer, e.host.clone(), async move { + let (_keep, mut stop) = watch::channel(false); + let source = site::source(sites.as_ref(), &task, &stop).await?; + verify::sidecar(&shared.client, &source, &mut stop).await + }); + } + + fn read_metalink(&self, link: NewLink, answer: oneshot::Sender>>) { + let (shared, sites) = (self.config.shared.clone(), self.config.sites.clone()); + self.look(answer, host_of(&link.url), async move { + let (_keep, mut stop) = watch::channel(false); + let mut task = Task::default(); + link.put_in(&mut task); + let source = site::source(sites.as_ref(), &task, &stop).await?; + metalink::read(&shared.client, &source, &mut stop).await + }); + } + fn check_partial(&self, path: PathBuf, link: NewLink, answer: oneshot::Sender>) { let (shared, sites) = (self.config.shared.clone(), self.config.sites.clone()); self.look(answer, host_of(&link.url), async move { @@ -770,7 +817,7 @@ impl Actor { return Ok(()); } self.entry(id).forced = 0; - if state == State::Running { + if matches!(state, State::Running | State::Checking) { self.stop_run(id); } self.set_state(id, State::Paused, None) @@ -808,7 +855,7 @@ impl Actor { t.queue = new.queue; t.position = new.position; t.priority = new.priority; - t.checksum = new.checksum; + t.checksum = new.checksum.map(verify::plain); t.max_parts = new.max_parts; t.tries = new.tries; t.speed_limit = new.speed_limit; @@ -900,7 +947,7 @@ impl Actor { /// Takes a running one's place away. fn suspend(&mut self, id: TaskId) { - if self.entries[&id].task.state == State::Running { + if matches!(self.entries[&id].task.state, State::Running | State::Checking) { self.stop_run(id); self.move_to(id, State::Queued, None); } @@ -973,6 +1020,23 @@ impl Actor { log::error!("task {id} not started: {e}"); return; } + self.launch(id, false); + } + + /// Compares a finished file with its checksum once more. + fn verify(&mut self, id: TaskId, answer: Option) { + let task = &self.entries[&id].task; + let wanted = task.checksum.is_some() || task.pieces.is_some(); + // Without them it would be downloaded. + let known = self.store.parts(id).is_ok_and(|p| !p.is_empty()); + let result = if wanted && known { self.set_state(id, State::Checking, None) } else { Ok(()) }; + if wanted && known && result.is_ok() { + self.launch(id, true); + } + self.answer(answer, result.map(|()| id)); + } + + fn launch(&mut self, id: TaskId, again: bool) { let task = self.entries[&id].task.clone(); if let Err(e) = Source::new(&task.url) { return self.failed(id, &Why::Http(e)); @@ -982,7 +1046,7 @@ impl Actor { flow.put(Group::Queue(task.queue)); flow.set(task.speed_limit); let monitor = Arc::new(Monitor::with_flow(unlimited(self.config.limits.parts_per_download), flow)); - let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded }; + let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded, again }; if std::mem::take(&mut self.entry(id).finish) { monitor.finish(); } @@ -1012,6 +1076,7 @@ impl Actor { e.log(&tr!("log.connect", server = e.host)); e.counters.runs += 1; e.meter = Meter::default(); + e.checked = 0.0; e.work = Some(Work::Run(run)); } @@ -1034,7 +1099,7 @@ impl Actor { fn ended(&mut self, id: TaskId, result: std::result::Result) { self.measure(id, Duration::ZERO); - let had = if let Some(Work::Run(run)) = &self.entries[&id].work { run.had } else { 0 }; + let (had, again) = if let Some(Work::Run(run)) = &self.entries[&id].work { (run.had, run.again) } else { (0, false) }; self.runs.remove(&id); let reloaded = self.reload(id, true); let e = self.entry(id); @@ -1047,9 +1112,13 @@ impl Actor { self.entry(id).fails = 0; } match result { + Ok(_) if again && self.entries[&id].task.state == State::Checking => { + self.move_to(id, State::Done, None); + self.entry(id).took(None); + } Ok(_) => self.finished(id), Err(Why::Http(http::Error::Stopped)) => self.suspend(id), - Err(why) if self.entries[&id].task.state == State::Running => self.failed(id, &why), + Err(why) if matches!(self.entries[&id].task.state, State::Running | State::Checking) => self.failed(id, &why), // It was being stopped anyway. Err(why) => { let text = self.failure(id, &why).text; @@ -1241,7 +1310,7 @@ impl Actor { /// Lets the computer sleep when no download is being stopped any more. fn saved(&mut self) { - if self.runs.iter().all(|id| self.entries[id].task.state == State::Running) { + if self.runs.iter().all(|id| matches!(self.entries[id].task.state, State::Running | State::Checking)) { self.going = None; } } @@ -1362,6 +1431,7 @@ impl Actor { fn measure(&mut self, id: TaskId, dt: Duration) { let Some(Work::Run(run)) = self.entries.get_mut(&id).and_then(|e| e.work.as_mut()) else { return }; let shot = run.monitor.snapshot(); + let again = run.again; let bytes = shot.received.saturating_sub(run.received); run.received = shot.received.max(run.received); let first = !run.known && !shot.parts.is_empty(); @@ -1374,6 +1444,21 @@ impl Actor { self.second += bytes; self.totals.counters.received += bytes; self.totals.counters.active += active; + match (shot.checked, self.entries[&id].task.state) { + (Some(share), state) => { + if state == State::Running { + self.move_to(id, State::Checking, None); + } + let e = self.entries.get_mut(&id).expect("seen above"); + if e.checked != share { + e.checked = share; + self.dirty.insert(id); + } + } + // Wrong pieces come again. + (None, State::Checking) if !again && shot.parts.iter().any(|p| p.state != PartState::Done) => self.move_to(id, State::Running, None), + _ => {} + } let e = self.entries.get_mut(&id).expect("seen above"); e.second += bytes; e.counters.received += bytes; diff --git a/crates/core/src/manager/files.rs b/crates/core/src/manager/files.rs index b86c9d1..d5852de 100644 --- a/crates/core/src/manager/files.rs +++ b/crates/core/src/manager/files.rs @@ -183,6 +183,7 @@ pub fn discard(store: &Store, id: TaskId) -> Result<()> { store.save_parts(id, vec![])?; store.edit_task(id, |t| { (t.size, t.etag, t.last_modified, t.mime, t.finished_at, t.downloaded) = (None, None, None, None, None, 0); + t.verified = None; })?; Ok(()) } diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index 88b8ea4..d2477a6 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -21,7 +21,9 @@ use crate::recover::sleep::Sleep; use crate::relink::{Checked, NewLink}; use crate::settings::Limits; use crate::site::Sites; +use crate::metalink; use crate::snapshot::Snapshot; +use crate::verify::Checksum; use crate::{store, tr}; use arc_swap::ArcSwap; use std::fmt; @@ -114,6 +116,10 @@ pub enum Command { Move { id: TaskId, folder: PathBuf }, /// Renames the file too. A taken name gets a number. Rename { id: TaskId, name: String }, + /// Compares a finished file with its checksum, or its pieces. Nothing without them. + Verify(TaskId), + /// From the start, as a new file, from the next mirror. The link it has becomes the last mirror. + OtherMirror(TaskId), /// Changes what the user decides: link, mirrors, queue, position, priority, limits, headers, notes and the like. /// Changes of other fields are dropped. Edit { id: TaskId, edit: Box }, @@ -133,7 +139,7 @@ impl Command { use Command::*; match self { Add(_) | Adopt { .. } => None, - Start(id) | Pause(id) | Resume(id) | Stop(id) | Finish(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id), + Start(id) | Pause(id) | Resume(id) | Stop(id) | Finish(id) | Restore(id) | Redownload(id) | Verify(id) | OtherMirror(id) | KeepBoth(id) | AwaitLink(id) => Some(*id), Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id), } } @@ -204,6 +210,8 @@ type Answer = oneshot::Sender>; enum Msg { Command(Command, Option), Check(TaskId, NewLink, oneshot::Sender>), + FindChecksum(TaskId, oneshot::Sender>>), + ReadMetalink(NewLink, oneshot::Sender>>), CheckPartial(PathBuf, NewLink, oneshot::Sender>), Limits(Limits), OnChange(Box), @@ -253,6 +261,20 @@ impl Manager { Reply(reply) } + /// Looks for a checksum beside the file on its server; nothing changes. `Command::Edit` takes it. + pub fn find_checksum(&self, id: TaskId) -> Reply> { + let (answer, reply) = oneshot::channel(); + let _ = self.to.send(Msg::FindChecksum(id, answer)); + Reply(reply) + } + + /// The files in a metalink; `metalink::File::task` makes downloads of them. + pub fn read_metalink(&self, link: NewLink) -> Reply> { + let (answer, reply) = oneshot::channel(); + let _ = self.to.send(Msg::ReadMetalink(link, answer)); + Reply(reply) + } + /// The same for an unfinished file of another program. pub fn check_partial(&self, path: PathBuf, link: NewLink) -> Reply { let (answer, reply) = oneshot::channel(); diff --git a/crates/core/src/metalink.rs b/crates/core/src/metalink.rs new file mode 100644 index 0000000..e449255 --- /dev/null +++ b/crates/core/src/metalink.rs @@ -0,0 +1,452 @@ +//! Metalink: lists of sources and checksums, as files (versions 3 and 4) and as headers of a reply (RFC 6249). +//! +//! They come from anywhere: sizes, depth and counts have limits, and a document type or an entity of its own ends the reading. + +use crate::http::{self, Client, Error, Source, Stop, safe_name}; +use crate::model::Task; +use crate::tr; +use crate::verify::{Algo, Checksum, Pieces}; +use quick_xml::XmlVersion; +use quick_xml::events::{BytesStart, Event}; +use quick_xml::reader::Reader; +use reqwest::header::HeaderMap; +use std::fmt; +use std::sync::Arc; +use url::Url; + +/// Of a whole metalink file. +pub const MAX_SIZE: u64 = 16 << 20; +const MAX_DEPTH: usize = 16; +const MAX_FILES: usize = 10_000; +/// Sources kept of one file. +pub const MAX_URLS: usize = 64; +/// Of one text or attribute. +const MAX_TEXT: usize = 8192; + +/// One file of a metalink, with at least one source. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct File { + /// Safe to use as a file name. Empty when there is none. + pub name: String, + pub size: Option, + /// The strongest it has. + pub checksum: Option, + pub pieces: Option>, + /// The best first. + pub urls: Vec, +} + +impl File { + /// A download of it. + pub fn task(&self) -> Task { + let mut task = Task { url: self.urls.first().cloned().unwrap_or_default(), name: self.name.clone(), ..Task::default() }; + self.put_in(&mut task); + task + } + + /// Adds its sources, and the checksums the task doesn't have. + pub(crate) fn put_in(&self, task: &mut Task) { + for url in &self.urls { + if *url != task.url && !task.mirrors.contains(url) && task.mirrors.len() < MAX_URLS { + task.mirrors.push(url.clone()); + } + } + if task.checksum.is_none() { + task.checksum = self.checksum.as_ref().map(Checksum::to_string); + } + if task.pieces.is_none() { + task.pieces = self.pieces.clone(); + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bad { + /// Not a metalink, or a broken one. + Form, + /// Beyond the limits, or with a document type. + Unsafe, + /// Nothing in it can be downloaded. + Empty, +} + +impl fmt::Display for Bad { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&match self { + Bad::Form => tr!("metalink.form"), + Bad::Unsafe => tr!("metalink.unsafe"), + Bad::Empty => tr!("metalink.empty"), + }) + } +} + +impl std::error::Error for Bad {} + +/// Whether a link or a file leads to a metalink. +pub fn is(name: &str, mime: Option<&str>) -> bool { + let name = name.to_ascii_lowercase(); + name.ends_with(".meta4") || name.ends_with(".metalink") || matches!(mime, Some("application/metalink4+xml" | "application/metalink+xml")) +} + +/// Fetches a metalink and reads it. +pub async fn read(client: &Client, source: &Source, stop: &mut Stop) -> http::Result> { + let data = http::small(client, source, MAX_SIZE, stop).await?; + parse(&data).map_err(|e| Error::BadReply(e.to_string())) +} + +#[derive(Default)] +struct Building { + file: File, + /// Order and link; the lowest first. + urls: Vec<(i64, String)>, + checksums: Vec, + /// Kind, length, hashes. + pieces: Option<(Option, u64, Vec)>, + best: Option, + /// None: the pieces can't be used. + piece_index: Option, +} + +impl Building { + fn end(mut self) -> Option { + self.urls.sort_by_key(|(order, _)| *order); + for (_, url) in self.urls { + if !self.file.urls.contains(&url) && self.file.urls.len() < MAX_URLS { + self.file.urls.push(url); + } + } + self.file.checksum = self.checksums.into_iter().max_by_key(|c| c.algo); + let size = self.file.size; + self.file.pieces = self.best.filter(|p| size.is_none_or(|s| p.fit(s))).map(Arc::new); + (!self.file.urls.is_empty()).then_some(self.file) + } + + fn end_pieces(&mut self) { + let Some((Some(algo), size, hashes)) = self.pieces.take() else { return }; + let Some(pieces) = Pieces::new(algo, size, hashes) else { return }; + if self.best.as_ref().is_none_or(|b| b.algo < pieces.algo) { + self.best = Some(pieces); + } + } +} + +pub fn parse(data: &[u8]) -> Result, Bad> { + if data.len() as u64 > MAX_SIZE { + return Err(Bad::Unsafe); + } + let mut reader = Reader::from_reader(data); + reader.config_mut().expand_empty_elements = true; + // Names of the open elements, and what stands in the innermost one. + let mut path: Vec = vec![]; + let mut text = String::new(); + let mut attributes: Vec<(String, String)> = vec![]; + let mut files = vec![]; + let mut file: Option = None; + loop { + match reader.read_event().map_err(|_| Bad::Form)? { + Event::Start(e) => { + let name = std::str::from_utf8(e.local_name().as_ref()).map_err(|_| Bad::Form)?.to_string(); + if path.is_empty() && name != "metalink" { + return Err(Bad::Form); + } + path.push(name); + if path.len() > MAX_DEPTH { + return Err(Bad::Unsafe); + } + text.clear(); + attributes = attributes_of(&e)?; + let get = |k: &str| attributes.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()); + match (path.last().map(String::as_str), &mut file) { + (Some("file"), None) => { + if files.len() >= MAX_FILES { + return Err(Bad::Unsafe); + } + let name = get("name").and_then(safe_name).unwrap_or_default(); + file = Some(Building { file: File { name, ..File::default() }, ..Building::default() }); + } + (Some("pieces"), Some(f)) => { + let len = get("length").and_then(|l| l.parse().ok()).unwrap_or(0); + f.pieces = Some((get("type").and_then(Algo::from_name), len, vec![])); + f.piece_index = Some(0); + } + _ => {} + } + } + Event::End(_) => { + let Some(name) = path.pop() else { return Err(Bad::Form) }; + if let Some(f) = &mut file { + let get = |k: &str| attributes.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()); + let inside = path.last().map(String::as_str); + let value = text.trim(); + match (name.as_str(), inside) { + ("file", _) => files.extend(file.take().and_then(Building::end)), + ("size", Some("file")) => f.file.size = value.parse().ok(), + ("hash", Some("pieces")) => { + let Some((Some(algo), _, hashes)) = &mut f.pieces else { continue }; + let hash = format!("{}:{value}", algo.name()).parse::(); + // Version 3 numbers them. + let place = get("piece").map_or(f.piece_index, |p| p.parse().ok()); + match hash { + Ok(hash) if place.is_some() && place == f.piece_index && hashes.len() < algo.len() * crate::verify::MAX_PIECES => { + hashes.extend(hash.hash); + f.piece_index = place.map(|p| p + 1); + } + // One missing makes all useless. + _ => f.pieces = None, + } + } + ("hash", Some("file" | "verification")) => { + let algo = get("type").and_then(Algo::from_name); + f.checksums.extend(algo.and_then(|a| format!("{}:{value}", a.name()).parse().ok())); + } + ("pieces", _) => f.end_pieces(), + ("url", Some("file" | "resources")) => { + let number = |k| get(k).and_then(|n| n.parse::().ok()); + // Version 3: more is better. Version 4: less is. + let order = number("preference").map(|p| 1_000_000 - p.clamp(0, 1_000_000)).or(number("priority")); + if f.urls.len() < MAX_URLS * 4 && let Some(url) = usable(value) { + f.urls.push((order.unwrap_or(1_000_001), url)); + } + } + _ => {} + } + } + text.clear(); + attributes.clear(); + } + Event::Text(t) => add(&mut text, &t.decode().map_err(|_| Bad::Form)?)?, + Event::CData(t) => add(&mut text, &t.decode().map_err(|_| Bad::Form)?)?, + Event::GeneralRef(r) => { + let known = match (r.resolve_char_ref(), &*r) { + (Ok(Some(c)), _) => c, + (_, b"amp") => '&', + (_, b"lt") => '<', + (_, b"gt") => '>', + (_, b"quot") => '"', + (_, b"apos") => '\'', + _ => return Err(Bad::Unsafe), + }; + add(&mut text, known.encode_utf8(&mut [0; 4]))?; + } + Event::DocType(_) => return Err(Bad::Unsafe), + Event::Eof if path.is_empty() && files.is_empty() => return Err(Bad::Empty), + Event::Eof if path.is_empty() => return Ok(files), + Event::Eof => return Err(Bad::Form), + Event::Empty(_) | Event::Comment(_) | Event::Decl(_) | Event::PI(_) => {} + } + } +} + +fn add(text: &mut String, more: &str) -> Result<(), Bad> { + if text.len() + more.len() > MAX_TEXT { + // Descriptions may be long; nothing read here is. + text.clear(); + return Ok(()); + } + text.push_str(more); + Ok(()) +} + +fn attributes_of(e: &BytesStart) -> Result, Bad> { + let mut out = vec![]; + for a in e.attributes().take(32) { + let a = a.map_err(|_| Bad::Form)?; + // Knows the five entities of XML and no others. + let value = a.normalized_value(XmlVersion::Implicit1_0).map_err(|_| Bad::Unsafe)?; + let name = std::str::from_utf8(a.key.local_name().into_inner()).map_err(|_| Bad::Form)?.to_string(); + if value.len() <= MAX_TEXT { + out.push((name, value.into_owned())); + } + } + Ok(out) +} + +/// A link that can be downloaded and holds no login. +fn usable(url: &str) -> Option { + let url = Source::new(url).ok()?.url; + (url.username().is_empty() && url.password().is_none()).then(|| url.into()) +} + +/// What the headers of a reply say about the file. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Hints { + pub checksum: Option, + /// The best first. Only with a checksum, as RFC 6249 wants it. + pub mirrors: Vec, + /// A metalink file about it. + pub metalink: Option, +} + +/// `Digest` (RFC 3230), `Repr-Digest` (RFC 9530) and `Link` (RFC 6249). `at` is where the reply came from. +pub fn hints(headers: &HeaderMap, at: &Url) -> Hints { + let values = |name: &str| -> Vec<&str> { headers.get_all(name).iter().take(64).filter_map(|v| v.to_str().ok()).collect() }; + let mut hints = Hints::default(); + let digests = ["digest", "repr-digest"].into_iter().flat_map(values).flat_map(|v| v.split(',')); + hints.checksum = digests + .filter_map(|d| { + let (algo, value) = d.trim().split_once('=')?; + Checksum::from_base64(Algo::from_name(algo.trim())?, value.trim_matches(':')) + }) + .max_by_key(|c| c.algo); + let mut mirrors: Vec<(i64, String)> = vec![]; + for value in values("link") { + for (target, parameters) in links(value) { + let get = |k: &str| parameters.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.as_str()); + let Some(url) = at.join(target).ok().and_then(|u| usable(u.as_str())) else { continue }; + let is = |rel: &str| get("rel").is_some_and(|r| r.split_ascii_whitespace().any(|r| r.eq_ignore_ascii_case(rel))); + if is("duplicate") && mirrors.len() < MAX_URLS && url != at.as_str() && mirrors.iter().all(|(_, m)| *m != url) { + mirrors.push((get("pri").and_then(|p| p.parse().ok()).unwrap_or(1_000_000), url)); + } else if is("describedby") && get("type") == Some("application/metalink4+xml") { + hints.metalink = hints.metalink.or(Url::parse(&url).ok()); + } + } + } + if hints.checksum.is_some() { + mirrors.sort_by_key(|(order, _)| *order); + hints.mirrors = mirrors.into_iter().map(|(_, url)| url).collect(); + } + hints +} + +/// `; name=value; name="value", …` +fn links(value: &str) -> Vec<(&str, Vec<(&str, String)>)> { + let mut out = vec![]; + let mut rest = value; + while let Some((_, after)) = rest.split_once('<') { + let Some((target, mut tail)) = after.split_once('>') else { break }; + let mut parameters = vec![]; + loop { + tail = tail.trim_start(); + let Some(next) = tail.strip_prefix(';') else { break }; + let end = next.find(['=', ';', ',']).unwrap_or(next.len()); + let name = next[..end].trim(); + tail = &next[end..]; + let Some(value) = tail.strip_prefix('=') else { + parameters.push((name, String::new())); + continue; + }; + let value = value.trim_start(); + if let Some(quoted) = value.strip_prefix('"') { + let Some((inner, after)) = quoted.split_once('"') else { return out }; + parameters.push((name, inner.to_string())); + tail = after; + } else { + let end = value.find([';', ',']).unwrap_or(value.len()); + parameters.push((name, value[..end].trim().to_string())); + tail = &value[end..]; + } + } + out.push((target.trim(), parameters)); + rest = tail; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use reqwest::header::{HeaderName, HeaderValue}; + + const SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + const MD5: &str = "d41d8cd98f00b204e9800998ecf8427e"; + + fn v4(inner: &str) -> String { + format!("\n{inner}") + } + + #[test] + fn version_4() { + let text = v4(&format!( + "x & y + 500{MD5} {SHA}\n + 00 + {MD5}{MD5} + https://two/f?a=1&b=2 + ftp://three/fmagnet:?xt=1http://user:pw@four/fhttp://one/f + http://t/f.torrent + sftp://h/b" + )); + let files = parse(text.as_bytes()).unwrap(); + assert_eq!(files.len(), 2); + let f = &files[0]; + assert!(!f.name.contains('/') && !f.name.starts_with('.'), "{}", f.name); + assert_eq!(f.urls, ["http://one/f", "https://two/f?a=1&b=2", "ftp://three/f"]); + assert_eq!((f.size, f.checksum.as_ref().unwrap().to_string()), (Some(500), format!("sha256:{SHA}"))); + assert_eq!(f.pieces.as_ref().unwrap().count(), 2); + let task = f.task(); + assert_eq!((task.url.as_str(), task.mirrors.len(), task.pieces.is_some()), ("http://one/f", 2, true)); + assert_eq!((files[1].name.as_str(), files[1].checksum.as_ref()), ("b", None)); + } + + #[test] + fn version_3() { + let text = format!( + "9 + {MD5}da39a3ee5e6b4b0d3255bfef95601890afd80709 + {MD5}{MD5}{MD5} + + http://b/http://t/ + http://a/" + ); + let f = parse(text.as_bytes()).unwrap().remove(0); + assert_eq!(f.urls[..2], ["http://a/", "http://b/"]); + assert_eq!(f.checksum.unwrap().algo, Algo::Sha1); + assert_eq!(f.pieces.unwrap().count(), 3); + let gap = parse(text.replace("piece=\"1\"", "piece=\"5\"").as_bytes()).unwrap().remove(0); + assert_eq!(gap.pieces, None); + let short = parse(text.replace("9", "900").as_bytes()).unwrap().remove(0); + assert_eq!(short.pieces, None, "they don't fit the size"); + } + + #[test] + fn hostile_files() { + let url = "http://a/"; + let file = format!("{url}"); + for (text, why) in [ + (format!("]>{}", v4(&file)), Bad::Unsafe), + (format!("{file}"), Bad::Unsafe), + (v4("http://a/&lol;"), Bad::Unsafe), + (v4("http://a/"), Bad::Unsafe), + (v4(&("".repeat(100) + &"".repeat(100))), Bad::Unsafe), + (v4(&"http://a/".repeat(MAX_FILES + 1)), Bad::Unsafe), + (" ".repeat(MAX_SIZE as usize + 1), Bad::Unsafe), + (format!("{file}"), Bad::Form), + (format!("{file}"), Bad::Form), + (format!("{file}".into(), Bad::Form), + (v4("javascript:1file:///etc/passwd"), Bad::Empty), + (String::new(), Bad::Empty), + ] { + assert_eq!(parse(text.as_bytes()), Err(why), "{}", &text[..text.len().min(200)]); + } + assert_eq!(parse(b"\xff\xfe<\0m\0"), Err(Bad::Form)); + let many = v4(&format!("{}", (0..5000).map(|i| format!("http://h{i}/")).collect::())); + assert_eq!(parse(many.as_bytes()).unwrap()[0].urls.len(), MAX_URLS); + let long = v4(&format!("{url}{}", "x".repeat(100_000))); + assert_eq!(parse(long.as_bytes()).unwrap().len(), 1); + } + + #[test] + fn headers() { + let at = Url::parse("https://h/d/f.iso").unwrap(); + let of = |all: &[(&str, &str)]| { + let all = all.iter().map(|(k, v)| (HeaderName::try_from(*k).unwrap(), HeaderValue::try_from(*v).unwrap())); + hints(&HeaderMap::from_iter(all), &at) + }; + let sha = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="; + let digest = format!("MD5=1B2M2Y8AsgTpgAmY7PhCfg==,SHA-256={sha}"); + let link = "; rel=duplicate; pri=2; geo=\"a,b;c\", ; rel=\"duplicate other\"; pri=1, \ + ; rel=describedby; type=\"application/metalink4+xml\", ; rel=duplicate, ; rel=duplicate"; + let h = of(&[("digest", &digest), ("link", link)]); + assert_eq!(h.checksum.unwrap().to_string(), format!("sha256:{SHA}")); + assert_eq!(h.mirrors, ["https://h/m1", "http://m/2,x"]); + assert_eq!(h.metalink.unwrap().as_str(), "https://h/d/f.meta4"); + assert_eq!(of(&[("link", link)]).mirrors, [""; 0], "nothing to check them with"); + let repr = of(&[("repr-digest", &format!("sha-256=:{sha}:"))]); + assert_eq!(repr.checksum.unwrap().algo, Algo::Sha256); + for bad in ["<", ";", "; rel=\"dup", ",,,", ";;;=;", "é"] { + let _ = links(bad); + } + assert_eq!(of(&[("digest", "SHA-256=x"), ("digest", "nonsense")]).checksum, None); + } +} diff --git a/crates/core/src/mirror.rs b/crates/core/src/mirror.rs new file mode 100644 index 0000000..b2522cd --- /dev/null +++ b/crates/core/src/mirror.rs @@ -0,0 +1,133 @@ +//! Other links to the same file, used beside the first one. +//! +//! Nothing comes from a mirror before it was compared with what is here, and with the base at places that aren't here yet. + +use crate::http::{Client, Link, Result, Source, Stop, bytes_at, same_bytes}; +use crate::model::{Part, Task}; +use crate::relink::{self, NewLink, Reason, Verdict}; +use std::hash::{BuildHasher, RandomState}; +use std::ops::Range; + +/// So many finished bytes are needed for a comparison. +pub const NEEDED: u64 = 16 * 1024; +/// Compared in one place that isn't here yet. +const SPOT: u64 = 4096; + +/// The mirror, ready for use. None if it isn't the same file, or can't be told. +pub(crate) async fn check(client: Client, task: Task, parts: Vec, base: Link, source: Source, mut stop: Stop) -> Result> { + let link = NewLink { url: source.url.to_string(), ..NewLink::default() }; + let (checked, opened) = relink::open_link(&client, &task, &parts, link, source, &mut stop).await?; + let Some(mirror) = usable(&checked).then_some(opened).flatten() else { + log::debug!("mirror refused: {:?}", checked.reason); + return Ok(None); + }; + if mirror.version.size != base.version.size { + return Ok(None); + } + if checked.reason == Reason::Samples { + for spot in spots(&parts, base.version.size.unwrap_or(0)) { + let known = bytes_at(&base, spot.start, spot.end - spot.start, &mut stop).await?; + if !same_bytes(&mirror, &known, spot.start, &mut stop).await? { + log::debug!("mirror refused: other bytes at {}", spot.start); + return Ok(None); + } + } + } + Ok(Some(mirror)) +} + +/// The comparison says it can be continued from. +pub(crate) fn usable(checked: &relink::Checked) -> bool { + checked.ranges && matches!(checked.verdict(), Verdict::Same | Verdict::ProbablySame) +} + +/// The end of the file and a place by chance, unless they are here. +fn spots(parts: &[Part], size: u64) -> Vec> { + let chance = RandomState::new().hash_one(size) % size.max(1); + let here = relink::runs(parts); + [size.saturating_sub(SPOT)..size, chance..size.min(chance + SPOT)] + .into_iter() + .filter(|s| !s.is_empty() && !here.iter().any(|r| r.start <= s.start && s.end <= r.end)) + .collect() +} + +/// The parts without `bad`, whose bytes have to come again. +pub(crate) fn without(parts: &[Part], bad: &[Range]) -> Vec { + let mut out = vec![]; + for p in parts { + let end = p.end.unwrap_or(p.start + p.done); + let mut at = p.start; + let mut cuts: Vec<_> = bad.iter().filter(|b| b.start < p.start + p.done && b.end > p.start).collect(); + cuts.sort_by_key(|b| b.start); + for b in cuts { + let (from, to) = (b.start.max(at), b.end.min(p.start + p.done)); + if from >= to { + continue; + } + if from > at { + out.push(Part { start: at, end: Some(from), done: from - at }); + } + // The rest of an unfinished part goes with it. + let last = to == p.start + p.done; + out.push(Part { start: from, end: Some(if last { end } else { to }), done: 0 }); + at = if last { end } else { to }; + } + if at < end || (p.start == end && at == end) { + out.push(Part { start: at, end: p.end, done: (p.start + p.done).saturating_sub(at) }); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn part(start: u64, end: u64, done: u64) -> Part { + Part { start, end: Some(end), done } + } + + #[test] + #[allow(clippy::single_range_in_vec_init)] + fn bad_ranges_come_again() { + let parts = [part(0, 100, 100), part(100, 200, 50), part(200, 300, 0)]; + assert_eq!(without(&parts, &[]), parts); + assert_eq!(without(&parts, &[0..100]), [part(0, 100, 0), parts[1], parts[2]]); + assert_eq!(without(&parts, &[10..20, 90..120]), [ + part(0, 10, 10), part(10, 20, 0), part(20, 90, 70), part(90, 100, 0), part(100, 120, 0), part(120, 200, 30), parts[2] + ]); + assert_eq!(without(&parts, &[140..260]), [parts[0], part(100, 140, 40), part(140, 200, 0), parts[2]]); + assert_eq!(without(&parts, &[150..200]), parts, "nothing of it is here"); + assert_eq!(without(&[part(0, 0, 0)], &[0..10]), [part(0, 0, 0)]); + } + + /// Every byte stays in exactly one part, and none of the bad ones counts as done. + #[test] + fn no_gap_after_a_cut() { + for _ in 0..500 { + let (mut parts, mut at) = (vec![], 0); + for _ in 0..fastrand::u64(1..6) { + let len = fastrand::u64(1..50); + parts.push(part(at, at + len, fastrand::u64(0..=len))); + at += len; + } + let bad: Vec<_> = (0..fastrand::u64(0..4)).map(|_| fastrand::u64(0..at)).map(|s| s..s + fastrand::u64(1..40)).collect(); + let new = without(&parts, &bad); + assert_eq!((new[0].start, new.last().unwrap().end), (0, Some(at)), "{parts:?} {bad:?}"); + assert!(new.windows(2).all(|w| w[0].end == Some(w[1].start)), "{parts:?} {bad:?} {new:?}"); + let done = |parts: &[Part], i: u64| parts.iter().any(|p| p.start <= i && i < p.start + p.done); + for i in 0..at { + assert_eq!(done(&new, i), done(&parts, i) && !bad.iter().any(|b| b.contains(&i)), "{i}: {parts:?} {bad:?} {new:?}"); + } + } + } + + #[test] + fn spots_are_not_here_yet() { + for _ in 0..100 { + let s = spots(&[part(0, 100_000, 50_000)], 100_000); + assert!(s.contains(&(95_904..100_000)) && s.iter().all(|s| s.end <= 100_000 && s.end > 50_000)); + } + assert_eq!(spots(&[part(0, 9, 9)], 9), []); + } +} diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 15c0a3e..c125580 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -2,8 +2,10 @@ //! //! Secrets (cookies, logins, tokens) never appear here. `secret` fields hold the name of a keyring item. +use crate::verify::Pieces; use serde::{Deserialize, Serialize}; use std::path::PathBuf; +use std::sync::Arc; pub type TaskId = i64; pub type QueueId = i64; @@ -65,7 +67,8 @@ impl State { // Queued again: the app was killed, or the task gave up its place. Running => &[Queued, Waiting, Paused, Checking, Finishing, Failed], Paused => &[Queued, Waiting, Failed], - Checking => &[Queued, Paused, Finishing, Failed], + // Running: some pieces come again. Done: it was done before. + Checking => &[Queued, Running, Paused, Finishing, Done, Failed], Finishing => &[Queued, Done, Failed], // Queued: download again. Checking: check the file again. Done => &[Queued, Checking, Gone], @@ -136,6 +139,8 @@ named_enum!( /// Sound and picture that can't be made a file of. Media = "media", Crashed = "crashed", + /// The file doesn't match its checksum. + Checksum = "checksum", } ); @@ -172,6 +177,10 @@ pub struct Task { pub last_modified: Option, /// `sha256:…`. pub checksum: Option, + /// Hashes of its pieces, to repair single ones. + pub pieces: Option>, + /// What the finished file was found to match: `checksum` as it was then, or `pieces`. + pub verified: Option, pub max_parts: Option, /// Failures in a row before it fails, 0 for never. None for the setting. pub tries: Option, @@ -214,6 +223,8 @@ impl Default for Task { etag: None, last_modified: None, checksum: None, + pieces: None, + verified: None, max_parts: None, tries: None, speed_limit: None, diff --git a/crates/core/src/relink/mod.rs b/crates/core/src/relink/mod.rs index 2d178fc..9474d28 100644 --- a/crates/core/src/relink/mod.rs +++ b/crates/core/src/relink/mod.rs @@ -149,45 +149,68 @@ impl Checked { /// Compares the task's finished bytes with the new link's. Reads the file only; the task may even be running. pub async fn check(client: &Client, task: &Task, parts: &[Part], link: NewLink, source: Source, stop: &mut Stop) -> Result { + Ok(open_link(client, task, parts, link, source, stop).await?.0) +} + +/// The same, and the server to go on from. None when the verdict was clear without it. +pub(crate) async fn open_link( + client: &Client, + task: &Task, + parts: &[Part], + link: NewLink, + source: Source, + stop: &mut Stop, +) -> Result<(Checked, Option)> { let path = disk::partial_path(&task.folder, &task.name); let whole = runs(parts); let file = if whole.is_empty() { None } else { Some(open(&path).await?) }; let (mut checked, opened) = probed(client, task, link, source, total(&whole), stop).await?; - let Some((server, body)) = opened else { return Ok(checked) }; - let Some(file) = file else { - checked.reason = Reason::Nothing; - return Ok(checked); - }; + let Some((server, body)) = opened else { return Ok((checked, None)) }; + if let Some(file) = file { + judge(&mut checked, &server, body, task, &file, &whole, stop).await?; + } + Ok((checked, Some(server))) +} + +async fn judge( + checked: &mut Checked, + server: &Link, + body: Option, + task: &Task, + file: &Arc, + whole: &[Range], + stop: &mut Stop, +) -> Result<()> { let old = Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() }; // Both at the same server, as far as is known. let same_server = url::Url::parse(&task.url).is_ok_and(|u| u.origin() == server.source.url.origin()); let opinion = versions(&old, &server.version, same_server); if opinion == Opinion::Other { checked.reason = Reason::OtherVersion; - return Ok(checked); + return Ok(()); } // More is here than it has. if let (Some(size), Some(last)) = (server.version.size, whole.last()) && last.end > size { checked.reason = Reason::Size { old: last.end, new: size }; - return Ok(checked); + return Ok(()); } if !server.ranges { let head = whole.first().filter(|r| r.start == 0).map(|r| r.end.min(ALL)).unwrap_or(0); - let known = read(&file, 0..head).await?; + let known = read(file, 0..head).await?; let same = match body { - Some(body) => same_body(client, body, &known, stop).await?, + Some(body) => same_body(&server.client, body, &known, stop).await?, None => true, }; checked.compared = head; checked.reason = if same { Reason::NoRanges } else { Reason::Bytes }; - return Ok(checked); + return Ok(()); } drop(body); - for sample in samples(&whole) { - let known = read(&file, sample.clone()).await?; - checked.reason = match same_bytes(&server, &known, sample.start, stop).await { + for sample in samples(whole) { + let known = read(file, sample.clone()).await?; + checked.reason = match same_bytes(server, &known, sample.start, stop).await { Ok(true) => { checked.compared += known.len() as u64; continue; @@ -201,14 +224,14 @@ pub async fn check(client: &Client, task: &Task, parts: &[Part], link: NewLink, } Err(e) => return Err(e), }; - return Ok(checked); + return Ok(()); } checked.reason = match opinion { Opinion::Same => Reason::Version, _ if checked.compared < SAMPLE => Reason::TooLittle, _ => Reason::Samples, }; - Ok(checked) + Ok(()) } /// What the link leads to. Nothing to compare comes along when the verdict is clear already. diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs index cd109e3..2320848 100644 --- a/crates/core/src/snapshot.rs +++ b/crates/core/src/snapshot.rs @@ -1,8 +1,9 @@ //! The download list as everyone but the manager sees it. Never changes; a newer one shares all that stayed the same. use crate::http::PartView; -use crate::model::{State, Task, TaskId, Time}; +use crate::model::{ErrorKind, State, Task, TaskId, Time}; use crate::speed::History; +use crate::verify::{self, Offer}; use std::collections::VecDeque; use std::sync::Arc; use std::time::Duration; @@ -48,6 +49,27 @@ impl TaskView { self.task.state } + /// How the file stands to its checksum. + pub fn verify(&self) -> verify::State { + let t = &self.task; + match t.state { + State::Checking => verify::State::Checking, + _ if t.error.as_ref().is_some_and(|e| e.kind == Some(ErrorKind::Checksum)) => verify::State::Bad, + _ if t.verified.is_some() && (t.checksum.is_none() || t.verified == t.checksum) => verify::State::Good, + _ if t.checksum.is_some() || t.pieces.is_some() => verify::State::Open, + _ => verify::State::Nothing, + } + } + + /// What can be done about a file that doesn't match, the cheapest first. + pub fn offers(&self) -> Vec { + if self.verify() != verify::State::Bad { + return vec![]; + } + let all = [(Offer::Repair, self.task.pieces.is_some()), (Offer::OtherMirror, !self.task.mirrors.is_empty()), (Offer::Restart, true)]; + all.into_iter().filter_map(|(o, can)| can.then_some(o)).collect() + } + /// Share of the file that is here, 0 to 1. None when the size is unknown. pub fn progress(&self) -> Option { match (self.task.state, self.size?) { diff --git a/crates/core/src/store/004.sql b/crates/core/src/store/004.sql new file mode 100644 index 0000000..e960a35 --- /dev/null +++ b/crates/core/src/store/004.sql @@ -0,0 +1,2 @@ +ALTER TABLE tasks ADD COLUMN pieces TEXT; +ALTER TABLE tasks ADD COLUMN verified TEXT; diff --git a/crates/core/src/store/mod.rs b/crates/core/src/store/mod.rs index 4d6b8e2..6fec2e8 100644 --- a/crates/core/src/store/mod.rs +++ b/crates/core/src/store/mod.rs @@ -16,7 +16,7 @@ use std::thread::JoinHandle; use std::time::Duration; /// Never edit one that shipped; add the next number. -const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql")]; +const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql")]; #[derive(Debug)] pub enum Error { diff --git a/crates/core/src/store/rows.rs b/crates/core/src/store/rows.rs index 6fa69c1..8bf8a09 100644 --- a/crates/core/src/store/rows.rs +++ b/crates/core/src/store/rows.rs @@ -7,6 +7,7 @@ use std::collections::HashSet; use std::ffi::OsString; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::path::{Path, PathBuf}; +use std::sync::Arc; /// File names needn't be UTF-8. fn path_bytes(path: &Path) -> &[u8] { @@ -29,6 +30,7 @@ fn from_json(text: String) -> Result { fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result { let folder = path_bytes(&t.folder); let (mirrors, headers) = (json(&t.mirrors), json(&t.headers)); + let pieces = t.pieces.as_ref().map(|p| p.to_string()); let columns: &[(&str, &dyn ToSql)] = named_params! { ":url": t.url, ":mirrors": mirrors, ":source_page": t.source_page, ":name": t.name, ":folder": folder, ":queue": t.queue, ":position": t.position, ":priority": t.priority.name(), ":size": t.size, @@ -36,7 +38,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result { ":checksum": t.checksum, ":max_parts": t.max_parts, ":speed_limit": t.speed_limit, ":headers": headers, ":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at, ":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes, ":tries": t.tries, - ":replaces": t.replaces, + ":replaces": t.replaces, ":pieces": pieces, ":verified": t.verified, }; Ok(c.execute(sql, columns)?) } @@ -46,10 +48,10 @@ pub fn insert_task(c: &Connection, t: &Task) -> Result { c, "INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime, etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at, - finished_at, removed_at, notes, tries, replaces) + finished_at, removed_at, notes, tries, replaces, pieces, verified) VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime, :etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at, - :finished_at, :removed_at, :notes, :tries, :replaces)", + :finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified)", t, )?; let id = c.last_insert_rowid(); @@ -68,7 +70,7 @@ pub fn update_task(c: &Connection, t: &Task) -> Result { etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts, speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after, start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes, - tries = :tries, replaces = :replaces + tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified WHERE id = {}", t.id ); @@ -120,6 +122,9 @@ fn task(r: &Row) -> Result { etag: r.get("etag")?, last_modified: r.get("last_modified")?, checksum: r.get("checksum")?, + // One that can't be read is one that can't repair anything. + pieces: r.get::<_, Option>("pieces")?.and_then(|p| p.parse().ok()).map(Arc::new), + verified: r.get("verified")?, max_parts: r.get("max_parts")?, tries: r.get("tries")?, speed_limit: r.get("speed_limit")?, diff --git a/crates/core/src/verify.rs b/crates/core/src/verify.rs new file mode 100644 index 0000000..ffd95fa --- /dev/null +++ b/crates/core/src/verify.rs @@ -0,0 +1,553 @@ +//! Checksums: what is known of them, and comparing files with them. + +use crate::disk::blocking; +use crate::http::{self, Client, Error, Source, Stop}; +use crate::tr; +use base64::Engine; +use base64::prelude::BASE64_STANDARD; +use blake3::Hasher as Blake3; +use md5::Md5; +use sha1::Sha1; +use sha2::{Digest, Sha256, Sha512}; +use std::fmt; +use std::fs::File; +use std::io; +use std::ops::Range; +use std::os::unix::fs::FileExt; +use std::path::PathBuf; +use std::str::FromStr; +use std::sync::Arc; + +/// More pieces than this are not kept. +pub const MAX_PIECES: usize = 1 << 16; +/// Read at once. +const CHUNK: usize = 1 << 20; +/// A list of checksums is never larger. +const MAX_LIST: u64 = 1 << 20; + +/// Weakest first. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Algo { + Md5, + Sha1, + Sha256, + Blake3, + Sha512, +} + +impl Algo { + pub const ALL: [Algo; 5] = [Algo::Md5, Algo::Sha1, Algo::Sha256, Algo::Blake3, Algo::Sha512]; + + pub fn name(self) -> &'static str { + match self { + Algo::Md5 => "md5", + Algo::Sha1 => "sha1", + Algo::Sha256 => "sha256", + Algo::Blake3 => "blake3", + Algo::Sha512 => "sha512", + } + } + + /// As it is shown. + pub fn label(self) -> &'static str { + match self { + Algo::Md5 => "MD5", + Algo::Sha1 => "SHA-1", + Algo::Sha256 => "SHA-256", + Algo::Blake3 => "BLAKE3", + Algo::Sha512 => "SHA-512", + } + } + + /// `sha-256`, `SHA256`, `b3` … + pub fn from_name(name: &str) -> Option { + let plain: String = name.chars().filter(|c| !matches!(c, '-' | '_')).collect::().to_ascii_lowercase(); + match plain.as_str() { + "sha" => Some(Algo::Sha1), + "b3" | "b3sum" => Some(Algo::Blake3), + _ => Algo::ALL.into_iter().find(|a| a.name() == plain), + } + } + + /// Bytes of a hash. + #[allow(clippy::len_without_is_empty)] + pub fn len(self) -> usize { + match self { + Algo::Md5 => 16, + Algo::Sha1 => 20, + Algo::Sha256 | Algo::Blake3 => 32, + Algo::Sha512 => 64, + } + } + + /// SHA-256, where it could be BLAKE3 too. + fn of_len(len: usize) -> Option { + Algo::ALL.into_iter().find(|a| a.len() == len) + } + + /// The usual ending of a file that holds one. + fn ending(self) -> &'static str { + if self == Algo::Blake3 { "b3" } else { self.name() } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Checksum { + pub algo: Algo, + pub hash: Vec, +} + +impl Checksum { + pub fn new(algo: Algo, hash: Vec) -> Option { + (hash.len() == algo.len()).then_some(Checksum { algo, hash }) + } + + fn from_hex(algo: Option, text: &str) -> Option { + let hash = unhex(text)?; + Checksum::new(algo.or(Algo::of_len(hash.len()))?, hash) + } + + pub(crate) fn from_base64(algo: Algo, text: &str) -> Option { + Checksum::new(algo, BASE64_STANDARD.decode(text.trim()).ok()?) + } +} + +/// `sha256:…` +impl fmt::Display for Checksum { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}:{}", self.algo.name(), hex(&self.hash)) + } +} + +/// What someone pastes: the hash alone (its length tells the kind), with the kind before it (`sha256:…`, `SHA-256 = …`, +/// `sha256-` and base64), or a line of a list. Of several lines the first that has one. +impl FromStr for Checksum { + type Err = (); + + fn from_str(text: &str) -> Result { + text.lines().find_map(|l| line(l, None)).map(|l| l.0).ok_or(()) + } +} + +/// The checksum of `name` in a list. One that names no file counts if it is the only one. +pub fn find(list: &str, name: &str, kind: Option) -> Option { + let lines: Vec<_> = list.lines().take(10_000).filter_map(|l| line(l, kind)).collect(); + let of = |n: &str| n.rsplit(['/', '\\']).next() == Some(name); + // The strongest, if there are several. + let named = lines.iter().filter(|(_, n)| n.as_deref().is_some_and(of)).map(|(c, _)| c).max_by_key(|c| c.algo); + match lines.as_slice() { + [(only, None)] => Some(only.clone()), + _ => named.cloned(), + } +} + +/// A hash, and the file it is said to be of. +fn line(line: &str, kind: Option) -> Option<(Checksum, Option)> { + let line = line.trim().trim_start_matches('\u{feff}'); + if line.is_empty() || line.len() > 8192 || line.starts_with(['#', ';']) { + return None; + } + // `SHA256 (file) = hash` + if let Some((left, hash)) = line.rsplit_once(" = ") + && let Some((algo, name)) = left.split_once(" (") + && let Some(name) = name.strip_suffix(')') + { + return Some((Checksum::from_hex(Some(Algo::from_name(algo)?), hash.trim())?, Some(name.into()))); + } + // `hash file` and `hash *file` + let (first, rest) = line.split_once(char::is_whitespace).unwrap_or((line, "")); + if let Some(c) = Checksum::from_hex(kind, first) { + let name = rest.trim_start().trim_start_matches('*'); + return Some((c, Some(name.to_string()).filter(|n| !n.is_empty()))); + } + // `kind: hash`, `kind = hash`, `kind hash`, `kind-base64` + let at = line.find([':', '=', ' ', '\t'])?; + let (algo, hash) = (Algo::from_name(line[..at].trim()), line[at..].trim_matches(|c: char| c.is_whitespace() || matches!(c, ':' | '='))); + if let Some(algo) = algo { + return Some((Checksum::from_hex(Some(algo), hash)?, None)); + } + let (algo, hash) = line.split_once('-')?; + Some((Checksum::from_base64(Algo::from_name(algo)?, hash)?, None)) +} + +/// As it is stored: `sha256:…`. What can't be understood stays as it is, and is never compared. +pub(crate) fn plain(text: String) -> String { + text.parse::().map_or(text, |c| c.to_string()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(text: &str) -> Option> { + let digits = text.as_bytes(); + if digits.is_empty() || digits.len() % 2 == 1 || !digits.iter().all(u8::is_ascii_hexdigit) { + return None; + } + digits.chunks(2).map(|d| u8::from_str_radix(std::str::from_utf8(d).ok()?, 16).ok()).collect() +} + +/// Hashes of the pieces of a file, each `size` long but the last. +#[derive(Clone, PartialEq, Eq)] +pub struct Pieces { + pub algo: Algo, + pub size: u64, + hashes: Vec, +} + +impl Pieces { + pub fn new(algo: Algo, size: u64, hashes: Vec) -> Option { + let fine = size > 0 && !hashes.is_empty() && hashes.len().is_multiple_of(algo.len()) && hashes.len() / algo.len() <= MAX_PIECES; + fine.then_some(Pieces { algo, size, hashes }) + } + + pub fn count(&self) -> u64 { + (self.hashes.len() / self.algo.len()) as u64 + } + + /// Whether a file of `len` bytes has so many. + pub fn fit(&self, len: u64) -> bool { + len.div_ceil(self.size) == self.count() + } + + fn hash(&self, i: u64) -> &[u8] { + let n = self.algo.len(); + &self.hashes[i as usize * n..][..n] + } +} + +impl fmt::Debug for Pieces { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Pieces({} {} of {})", self.count(), self.algo.name(), self.size) + } +} + +/// `sha256:262144:` and all hashes in base64. +impl fmt::Display for Pieces { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}:{}:{}", self.algo.name(), self.size, BASE64_STANDARD.encode(&self.hashes)) + } +} + +impl FromStr for Pieces { + type Err = (); + + fn from_str(text: &str) -> Result { + let mut parts = text.splitn(3, ':'); + let mut next = || parts.next().ok_or(()); + let (algo, size, hashes) = (next()?, next()?, next()?); + let hashes = BASE64_STANDARD.decode(hashes).map_err(drop)?; + Pieces::new(Algo::from_name(algo).ok_or(())?, size.parse().map_err(drop)?, hashes).ok_or(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Found { + /// The same; by what, as `Task::verified` has it. + Good(String), + /// Nothing to compare with. + Nothing, + /// With the ranges that are wrong, as far as that is known. + Bad(Vec>), +} + +/// What a file should be. +#[derive(Debug, Clone, Default)] +pub struct Wanted { + pub checksum: Option, + pub pieces: Option>, +} + +impl Wanted { + pub fn nothing(&self) -> bool { + self.checksum.is_none() && self.pieces.is_none() + } + + /// Reads the whole file, off the threads that download. `progress` gets the share that is done. + pub async fn compare(&self, path: PathBuf, progress: impl Fn(f32) + Send + 'static, stop: &Stop) -> http::Result { + if self.nothing() { + return Ok(Found::Nothing); + } + let (wanted, stop) = (self.clone(), stop.clone()); + let found = blocking(move || wanted.read(&path, progress, || *stop.borrow()).map_err(|e| (e, path))); + match found.await { + Ok(Some(found)) => Ok(found), + Ok(None) => Err(Error::Stopped), + Err((e, _)) if e.kind() == io::ErrorKind::NotFound => Err(Error::Missing), + Err((e, _)) => Err(crate::disk::Error::Io(e).into()), + } + } + + /// None when it was stopped. + fn read(&self, path: &PathBuf, progress: impl Fn(f32), stopped: impl Fn() -> bool) -> io::Result> { + let file = File::open(path)?; + let len = file.metadata()?.len(); + let pieces = self.pieces.as_ref().filter(|p| p.fit(len)); + if self.checksum.is_none() && pieces.is_none() { + return Ok(Some(if self.pieces.is_some() { Found::Bad(vec![]) } else { Found::Nothing })); + } + let mut whole = self.checksum.as_ref().map(|c| Hash::new(c.algo)); + let mut piece = pieces.map(|p| Hash::new(p.algo)); + let mut bad: Vec> = vec![]; + let mut buf = vec![0; CHUNK]; + let mut at = 0; + while at < len { + if stopped() { + return Ok(None); + } + // A piece ends where a read ends. + let piece_end = pieces.map_or(len, |p| ((at / p.size + 1).saturating_mul(p.size)).min(len)); + let n = (piece_end - at).min(CHUNK as u64) as usize; + file.read_exact_at(&mut buf[..n], at)?; + let end = at + n as u64; + if let Some(whole) = &mut whole { + whole.update(&buf[..n]); + } + if let (Some(p), Some(hash)) = (pieces, &mut piece) { + hash.update(&buf[..n]); + if end == piece_end { + let i = at / p.size; + if std::mem::replace(hash, Hash::new(p.algo)).end() != p.hash(i) { + let start = i * p.size; + match bad.last_mut() { + Some(last) if last.end == start => last.end = end, + _ => bad.push(start..end), + } + } + } + } + at = end; + progress(at as f32 / len as f32); + } + Ok(Some(match (&self.checksum, whole.map(Hash::end)) { + // The whole file's word counts more than that of its pieces. + (Some(c), Some(hash)) if hash == c.hash => Found::Good(c.to_string()), + (None, _) if bad.is_empty() => Found::Good("pieces".into()), + _ => Found::Bad(bad), + })) + } +} + +enum Hash { + Md5(Md5), + Sha1(Sha1), + Sha256(Sha256), + Sha512(Sha512), + Blake3(Box), +} + +impl Hash { + fn new(algo: Algo) -> Hash { + match algo { + Algo::Md5 => Hash::Md5(Md5::new()), + Algo::Sha1 => Hash::Sha1(Sha1::new()), + Algo::Sha256 => Hash::Sha256(Sha256::new()), + Algo::Sha512 => Hash::Sha512(Sha512::new()), + Algo::Blake3 => Hash::Blake3(Box::new(Blake3::new())), + } + } + + fn update(&mut self, data: &[u8]) { + match self { + Hash::Md5(h) => h.update(data), + Hash::Sha1(h) => h.update(data), + Hash::Sha256(h) => h.update(data), + Hash::Sha512(h) => h.update(data), + Hash::Blake3(h) => drop(h.update(data)), + } + } + + fn end(self) -> Vec { + match self { + Hash::Md5(h) => h.finalize().to_vec(), + Hash::Sha1(h) => h.finalize().to_vec(), + Hash::Sha256(h) => h.finalize().to_vec(), + Hash::Sha512(h) => h.finalize().to_vec(), + Hash::Blake3(h) => h.finalize().as_bytes().to_vec(), + } + } +} + +/// Looks for a checksum beside the file on its server: `name.sha256` and the like, then `SHA256SUMS` in its folder. +pub async fn sidecar(client: &Client, source: &Source, stop: &mut Stop) -> http::Result> { + let Some(name) = source.url.path_segments().and_then(|mut s| s.next_back()).filter(|n| !n.is_empty()) else { return Ok(None) }; + let plain = percent_encoding::percent_decode_str(name).decode_utf8_lossy().into_owned(); + let order = [Algo::Sha256, Algo::Sha512, Algo::Blake3, Algo::Sha1, Algo::Md5]; + let beside = order.map(|a| (format!("{name}.{}", a.ending()), a)); + let lists = [Algo::Sha256, Algo::Sha512].map(|a| (format!("{}SUMS", a.name().to_uppercase()), a)); + for (file, algo) in beside.into_iter().chain(lists) { + let mut url = source.url.clone(); + url.set_query(None); + let Ok(url) = url.join(&format!("./{file}")) else { continue }; + let list = match http::small(client, &source.at(&url), MAX_LIST, stop).await { + Ok(list) => list, + Err(Error::Status { .. } | Error::Page | Error::BadReply(_)) => continue, + Err(e) => return Err(e), + }; + if let Some(found) = find(&String::from_utf8_lossy(&list), &plain, Some(algo)) { + return Ok(Some(found)); + } + } + Ok(None) +} + +/// How a finished file stands to its checksum. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + /// There is nothing to compare it with. + Nothing, + /// Not compared yet. + Open, + /// `TaskView::checked` tells how far. + Checking, + Good, + Bad, +} + +impl State { + /// For the user. + pub fn label(self) -> String { + match self { + State::Nothing => tr!("verify.nothing"), + State::Open => tr!("verify.open"), + State::Checking => tr!("verify.checking"), + State::Good => tr!("verify.good"), + State::Bad => tr!("verify.bad"), + } + } +} + +/// What can be done about a file that doesn't match. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Offer { + /// Only the wrong pieces come again: `Command::Resume`. + Repair, + /// From the start, from the next mirror: `Command::OtherMirror`. + OtherMirror, + /// From the start: `Command::Redownload`. + Restart, +} + +impl Offer { + pub fn label(self) -> String { + match self { + Offer::Repair => tr!("verify.repair"), + Offer::OtherMirror => tr!("verify.other_mirror"), + Offer::Restart => tr!("verify.restart"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const EMPTY: [(Algo, &str); 4] = [ + (Algo::Md5, "d41d8cd98f00b204e9800998ecf8427e"), + (Algo::Sha1, "da39a3ee5e6b4b0d3255bfef95601890afd80709"), + (Algo::Sha256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), + ( + Algo::Sha512, + "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", + ), + ]; + + #[test] + fn length_tells_the_kind() { + for (algo, text) in EMPTY { + let c: Checksum = text.to_uppercase().parse().unwrap(); + assert_eq!((c.algo, c.to_string()), (algo, format!("{}:{text}", algo.name()))); + assert_eq!(c.to_string().parse(), Ok(c.clone())); + assert_eq!(Hash::new(algo).end(), c.hash); + } + let b3 = "blake3:af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"; + assert_eq!(b3.parse::().unwrap().hash, Hash::new(Algo::Blake3).end()); + assert_eq!(b3.parse::().unwrap().to_string(), b3); + } + + #[test] + fn pasted_text() { + let (_, sha) = EMPTY[2]; + let want: Checksum = sha.parse().unwrap(); + let sri = format!("sha256-{}", BASE64_STANDARD.encode(&want.hash)); + for text in [ + format!(" {sha} \n"), + format!("SHA-256: {sha}"), + format!("sha256={sha}"), + format!("SHA256 = {sha}"), + format!("sha256\t{sha}"), + format!("SHA256 (a b.iso) = {sha}"), + format!("{sha} *a b.iso"), + format!("# list\n\n{sha} a.iso\n"), + sri, + ] { + assert_eq!(text.parse(), Ok(want.clone()), "{text}"); + } + for text in ["", "hello", "sha256:", "abc", "md5:e3b0", &format!("md5: {sha}"), "sha256-####", "https://a/b", "é: ü"] { + assert_eq!(text.parse::(), Err(()), "{text}"); + } + } + + #[test] + fn lists() { + let [a, b] = [1u8, 2].map(|n| hex(&[n; 32])); + let list = format!("{a} ./dir/a.iso\n{b} *b.iso\nMD5 (a.iso) = {}\n", hex(&[3; 16])); + assert_eq!(find(&list, "a.iso", None).unwrap().hash, [1; 32]); + assert_eq!(find(&list, "b.iso", Some(Algo::Blake3)).unwrap().algo, Algo::Blake3); + assert_eq!(find(&list, "c.iso", None), None); + assert_eq!(find(&a, "c.iso", None).unwrap().hash, [1; 32], "alone, it is for any file"); + assert_eq!(find(&format!("{a} x.iso"), "c.iso", None), None); + assert_eq!(find(&format!("{a}\n{b}"), "c.iso", None), None); + } + + #[test] + fn pieces_and_whole() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("f"); + let data: Vec = (0..2_500_000u32).map(|i| (i % 251) as u8).collect(); + let sum = |algo, data: &[u8]| { + let mut h = Hash::new(algo); + h.update(data); + h.end() + }; + let pieces = |size: usize| { + let hashes = data.chunks(size).flat_map(|c| sum(Algo::Sha1, c)).collect(); + Some(Arc::new(Pieces::new(Algo::Sha1, size as u64, hashes).unwrap())) + }; + let checksum = Checksum::new(Algo::Blake3, sum(Algo::Blake3, &data)); + let read = |checksum: &Option, pieces| { + let w = Wanted { checksum: checksum.clone(), pieces }; + w.read(&path, |_| {}, || false).unwrap().unwrap() + }; + std::fs::write(&path, &data).unwrap(); + for size in [1000, 300_000, 1 << 20, 2_500_000, 9_000_000] { + assert_eq!(read(&None, pieces(size)), Found::Good("pieces".into())); + assert!(matches!(read(&checksum, pieces(size)), Found::Good(_))); + assert_eq!(pieces(size).unwrap().to_string().parse(), Ok((*pieces(size).unwrap()).clone())); + } + assert_eq!(read(&None, None), Found::Nothing); + let mut wrong = data.clone(); + for at in [0, 299_999, 300_000, 2_499_999] { + wrong[at] ^= 1; + } + std::fs::write(&path, &wrong).unwrap(); + assert_eq!(read(&checksum, pieces(300_000)), Found::Bad(vec![0..600_000, 2_400_000..2_500_000])); + assert_eq!(read(&None, pieces(1000)), Found::Bad(vec![0..1000, 299_000..301_000, 2_499_000..2_500_000])); + assert_eq!(read(&checksum, None), Found::Bad(vec![])); + // Pieces of another file. + std::fs::write(&path, &data[..9]).unwrap(); + assert_eq!(read(&None, pieces(1000)), Found::Bad(vec![])); + let stopped = Wanted { checksum, pieces: None }.read(&path, |_| {}, || true).unwrap(); + assert_eq!(stopped, None); + } + + #[test] + fn pieces_from_the_store() { + for bad in ["", "sha1", "sha1:5", "sha1:0:AAAA", "sha1:5:AAAA", "nope:5:AAAA", "sha1:x:"] { + assert!(bad.parse::().is_err(), "{bad}"); + } + assert!(Pieces::new(Algo::Md5, 1, vec![0; 16 * (MAX_PIECES + 1)]).is_none()); + let p = Pieces::new(Algo::Md5, 10, vec![0; 48]).unwrap(); + assert!(p.fit(21) && p.fit(30) && !p.fit(20) && !p.fit(31)); + } +} diff --git a/crates/core/tests/mirror.rs b/crates/core/tests/mirror.rs new file mode 100644 index 0000000..d4b69f1 --- /dev/null +++ b/crates/core/tests/mirror.rs @@ -0,0 +1,498 @@ +//! Several sources for one file, metalinks, and comparing with checksums. + +use medlar_core::adapt::Timing; +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::*; +use medlar_core::manager::{Bin, Command, Config, Manager}; +use medlar_core::metalink; +use medlar_core::model::{ErrorKind, State, Task, TaskId}; +use medlar_core::relink::NewLink; +use medlar_core::segment::Rules; +use medlar_core::settings::Limits; +use medlar_core::snapshot::TaskView; +use medlar_core::store::Store; +use medlar_core::verify::{self, Algo, Checksum, Offer, Pieces}; +use medlar_testserver::{Faults, META_LEN, META_SEED, TestServer, expected}; +use sha2::{Digest, Sha256}; +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::sync::watch; +use tokio::time::sleep; + +const LEN: usize = 4 << 20; +const PIECE: usize = 256 * 1024; + +/// Speeds are measured: one test at a time. +static ALONE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +fn options() -> Options { + Options { + rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) }, + timing: Timing { settle: ms(200), window: ms(400), hold: ms(2000), refused: ms(60_000) }, + tick: ms(25), + stall: ms(1000), + patience: ms(300), + tries: 2, + backoff: ms(20), + max_wait: ms(2000), + checkpoint: ms(20), + } +} + +/// Without tags and dates, so that only the bytes tell. +fn path(seed: u64) -> String { + format!("/data/{seed}/{LEN}/a.bin?etag=0&lm=0") +} + +fn sha256(seed: u64) -> String { + format!("sha256:{}", Sha256::digest(expected(seed, 0, LEN)).iter().map(|b| format!("{b:02x}")).collect::()) +} + +fn pieces(seed: u64) -> Option> { + let hashes = expected(seed, 0, LEN).chunks(PIECE).flat_map(|c| Sha256::digest(c).to_vec()).collect(); + Pieces::new(Algo::Sha256, PIECE as u64, hashes).map(Arc::new) +} + +fn whole(path: &Path, seed: u64) { + assert!(std::fs::read(path).unwrap() == expected(seed, 0, LEN)); +} + +/// One server for the first link, one for the mirrors. +struct Bench { + one: TestServer, + two: TestServer, + dir: tempfile::TempDir, + shared: Shared, + monitor: Arc, +} + +fn shared(dir: &Path) -> Shared { + let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap()); + let client = client(&ClientOptions { idle_timeout: ms(1500), ..ClientOptions::default() }).unwrap(); + Shared { client, store, hosts: Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() }) } +} + +impl Bench { + async fn new(cap: u32) -> Bench { + let dir = tempfile::tempdir().unwrap(); + let shared = shared(dir.path()); + Bench { one: TestServer::start().await, two: TestServer::start().await, dir, shared, monitor: Arc::new(Monitor::new(cap)) } + } + + fn add(&self, task: Task) -> TaskId { + self.shared.store.add_task(Task { folder: self.dir.path().join("files"), ..task }).unwrap() + } + + /// The right file on both. + fn both(&self) -> Task { + Task { url: self.one.url(&path(1)), mirrors: vec![self.two.url(&path(1))], ..Task::default() } + } + + async fn run(&self, id: TaskId) -> Result { + let (_keep, stop) = watch::channel(false); + let source = Source::new(&self.shared.store.task(id).unwrap().url).unwrap(); + let options = options(); + let run = download(&self.shared, id, source, &options, &self.monitor, stop); + tokio::time::timeout(Duration::from_secs(60), run).await.unwrap_or_else(|_| panic!("hangs: {:?}", self.monitor.snapshot())) + } +} + +/// Body bytes of the file that a server gave. +fn sent(server: &TestServer) -> u64 { + server.requests_for("/data/1/4194304/a.bin").iter().map(|r| r.sent).sum() +} + +fn slow(per_connection: u64) -> Faults { + Faults { throttle_conn: Some(per_connection), ..Faults::default() } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_fast_mirror_brings_more_than_a_slow_one() { + let _alone = ALONE.lock().await; + for fast_first in [false, true] { + let b = Bench::new(6).await; + let (fast, sluggish) = if fast_first { (&b.one, &b.two) } else { (&b.two, &b.one) }; + fast.set_faults("*", slow(1_000_000)); + sluggish.set_faults("*", slow(60_000)); + whole(&b.run(b.add(b.both())).await.unwrap(), 1); + println!("fast {} slow {}", sent(fast), sent(sluggish)); + assert!(sent(fast) > 3 * sent(sluggish), "fast {} slow {}", sent(fast), sent(sluggish)); + assert!(sent(sluggish) > 0); + let shot = b.monitor.snapshot(); + // The fast one alone may be done before the slow one was compared. + assert!(fast_first || shot.servers.iter().all(|s| s.state == ServerState::Ready && !s.host.is_empty()), "{:?}", shot.servers); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_mirror_with_another_file_gives_nothing() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + b.one.set_faults("*", slow(800_000)); + let page = b.two.url("/site/"); + let short = b.two.url("/data/1/4194303/a.bin"); + let mirrors = vec![b.two.url(&path(2)), short, page, b.two.url("/status/404"), "gopher://x/".into(), b.two.url(&(path(1) + "&ignore_range=1"))]; + let id = b.add(Task { mirrors, ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + let shot = b.monitor.snapshot(); + assert_eq!(shot.servers.iter().filter(|s| s.state == ServerState::Ready).count(), 1, "{:?}", shot.servers); + assert!(sent(&b.two) <= LEN as u64, "only looked at"); + let used = b.two.requests_for(&format!("/data/2/{LEN}/a.bin")); + assert!(!used.is_empty() && used.iter().map(|r| r.sent).sum::() < 200_000); +} + +/// It has the same start and end, so it passes; its bytes show when another one goes on behind them. +#[tokio::test(flavor = "multi_thread")] +async fn a_caught_liar_loses_all_it_gave() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + b.one.set_faults("*", slow(300_000)); + b.two.set_faults("*", Faults { change_after: Some(64 * 1024), cut_after: Some(200 * 1024), ..Faults::default() }); + whole(&b.run(b.add(b.both())).await.unwrap(), 1); + assert!(sent(&b.two) > 100_000, "it was used: {}", sent(&b.two)); + assert_eq!(b.monitor.snapshot().servers[1].state, ServerState::Out); +} + +#[tokio::test(flavor = "multi_thread")] +async fn wrong_pieces_of_a_lying_mirror_come_again() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + b.one.set_faults("*", slow(300_000)); + b.two.set_faults("*", Faults { change_after: Some(64 * 1024), ..slow(2_000_000) }); + let id = b.add(Task { checksum: Some(sha256(1)), pieces: pieces(1), ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + assert!(sent(&b.two) > 100_000, "it was used: {}", sent(&b.two)); + assert_eq!(b.shared.store.task(id).unwrap().verified, Some(sha256(1))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn bad_mirrors_are_dropped_alone() { + let _alone = ALONE.lock().await; + // Dead at once, dead later, refusing, cutting. + let faults = [ + Faults { expire_requests: Some(9), ..Faults::default() }, + Faults { expire_requests: Some(9), expire_status: Some(503), ..Faults::default() }, + Faults { cut_after: Some(8000), ..Faults::default() }, + ]; + for f in faults { + for mirror in [true, false] { + let b = Bench::new(4).await; + let (bad, good) = if mirror { (&b.two, &b.one) } else { (&b.one, &b.two) }; + good.set_faults("*", slow(500_000)); + bad.set_faults("*", Faults { throttle_conn: Some(500_000), ..f.clone() }); + let id = b.add(b.both()); + match b.run(id).await { + Ok(file) => whole(&file, 1), + // The first one died before the mirror was compared. The next run begins with the mirror. + Err(_) if !mirror => whole(&b.run(id).await.unwrap(), 1), + Err(e) => panic!("{f:?}: {e:?}"), + } + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_dead_first_link_is_replaced_also_later() { + let _alone = ALONE.lock().await; + let b = Bench::new(2).await; + b.one.set_faults("*", Faults::status(404)); + let id = b.add(b.both()); + whole(&b.run(id).await.unwrap(), 1); + // Half of it came from the first link. + b.one.set_faults("*", slow(1_000_000)); + b.two.set_faults("*", Faults::status(404)); + let id = b.add(b.both()); + let (stop, stopping) = watch::channel(false); + let source = Source::new(&b.one.url(&path(1))).unwrap(); + let options = options(); + let run = download(&b.shared, id, source, &options, &b.monitor, stopping); + let (result, ()) = tokio::join!(run, async { + sleep(ms(700)).await; + stop.send_replace(true); + }); + assert!(matches!(result, Err(Error::Stopped))); + b.one.set_faults("*", Faults::status(410)); + b.two.clear_all_faults(); + b.two.clear_log(); + whole(&b.run(id).await.unwrap(), 1); + assert!(sent(&b.two) < LEN as u64, "it went on: {}", sent(&b.two)); + // Another file is never continued from; the error is the first link's. + let id = b.add(Task { mirrors: vec![b.two.url(&path(2))], ..b.both() }); + b.shared.store.edit_task(id, |t| t.size = Some(LEN as u64)).unwrap(); + b.one.clear_all_faults(); + b.one.set_faults("*", Faults { expire_requests: Some(2), ..slow(200_000) }); + assert!(b.run(id).await.is_err()); + assert!(matches!(b.run(id).await, Err(Error::Status { code: 403, .. }))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_corrupt_piece_is_repaired() { + let _alone = ALONE.lock().await; + let b = Bench::new(1).await; + // The only source: wrong until it isn't. + b.one.set_faults("*", Faults { change_after: Some(3 << 20), ..Faults::default() }); + let task = Task { url: b.one.url(&path(1)), pieces: pieces(1), checksum: Some(sha256(1)), ..Task::default() }; + let id = b.add(task.clone()); + // One wrong megabyte is four pieces, asked for again in one: the first time it is whole, so the server has nothing to lie about. + whole(&b.run(id).await.unwrap(), 1); + let again = sent(&b.one) - LEN as u64; + assert!((1 << 20..(1 << 20) + 100_000).contains(&again), "{again}"); + assert_eq!(b.shared.store.task(id).unwrap().verified, Some(sha256(1))); + + // It never gets better, until a mirror takes over. + b.one.set_faults("*", Faults { change_after: Some(1000), ..Faults::default() }); + let id = b.add(task.clone()); + assert!(matches!(b.run(id).await, Err(Error::Checksum))); + b.one.clear_log(); + assert!(matches!(b.run(id).await, Err(Error::Checksum)), "still"); + assert!(b.shared.store.task(id).unwrap().verified.is_none()); + b.shared.store.edit_task(id, |t| t.mirrors = vec!["http://127.0.0.1:9/x".into()]).unwrap(); + let mirror = b.two.url(&path(1)); + b.shared.store.edit_task(id, move |t| t.mirrors.push(mirror)).unwrap(); + whole(&b.run(id).await.unwrap(), 1); + + // Without hashes of pieces there is nothing to repair. + let id = b.add(Task { pieces: None, ..task }); + assert!(matches!(b.run(id).await, Err(Error::Checksum))); + let task = b.shared.store.task(id).unwrap(); + assert!(task.folder.join(format!("{}.medlar", task.name)).exists(), "kept, and not under its name"); + assert!(!task.folder.join(&task.name).exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn pieces_of_another_size_refuse_the_file() { + let _alone = ALONE.lock().await; + let b = Bench::new(1).await; + let id = b.add(Task { url: b.one.url("/data/1/1m/a.bin"), pieces: pieces(1), ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + assert_eq!(b.shared.store.task(id).unwrap().verified.as_deref(), Some("pieces")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn every_kind_of_checksum() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + for algo in Algo::ALL { + let checksum = match algo { + Algo::Blake3 => Checksum::new(algo, blake3::hash(&expected(1, 0, LEN)).as_bytes().to_vec()), + _ => { + let source = Source::new(&b.one.url(&format!("/sum/{}/1/{LEN}", algo.name()))).unwrap(); + let body = reqwest_text(&b, source).await; + verify::find(&body, "data-1.bin", None) + } + }; + let checksum = checksum.unwrap(); + assert_eq!(checksum.algo, algo); + let id = b.add(Task { checksum: Some(checksum.to_string()), ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + assert_eq!(b.shared.store.task(id).unwrap().verified, Some(checksum.to_string())); + let id = b.add(Task { url: b.one.url(&path(2)), mirrors: vec![], checksum: Some(checksum.to_string()), ..Task::default() }); + assert!(matches!(b.run(id).await, Err(Error::Checksum)), "{algo:?}"); + } +} + +async fn reqwest_text(b: &Bench, source: Source) -> String { + let id = b.add(Task { url: source.url.to_string(), name: "sum".into(), ..Task::default() }); + std::fs::read_to_string(b.run(id).await.unwrap()).unwrap() +} + +// The manager. + +struct Managed { + server: TestServer, + dir: tempfile::TempDir, + manager: Manager, +} + +impl Managed { + async fn new() -> Managed { + let dir = tempfile::tempdir().unwrap(); + let limits = Limits { speed: 0, max_active: 8, max_connections: 32, parts_per_download: 4, connections_per_host: 16 }; + let mut config = Config::new(shared(dir.path()), limits); + config.options = options(); + (config.bin, config.tick) = (Bin::at(dir.path().join("Trash")), ms(2)); + Managed { server: TestServer::start().await, manager: Manager::open(config).unwrap(), dir } + } + + async fn add(&self, task: Task) -> TaskId { + self.run(Command::Add(Box::new(Task { folder: self.dir.path().join("files"), ..task }))).await + } + + async fn run(&self, command: Command) -> TaskId { + self.manager.send(command).await.unwrap() + } + + async fn until(&self, id: TaskId, what: &str, is: impl Fn(&TaskView) -> bool) -> Arc { + let end = Instant::now() + Duration::from_secs(40); + loop { + let view = self.manager.snapshot().get(id).unwrap().clone(); + if is(&view) { + return view; + } + assert!(Instant::now() < end, "never {what}: {:?} {:?} {:#?}", view.state(), view.task.error, view.log); + sleep(ms(1)).await; + } + } + + async fn done(&self, id: TaskId) -> Arc { + self.until(id, "done", |v| v.state() == State::Done).await + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn states_of_the_check() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + let good = m.add(Task { url: m.server.url(&path(1)), checksum: Some(sha256(1)["sha256:".len()..].to_uppercase()), ..Task::default() }).await; + let view = m.done(good).await; + assert_eq!((view.verify(), view.task.checksum.as_deref()), (verify::State::Good, Some(&*sha256(1)))); + assert!(view.offers().is_empty()); + let none = m.add(Task { url: m.server.url(&path(1)), ..Task::default() }).await; + assert_eq!(m.done(none).await.verify(), verify::State::Nothing); + + // One that doesn't match, and its ways out. + let bad = m.add(Task { url: m.server.url(&path(2)), mirrors: vec![m.server.url(&path(1))], checksum: Some(sha256(1)), ..Task::default() }).await; + let view = m.until(bad, "failed", |v| v.state() == State::Failed).await; + assert_eq!(view.task.error.as_ref().unwrap().kind, Some(ErrorKind::Checksum)); + assert_eq!((view.verify(), view.offers()), (verify::State::Bad, vec![Offer::OtherMirror, Offer::Restart])); + m.run(Command::OtherMirror(bad)).await; + let view = m.done(bad).await; + whole(&view.task.folder.join(&view.task.name), 1); + assert_eq!((view.verify(), view.task.mirrors.clone()), (verify::State::Good, vec![m.server.url(&path(2))])); + + // A pasted one counts when the file was compared with it. + m.run(Command::Edit { id: none, edit: Box::new(|t| t.checksum = Some(format!("SHA-256: {}", &sha256(1)[7..]))) }).await; + let view = m.until(none, "open", |v| v.verify() == verify::State::Open).await; + let (finished, counted) = (view.task.finished_at, view.counters.finished); + m.run(Command::Verify(none)).await; + let view = m.until(none, "good", |v| v.verify() == verify::State::Good).await; + assert_eq!((view.state(), view.task.finished_at, view.counters.finished), (State::Done, finished, counted)); + + // It rots on the disk. + let file = view.task.folder.join(&view.task.name); + let mut data = std::fs::read(&file).unwrap(); + data[3_000_000] ^= 1; + std::fs::write(&file, &data).unwrap(); + m.run(Command::Verify(none)).await; + let view = m.until(none, "bad", |v| v.verify() == verify::State::Bad).await; + assert_eq!((view.state(), view.offers()), (State::Failed, vec![Offer::Restart])); + assert!(file.exists()); + + // With pieces it is repaired at once. + let id = m.add(Task { url: m.server.url(&path(1)), pieces: pieces(1), ..Task::default() }).await; + let view = m.done(id).await; + let file = view.task.folder.join(&view.task.name); + let mut data = std::fs::read(&file).unwrap(); + data[3_000_000] ^= 1; + std::fs::write(&file, &data).unwrap(); + m.server.clear_log(); + m.run(Command::Verify(id)).await; + m.until(id, "good", |v| v.state() == State::Done && v.verify() == verify::State::Good).await; + whole(&file, 1); + assert!(sent(&m.server) < 2 * PIECE as u64, "{}", sent(&m.server)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn checking_can_be_seen_and_paused() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + // Long enough to be seen: MD5 in a debug build, 300 MB. + let len = 300u64 << 20; + let task = Task { url: m.server.url(&format!("/data/1/{len}/big.bin")), checksum: Some("00".repeat(16)), ..Task::default() }; + let id = m.add(task).await; + let end = Instant::now() + Duration::from_secs(40); + let mut seen = vec![]; + while seen.len() < 2 { + let view = m.manager.snapshot().get(id).unwrap().clone(); + if view.verify() == verify::State::Checking && view.checked > 0.0 && seen.last() != Some(&view.checked) { + seen.push(view.checked); + } + assert!(Instant::now() < end && view.state() != State::Failed, "{:?} {seen:?}", view.state()); + sleep(ms(1)).await; + } + assert!(seen.is_sorted() && seen[1] <= 1.0); + m.run(Command::Pause(id)).await; + let view = m.until(id, "paused", |v| v.state() == State::Paused && v.connections == 0).await; + assert_eq!(view.checked, 0.0); + sleep(ms(100)).await; + assert_eq!(m.until(id, "still paused", |_| true).await.state(), State::Paused); + m.server.clear_log(); + m.run(Command::Resume(id)).await; + let view = m.until(id, "failed", |v| v.state() == State::Failed).await; + assert_eq!(view.verify(), verify::State::Bad); + assert!(m.server.log().is_empty(), "it was whole"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn metalinks_and_headers() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + for (file, algo) in [("/meta/v4.meta4", "sha256"), ("/meta/v3.metalink", "sha1")] { + assert!(metalink::is(file, None)); + let link = NewLink { url: m.server.url(file), ..NewLink::default() }; + let files = m.manager.read_metalink(link).await.unwrap(); + let task = files[0].task(); + assert_eq!((task.name.as_str(), task.mirrors.len()), ("meta.bin", 1)); + let id = m.add(task).await; + let view = m.done(id).await; + assert_eq!(view.verify(), verify::State::Good); + assert!(view.task.checksum.as_ref().unwrap().starts_with(algo)); + assert!(std::fs::read(view.task.folder.join(&view.task.name)).unwrap() == expected(META_SEED, 0, META_LEN as usize)); + } + let id = m.add(Task { url: m.server.url("/meta/header.bin"), ..Task::default() }).await; + let view = m.done(id).await; + assert_eq!((view.verify(), view.task.mirrors.len()), (verify::State::Good, 1)); + // Not one. + let link = NewLink { url: m.server.url("/data/1/1000"), ..NewLink::default() }; + assert!(m.manager.read_metalink(link).await.is_err()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn sidecars() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + let id = m.add(Task { url: m.server.url("/meta/header.bin"), ..Task::default() }).await; + m.done(id).await; + assert_eq!(m.manager.find_checksum(id).await.unwrap(), None); + // Beside the file, and in a list. + let files = vec![ + ("/d/a%20b.iso.sha512", format!("{} a b.iso\n", "ab".repeat(64))), + ("/d/SHA256SUMS", format!("{} other.iso\n{} *listed.iso\n", "11".repeat(32), "22".repeat(32))), + ]; + let base = serve(files); + for (name, want) in [("a%20b.iso?x=1", Some(Checksum::new(Algo::Sha512, vec![0xab; 64]).unwrap())), ("listed.iso", "22".repeat(32).parse().ok()), ("c", None)] { + let id = m.add(Task { url: format!("{base}/d/{name}"), state: State::Paused, ..Task::default() }).await; + assert_eq!(m.manager.find_checksum(id).await.unwrap(), want, "{name}"); + } +} + +/// Answers 404 to all else. +fn serve(files: Vec<(&'static str, String)>) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + for mut stream in listener.incoming().flatten() { + let mut line = String::new(); + let mut lines = BufReader::new(stream.try_clone().unwrap()); + lines.read_line(&mut line).unwrap(); + let path = line.split(' ').nth(1).unwrap_or("").to_string(); + while line.trim() != "" { + line.clear(); + lines.read_line(&mut line).unwrap(); + } + let (status, body) = match files.iter().find(|f| f.0 == path) { + Some((_, body)) => ("200 OK", body.as_str()), + None => ("404 Not Found", ""), + }; + let _ = write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + } + }); + base +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 8f03492..29935ad 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -52,3 +52,6 @@ - D-050 — 2026-11-25 — One listing type for all (`listing::Entry`), with the link made of the raw bytes of the name; entries whose names could leave their folder are dropped. SFTP is russh with ring (no aws-lc-rs) and russh-sftp: a connection per part, 2 to 64 reads of 32 KiB under way, more only when they come too late. - D-051 — 2026-11-25 — Keys of SSH servers are in Medlar's own file (`Paths::known_hosts`), never in `~/.ssh`. An unknown or changed key stops the download before any login is sent; a key of another kind than the known one counts as changed. Only `host_keys.accept` adds one, and it replaces the server's old ones. With a key file, the login's password is its passphrase and is not sent to the server if it unlocked the key. - D-052 — 2026-11-25 — From here on the plans run on the branch `claude/orchestrate-0ad55c` (a new worktree); the rest of D-014 holds: sessions push only the branch, the orchestrator fast-forwards `main` after each validated category. — New orchestrator session. — all +- D-053 — 2026-11-25 — A mirror is used only after S008's comparison with what is here (verdict same or probably same, at least 16 KiB here) and, where no version proves it, after two more places that the base and the mirror must both have. Whoever is caught with other bytes is dropped and all it gave comes again; between the base and a mirror the mirror is the liar. If the first link fails, the next one that passes becomes the base. Each connection goes to the server that brings the most per connection, an untried one first; a connection four times slower than another server's moves there. — A wrong byte costs more than a slow start — 02, 06 +- D-054 — 2026-11-25 — Files are compared under their unfinished name, before they get their own, in the state `checking` (no place in the queue); `Checking` may go back to `Running` (pieces) and, for a file that was done before, to `Done`, which is no new finish. `Task::verified` holds what the file matched, so a new checksum counts as open by itself. The whole file's hash counts more than its pieces'. — A bad file never appears finished — 03, 05 +- D-055 — 2026-11-25 — Headers give mirrors only with a `Digest` or `Repr-Digest` (RFC 6249); they and a linked metalink fill only what the task doesn't have. Sidecars are looked for only when asked. Metalinks are read by quick-xml within limits; a document type or an unknown entity refuses the file. — No extra requests, nothing to expand — 02, 06 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b95e9ab..c198adc 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -159,5 +159,16 @@ Verified: `nice cargo test -j 2 -p medlar --test settings` green (26), all medla Not done: notifications and power have no settings yet, so these pages are hidden until later plans add rows; no folder chooser (a plain field); the SFTP key of a site (S011) has no field; a site's old login is deleted from the keyring only when the settings screen closes; the toast's Undo puts all settings back, not only that change. Real keyring, real desktop scheme change and a real GPU not tried. Seen: boxes 2 to 7 were ticked together after the tests, against rule 3. +## S009 — Mirrors, Metalink and checksums (2026-11-25) +Done: `core::{verify, metalink, mirror}`; several servers per download in `http/{download,parts,monitor}`, `Checking` in the manager, migration 004 (`Task::pieces`, `verified`). Choices: D-053 to D-055. Outside the plan's files: those, `probe`, `fetch` (`small`, `bytes_at`), `relink::open_link`, `snapshot`, `error`, strings; crates `blake3`, `quick-xml` 0.41 and `sha1` (the last two were in the tree). +- Verify states for the UI: `view.verify()` → `verify::State::{Nothing, Open, Checking, Good, Bad}`, each with `label()`; while `Checking` (also the task's state) `view.checked` is the share. `Bad` comes with `ErrorKind::Checksum`; `view.offers()` → `Offer::{Repair, OtherMirror, Restart}` with `label()`: `Command::{Resume, OtherMirror, Redownload}`. A finished file: `Command::Verify(id)` (after a pasted checksum: `Command::Edit`, then this). +- Checksum field: any pasted text, `text.parse::()` tells the kind (64 digits are SHA-256; BLAKE3 needs `blake3:`). `manager.find_checksum(id)` looks for sidecars, only when asked. Task's `checksum` is `sha256:…`. +- Metalink: `metalink::is(name, mime)`, `manager.read_metalink(link)` or `metalink::parse(&bytes)`, then `file.task()` (set the folder). Nothing in the app calls it yet (S016, S030). +- `http::Snapshot.servers` has each link's host, state, connections, speed (for the details panel). +- Wrong pieces come again by themselves, up to three times, without the mirror that gave them. +Not done: the Fix for `Checksum` in the list is the general `Choose` menu, not `offers()`; which mirror gave what is not kept over a restart; a mirror whose host has a speed limit is not used beside another host (the limit is of one host per download); no mirrors for files under 16 KiB, of unknown size or without ranges; a first link that dies before a mirror was compared fails the run, and the next one starts with the mirror. S019 applies host limits already (checked, not redone). +Verified: `nice cargo test -j 2 -p medlar-core --test mirror` green (13, three times; 36 to 49 s), all of core and clippy green with the S012 and S016 work of that moment. Covered: fast and slow mirror, other file, short file, page, caught liar, corrupt pieces, dead first and later links, all five kinds, paste, sidecars, headers, both metalinks, hostile XML, rot on disk, pause while checking. +Seen: boxes 2 to 5 were ticked together after the tests. A copy of the tree built into the shared target makes cargo take its artifacts for fresh ones of the real tree: never do that. + ## Later - diff --git a/docs/RECOVERY.md b/docs/RECOVERY.md index cfaa154..2385b6f 100644 --- a/docs/RECOVERY.md +++ b/docs/RECOVERY.md @@ -36,6 +36,7 @@ Title and text: `error.` and `error..why` in the catalogue; button: | `rejected` | Request rejected | blocked | no | Edit link (`edit_link`) | | `bad_link` | Link can't be used | blocked | no | Edit link (`edit_link`) | | `changed` | File changed on the server | blocked | no | Choose (`choose`) | +| `checksum` | File is damaged | blocked | no | Choose (`choose`) | | `no_resume` | Can't be continued | blocked | no | Choose (`choose`) | | `killed` | Interrupted | passing | no | Resume (`resume`) | | `drm` | Copy protected | blocked | no | Edit link (`edit_link`) |