S009: mirrors, Metalink and checksums
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
d26c59ee26
commit
f9eec8f161
29 changed files with 2597 additions and 106 deletions
22
Cargo.lock
generated
22
Cargo.lock
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<Range<u64>>)>;
|
||||
|
||||
/// 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<PathBuf> {
|
||||
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<String> {
|
||||
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<Opened> {
|
||||
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<PartialFile>, Vec<Part>)> {
|
||||
async fn start(shared: &Shared, job: &Job, task: &Task, probe: Probe, link: &Link, stop: &mut Stop) -> Result<(Arc<PartialFile>, Vec<Part>)> {
|
||||
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<PartialFile>
|
|||
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<PartialFile>
|
|||
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<metalink::File> {
|
||||
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<Part>, link: &Link, stop: &mut Stop) -> Result<(Arc<PartialFile>, Vec<Part>)> {
|
||||
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<Part>,
|
||||
link: &Link,
|
||||
compared: bool,
|
||||
stop: &mut Stop,
|
||||
) -> Result<(Arc<PartialFile>, Vec<Part>)> {
|
||||
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<Task> {
|
||||
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<Range<u64>>) -> 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<T: Send + 'static>(&self, work: impl FnOnce(&Store) -> Result<T> + Send + 'static) -> Result<T> {
|
||||
let store = self.store.clone();
|
||||
blocking(move || work(&store)).await
|
||||
|
|
|
|||
|
|
@ -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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<bool> {
|
||||
let mut rest = known;
|
||||
|
|
|
|||
|
|
@ -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<u64> },
|
||||
/// 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<Source> {
|
||||
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()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<u64>,
|
||||
|
|
@ -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<ServerView>,
|
||||
/// Share of the file that was compared with its checksum, while that goes on.
|
||||
pub checked: Option<f32>,
|
||||
}
|
||||
|
||||
/// One per download; outlives its runs.
|
||||
|
|
@ -67,6 +92,7 @@ pub struct Monitor {
|
|||
state: Mutex<(Snapshot, Vec<Arc<LivePart>>)>,
|
||||
flow: Arc<Flow>,
|
||||
finish: watch::Sender<bool>,
|
||||
checked: Arc<Mutex<Option<f32>>>,
|
||||
}
|
||||
|
||||
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<Mutex<Option<f32>>> {
|
||||
self.checked.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn cap(&self) -> watch::Receiver<u32> {
|
||||
self.cap.subscribe()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Link>,
|
||||
shared: &'a Shared,
|
||||
task: Arc<Task>,
|
||||
/// The base first, then the mirrors.
|
||||
servers: Vec<Server>,
|
||||
checks: JoinSet<(usize, Result<Option<Link>>)>,
|
||||
/// Why the last server that was given up failed.
|
||||
gave_up: Option<Error>,
|
||||
/// Servers whose bytes have to come again. Nothing runs meanwhile.
|
||||
distrusted: Vec<usize>,
|
||||
file: Arc<PartialFile>,
|
||||
body: Option<Response>,
|
||||
host: String,
|
||||
hosts: Arc<Hosts>,
|
||||
member: Member,
|
||||
/// Its speed had a limit, so it says nothing about the host.
|
||||
limited: bool,
|
||||
max_parts: Option<u32>,
|
||||
|
|
@ -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<Ready>,
|
||||
/// Bytes per second of one of its connections.
|
||||
speed: Option<f64>,
|
||||
/// No connection before this.
|
||||
rest_until: Option<Instant>,
|
||||
/// 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<Range<u64>>,
|
||||
}
|
||||
|
||||
struct Ready {
|
||||
link: Arc<Link>,
|
||||
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<u64>) {
|
||||
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<LivePart>,
|
||||
|
|
@ -59,9 +113,14 @@ struct Slot {
|
|||
swaps: u32,
|
||||
/// Had a connection before.
|
||||
used: bool,
|
||||
/// The server its last bytes came from.
|
||||
last: Option<usize>,
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
server: usize,
|
||||
/// Where it began.
|
||||
from: u64,
|
||||
stop: watch::Sender<bool>,
|
||||
permit: Permit,
|
||||
leaving: bool,
|
||||
|
|
@ -87,6 +146,15 @@ impl Slot {
|
|||
}
|
||||
}
|
||||
|
||||
/// What is left of a run.
|
||||
pub(super) struct Ended {
|
||||
pub live: Vec<Arc<LivePart>>,
|
||||
/// The number of connections to remember for the base's host.
|
||||
pub learned: Option<u32>,
|
||||
/// The links, the base's first, and what came from each.
|
||||
pub gave: Vec<(String, Vec<Range<u64>>)>,
|
||||
}
|
||||
|
||||
/// 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<Task>,
|
||||
base: (String, Link),
|
||||
mirrors: Vec<(String, Source)>,
|
||||
file: Arc<PartialFile>,
|
||||
parts: Vec<Part>,
|
||||
body: Option<Response>,
|
||||
host: String,
|
||||
start: u32,
|
||||
max_parts: Option<u32>,
|
||||
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<Arc<LivePart>>, Option<u32>) {
|
||||
(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<Link> {
|
||||
&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<Part> = 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::<u64>() >= NEEDED
|
||||
}
|
||||
|
||||
fn checked(&mut self, i: usize, result: Result<Option<Link>>) {
|
||||
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<Part> = 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<usize> = (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<Arc<LivePart>> {
|
||||
|
|
@ -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<usize>, 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<f64> = 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::<f64>() / 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,
|
||||
|
|
|
|||
|
|
@ -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<String>,
|
||||
/// 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<Response>,
|
||||
}
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
|
|
|||
|
|
@ -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<bool>,
|
||||
/// Its next run ends a stream at once.
|
||||
finish: bool,
|
||||
checked: f32,
|
||||
meter: Meter,
|
||||
history: Arc<History>,
|
||||
/// 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<Result<Option<Checksum>>>) {
|
||||
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<Result<Vec<metalink::File>>>) {
|
||||
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<Result<Found>>) {
|
||||
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<Answer>) {
|
||||
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<PathBuf, Why>) {
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<dyn FnOnce(&mut Task) + Send> },
|
||||
|
|
@ -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<Result<TaskId>>;
|
|||
enum Msg {
|
||||
Command(Command, Option<Answer>),
|
||||
Check(TaskId, NewLink, oneshot::Sender<Result<Checked>>),
|
||||
FindChecksum(TaskId, oneshot::Sender<Result<Option<Checksum>>>),
|
||||
ReadMetalink(NewLink, oneshot::Sender<Result<Vec<metalink::File>>>),
|
||||
CheckPartial(PathBuf, NewLink, oneshot::Sender<Result<Found>>),
|
||||
Limits(Limits),
|
||||
OnChange(Box<dyn Fn() + Send>),
|
||||
|
|
@ -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<Option<Checksum>> {
|
||||
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<Vec<metalink::File>> {
|
||||
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<Found> {
|
||||
let (answer, reply) = oneshot::channel();
|
||||
|
|
|
|||
452
crates/core/src/metalink.rs
Normal file
452
crates/core/src/metalink.rs
Normal file
|
|
@ -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<u64>,
|
||||
/// The strongest it has.
|
||||
pub checksum: Option<Checksum>,
|
||||
pub pieces: Option<Arc<Pieces>>,
|
||||
/// The best first.
|
||||
pub urls: Vec<String>,
|
||||
}
|
||||
|
||||
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<Vec<File>> {
|
||||
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<Checksum>,
|
||||
/// Kind, length, hashes.
|
||||
pieces: Option<(Option<Algo>, u64, Vec<u8>)>,
|
||||
best: Option<Pieces>,
|
||||
/// None: the pieces can't be used.
|
||||
piece_index: Option<u64>,
|
||||
}
|
||||
|
||||
impl Building {
|
||||
fn end(mut self) -> Option<File> {
|
||||
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<Vec<File>, 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<String> = vec![];
|
||||
let mut text = String::new();
|
||||
let mut attributes: Vec<(String, String)> = vec![];
|
||||
let mut files = vec![];
|
||||
let mut file: Option<Building> = 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::<Checksum>();
|
||||
// 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::<i64>().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<Vec<(String, String)>, 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<String> {
|
||||
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<Checksum>,
|
||||
/// The best first. Only with a checksum, as RFC 6249 wants it.
|
||||
pub mirrors: Vec<String>,
|
||||
/// A metalink file about it.
|
||||
pub metalink: Option<Url>,
|
||||
}
|
||||
|
||||
/// `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
|
||||
}
|
||||
|
||||
/// `<target>; name=value; name="value", <target> …`
|
||||
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!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<metalink xmlns=\"urn:ietf:params:xml:ns:metalink\">{inner}</metalink>")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_4() {
|
||||
let text = v4(&format!(
|
||||
"<generator>x & y</generator>
|
||||
<file name=\"../../a/b.iso\"><size>500</size><hash type=\"md5\">{MD5}</hash><hash type=\"sha-256\"> {SHA}\n</hash>
|
||||
<hash type=\"whirlpool\">00</hash>
|
||||
<pieces length=\"300\" type=\"md5\"><hash>{MD5}</hash><hash>{MD5}</hash></pieces>
|
||||
<url priority=\"2\">https://two/f?a=1&b=2</url><url location=\"de\" priority=\"1\"><![CDATA[http://one/f]]></url>
|
||||
<url>ftp://three/f</url><url priority=\"1\">magnet:?xt=1</url><url>http://user:pw@four/f</url><url>http://one/f</url>
|
||||
<metaurl mediatype=\"torrent\">http://t/f.torrent</metaurl></file>
|
||||
<file name=\"none\"/><file name=\"b\"><url>sftp://h/b</url></file>"
|
||||
));
|
||||
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!(
|
||||
"<metalink version=\"3.0\" xmlns=\"http://www.metalinker.org/\"><files><file name=\"a\"><size>9</size>
|
||||
<verification><hash type=\"md5\">{MD5}</hash><hash type=\"sha1\">da39a3ee5e6b4b0d3255bfef95601890afd80709</hash>
|
||||
<pieces length=\"4\" type=\"md5\"><hash piece=\"0\">{MD5}</hash><hash piece=\"1\">{MD5}</hash><hash piece=\"2\">{MD5}</hash></pieces>
|
||||
</verification>
|
||||
<resources><url type=\"http\" preference=\"10\">http://b/</url><url type=\"bittorrent\">http://t/</url>
|
||||
<url type=\"http\" preference=\"100\">http://a/</url></resources></file></files></metalink>"
|
||||
);
|
||||
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("<size>9", "<size>900").as_bytes()).unwrap().remove(0);
|
||||
assert_eq!(short.pieces, None, "they don't fit the size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_files() {
|
||||
let url = "<url>http://a/</url>";
|
||||
let file = format!("<file name=\"a\">{url}</file>");
|
||||
for (text, why) in [
|
||||
(format!("<!DOCTYPE metalink [<!ENTITY a \"b\">]>{}", v4(&file)), Bad::Unsafe),
|
||||
(format!("<!DOCTYPE metalink SYSTEM \"file:///etc/passwd\"><metalink>{file}</metalink>"), Bad::Unsafe),
|
||||
(v4("<file name=\"a\"><url>http://a/&lol;</url></file>"), Bad::Unsafe),
|
||||
(v4("<file name=\"&lol;\"><url>http://a/</url></file>"), Bad::Unsafe),
|
||||
(v4(&("<x>".repeat(100) + &"</x>".repeat(100))), Bad::Unsafe),
|
||||
(v4(&"<file name=\"a\"><url>http://a/</url></file>".repeat(MAX_FILES + 1)), Bad::Unsafe),
|
||||
(" ".repeat(MAX_SIZE as usize + 1), Bad::Unsafe),
|
||||
(format!("<html>{file}</html>"), Bad::Form),
|
||||
(format!("<metalink>{file}"), Bad::Form),
|
||||
(format!("<metalink>{file}</metalink"), Bad::Form),
|
||||
("<metalink><file name=\"a\"></metalink>".into(), Bad::Form),
|
||||
(v4("<file name=\"a\"><url>javascript:1</url><url>file:///etc/passwd</url></file>"), 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!("<file name=\"a\">{}</file>", (0..5000).map(|i| format!("<url>http://h{i}/</url>")).collect::<String>()));
|
||||
assert_eq!(parse(many.as_bytes()).unwrap()[0].urls.len(), MAX_URLS);
|
||||
let long = v4(&format!("<file name=\"a\">{url}<description>{}</description></file>", "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 = "<http://m/2,x>; rel=duplicate; pri=2; geo=\"a,b;c\", </m1>; rel=\"duplicate other\"; pri=1, \
|
||||
<f.meta4>; rel=describedby; type=\"application/metalink4+xml\", <https://h/d/f.iso>; rel=duplicate, <gopher://x/>; 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 ["<", "<a", "<a>;", "<a>; rel=\"dup", ",,,", "<a>;;;=;", "é"] {
|
||||
let _ = links(bad);
|
||||
}
|
||||
assert_eq!(of(&[("digest", "SHA-256=x"), ("digest", "nonsense")]).checksum, None);
|
||||
}
|
||||
}
|
||||
133
crates/core/src/mirror.rs
Normal file
133
crates/core/src/mirror.rs
Normal file
|
|
@ -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<Part>, base: Link, source: Source, mut stop: Stop) -> Result<Option<Link>> {
|
||||
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<Range<u64>> {
|
||||
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<u64>]) -> Vec<Part> {
|
||||
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), []);
|
||||
}
|
||||
}
|
||||
|
|
@ -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<String>,
|
||||
/// `sha256:…`.
|
||||
pub checksum: Option<String>,
|
||||
/// Hashes of its pieces, to repair single ones.
|
||||
pub pieces: Option<Arc<Pieces>>,
|
||||
/// What the finished file was found to match: `checksum` as it was then, or `pieces`.
|
||||
pub verified: Option<String>,
|
||||
pub max_parts: Option<u32>,
|
||||
/// Failures in a row before it fails, 0 for never. None for the setting.
|
||||
pub tries: Option<u32>,
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<Checked> {
|
||||
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<Link>)> {
|
||||
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<http::Response>,
|
||||
task: &Task,
|
||||
file: &Arc<File>,
|
||||
whole: &[Range<u64>],
|
||||
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.
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue