From 4f1435e72f8dbfe47f7614276a001e8f5c2bf571 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 05:50:55 -0600 Subject: [PATCH] S008: continue from a new link, matcher and adopting partial files Co-Authored-By: Claude Opus 5.5 --- crates/core/lang/en.json | 15 + crates/core/src/adopt.rs | 339 ++++++++++++++++++++++ crates/core/src/error.rs | 2 +- crates/core/src/http/download.rs | 2 +- crates/core/src/http/fetch.rs | 28 +- crates/core/src/http/mod.rs | 7 +- crates/core/src/http/name.rs | 2 +- crates/core/src/lib.rs | 2 + crates/core/src/manager/actor.rs | 171 ++++++++++- crates/core/src/manager/files.rs | 72 ++++- crates/core/src/manager/mod.rs | 55 +++- crates/core/src/model.rs | 5 + crates/core/src/relink/matching.rs | 336 ++++++++++++++++++++++ crates/core/src/relink/mod.rs | 383 +++++++++++++++++++++++++ crates/core/src/store/003.sql | 1 + crates/core/src/store/mod.rs | 2 +- crates/core/src/store/rows.rs | 8 +- crates/core/tests/relink.rs | 438 +++++++++++++++++++++++++++++ docs/RECOVERY.md | 1 + 19 files changed, 1833 insertions(+), 36 deletions(-) create mode 100644 crates/core/src/adopt.rs create mode 100644 crates/core/src/relink/matching.rs create mode 100644 crates/core/src/relink/mod.rs create mode 100644 crates/core/src/store/003.sql create mode 100644 crates/core/tests/relink.rs diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 3cb7f8f..0238484 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -67,6 +67,19 @@ "log.file_unknown": "File {name}, of unknown size", "log.failed": "Failed: {why}", "log.moved": "Moved to {folder}", + "log.continued": "Continues from {url}", + "log.adopted": "Took over the unfinished file {path}", + "manager.different": "The new link leads to another file, so this download can't continue from it.", + "manager.partial": "Nothing in that file can be used: {why}", + "relink.version": "Same file. The server's version and the bytes compared are the same.", + "relink.samples": "Probably the same file. The bytes compared are the same, but the server doesn't tell versions apart.", + "relink.size": "Different file. The new one has {new} bytes, this one has {old}.", + "relink.bytes": "Different file. Some of its bytes are not the ones already here.", + "relink.other_version": "Different file. The server has a newer version of it.", + "relink.page": "Different file. The link leads to a web page.", + "relink.nothing": "Nothing is here yet, so the download starts with the new link.", + "relink.too_little": "Too little is here to tell whether it is the same file.", + "relink.no_ranges": "The server of the new link can't continue downloads, so it must start over. The unfinished file stays until the new one is complete.", "log.renamed": "Renamed to {name}", "error.dns": "Server not found", @@ -89,6 +102,8 @@ "error.login.why": "{server} wants a user name and password.", "error.forbidden": "Access denied", "error.forbidden.why": "{server} refused to give out the file (status {code}). The link may need the page it came from.", + "error.link": "Waiting for a new link", + "error.link.why": "Start the download again on the page it came from. Medlar continues this one with the new link.", "error.expired": "Link expired", "error.expired.why": "{server} gave out the file before but refuses now (status {code}). A new link for the same file continues the download.", "error.not_found": "File not found", diff --git a/crates/core/src/adopt.rs b/crates/core/src/adopt.rs new file mode 100644 index 0000000..8d0eb5a --- /dev/null +++ b/crates/core/src/adopt.rs @@ -0,0 +1,339 @@ +//! Taking over a file that another program left unfinished. +//! +//! `look` reads what is there, `check` compares it with a link, `Command::Adopt` copies it. The file itself is never touched. +//! Browsers fill a file from the start; aria2 keeps a list of its pieces next to it. Of anything else only the start counts, +//! as far as it stands the comparison with the server. + +use crate::http::{Client, Error, Link, Result, Source, Stop, same_bytes}; +use crate::model::{Part, Task}; +use crate::relink::{Checked, NewLink, Reason, probed, read, runs, samples, total}; +use crate::{disk, http}; +use std::fs::File; +use std::io::{self, ErrorKind, Read}; +use std::ops::Range; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +/// Looked at in one piece for being empty. +const BLOCK: u64 = 4096; +/// Empty stretches the server is asked about. +const DOUBTS: usize = 64; +/// Endings of unfinished files, and where the name comes before them. +const ENDINGS: &[&str] = &[".part", ".crdownload", ".opdownload", ".partial", ".download", disk::ENDING]; +const ARIA2: &str = ".aria2"; +/// Blocks inside aria2's unfinished pieces. +const ARIA2_BLOCK: u64 = 16 * 1024; +/// More than any control file of a sensible download. +const ARIA2_MAX: u64 = 64 << 20; + +#[derive(Debug, Clone, PartialEq)] +pub struct Partial { + pub path: PathBuf, + /// As far as the file's own name tells. + pub name: Option, + /// What seems to be finished. + pub runs: Vec>, + pub total: Option, + /// `runs` come from the other program's own list. + pub listed: bool, +} + +impl Partial { + pub fn bytes(&self) -> u64 { + total(&self.runs) + } +} + +/// An unfinished file and the link it can go on from. `partial.runs` holds only what stood the comparison. +#[derive(Debug, Clone)] +pub struct Found { + pub partial: Partial, + pub checked: Checked, +} + +impl Found { + pub(crate) fn parts(&self) -> Vec { + parts(&self.partial.runs, self.checked.size.unwrap_or(0)) + } +} + +/// Blocks. Takes the file or its list. +pub fn look(path: &Path) -> io::Result { + let text = path.to_string_lossy(); + if let Some(data) = text.strip_suffix(ARIA2) + && path.with_file_name(Path::new(data).file_name().unwrap_or_default()).is_file() + { + return look(Path::new(data)); + } + let meta = path.symlink_metadata()?; + if !meta.is_file() { + return Err(ErrorKind::InvalidInput.into()); + } + let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned(); + // Chrome's, before it knows the name. + let stem = ENDINGS.iter().find_map(|e| name.strip_suffix(e)).unwrap_or(&name); + let known = Some(stem).filter(|s| !s.starts_with("Unconfirmed ")).and_then(http::safe_name); + let start = std::iter::once(0..meta.len()).collect(); + let mut partial = Partial { path: path.into(), name: known, runs: start, total: None, listed: false }; + let mut list = path.as_os_str().to_os_string(); + list.push(ARIA2); + if let Some((runs, total)) = aria2(Path::new(&list)) { + let len = meta.len(); + partial.runs = runs.into_iter().map(|r| r.start.min(len)..r.end.min(len)).collect(); + (partial.total, partial.listed) = (Some(total), true); + } + partial.runs.retain(|r| !r.is_empty()); + Ok(partial) +} + +/// The finished ranges and the size in aria2's control file, as its manual describes it ("Control file (*.aria2) format"). +/// None for anything else, such as a torrent's. +fn aria2(path: &Path) -> Option<(Vec>, u64)> { + let mut file = File::open(path).ok()?; + if file.metadata().ok()?.len() > ARIA2_MAX { + return None; + } + let mut bytes = vec![]; + file.read_to_end(&mut bytes).ok()?; + let mut rest = &bytes[..]; + let mut take = |n: usize| -> Option<&[u8]> { + let (now, later) = rest.split_at_checked(n)?; + rest = later; + Some(now) + }; + let int = |b: &[u8]| b.iter().fold(0u64, |n, b| n << 8 | u64::from(*b)); + let (version, _extension, hash) = (int(take(2)?), take(4)?, int(take(4)?)); + if version != 1 || hash != 0 { + return None; + } + let (piece, total, _upload, field) = (int(take(4)?), int(take(8)?), take(8)?, int(take(4)?)); + if piece == 0 || total == 0 || field != total.div_ceil(piece).div_ceil(8) { + return None; + } + // The first bit is the highest one. + let set = |bits: &[u8], i: u64| bits.get((i / 8) as usize).is_some_and(|b| b & (0x80 >> (i % 8)) != 0); + let bits = take(field as usize)?; + let mut done: Vec> = + (0..total.div_ceil(piece)).filter(|i| set(bits, *i)).map(|i| i * piece..((i + 1) * piece).min(total)).collect(); + for _ in 0..int(take(4)?) { + let (index, len, field) = (int(take(4)?), int(take(4)?), int(take(4)?)); + let start = index.checked_mul(piece).filter(|s| s + len <= total)?; + let bits = take(field as usize)?; + let blocks = (0..len.div_ceil(ARIA2_BLOCK)).filter(|i| set(bits, *i)); + done.extend(blocks.map(|i| start + i * ARIA2_BLOCK..start + ((i + 1) * ARIA2_BLOCK).min(len))); + } + let done: Vec = done.iter().map(|r| Part { start: r.start, end: Some(r.end), done: r.end - r.start }).collect(); + Some((runs(&done), total)) +} + +/// Compares the file with what the link leads to. Reads only. +pub async fn check(client: &Client, partial: Partial, link: NewLink, source: Source, stop: &mut Stop) -> Result { + let task = Task { size: partial.total, name: partial.name.clone().unwrap_or_default(), url: link.url.clone(), ..Task::default() }; + let (checked, opened) = probed(client, &task, link, source, partial.bytes(), stop).await?; + let mut found = Found { partial, checked }; + let Some((server, _body)) = opened else { return Ok(found) }; + let Some(size) = server.version.size.filter(|_| server.ranges) else { + found.checked.reason = Reason::NoRanges; + return Ok(found); + }; + let Some(last) = found.partial.runs.last().map(|r| r.end) else { + found.checked.reason = Reason::Nothing; + return Ok(found); + }; + if last > size { + found.checked.reason = Reason::Size { old: last, new: size }; + return Ok(found); + } + let file = crate::relink::open(&found.partial.path).await?; + let mut eye = Eye { server: &server, file: &file, compared: 0, stop }; + let result = if found.partial.listed { eye.listed(&found.partial.runs).await } else { eye.start(last).await }; + found.checked.compared = eye.compared; + let ok = match result { + Ok(Some(runs)) => { + found.partial.runs = runs; + true + } + Ok(None) => false, + Err(Error::Changed) => { + found.checked.reason = Reason::OtherVersion; + return Ok(found); + } + Err(Error::RangeIgnored) => { + (found.checked.reason, found.checked.ranges) = (Reason::NoRanges, false); + return Ok(found); + } + Err(e) => return Err(e), + }; + found.checked.here = found.partial.bytes(); + found.checked.reason = match ok { + false => Reason::Bytes, + true if found.checked.compared < BLOCK => Reason::TooLittle, + true => Reason::Samples, + }; + Ok(found) +} + +struct Eye<'a> { + server: &'a Link, + file: &'a Arc, + compared: u64, + stop: &'a mut Stop, +} + +impl Eye<'_> { + async fn same(&mut self, range: Range) -> Result { + let known = read(self.file, range.clone()).await?; + self.compared += known.len() as u64; + same_bytes(self.server, &known, range.start, self.stop).await + } + + /// All or nothing. + async fn listed(&mut self, runs: &[Range]) -> Result>>> { + for sample in samples(runs) { + if !self.same(sample).await? { + return Ok(None); + } + } + Ok(Some(runs.to_vec())) + } + + /// How far the start of the file is the server's. The space may have been taken before it was filled. + async fn start(&mut self, len: u64) -> Result>>> { + let first = 0..len.min(BLOCK); + if !self.same(first.clone()).await? { + return Ok(None); + } + let file = self.file.clone(); + let empty = disk::blocking(move || empty(&file, len)).await.map_err(disk::Error::Io)?; + let mut end = len; + for (i, hole) in empty.into_iter().enumerate() { + let ends = [hole.start..hole.start + BLOCK.min(hole.end - hole.start), hole.end.saturating_sub(BLOCK).max(hole.start)..hole.end]; + if i >= DOUBTS || !self.same(ends[0].clone()).await? || !self.same(ends[1].clone()).await? { + end = hole.start; + break; + } + } + // Cut where the first of them differs, back to one that doesn't. + let mut good = first.end.min(end); + let mut looks = samples(std::slice::from_ref(&(0..end))); + looks.sort_by_key(|s| s.start); + for look in looks.into_iter().filter(|l| !l.is_empty()) { + if !self.same(look.clone()).await? { + end = good; + break; + } + good = look.end; + } + Ok((end > 0).then(|| std::iter::once(0..end).collect())) + } +} + +/// Stretches of nothing but zeros, as whole blocks. +fn empty(file: &File, len: u64) -> io::Result>> { + use std::os::unix::fs::FileExt; + let mut buf = vec![0; 1 << 20]; + let (mut at, mut out) = (0, Vec::>::new()); + while at < len { + let n = (len - at).min(buf.len() as u64) as usize; + file.read_exact_at(&mut buf[..n], at)?; + for block in buf[..n].chunks(BLOCK as usize) { + let next = at + block.len() as u64; + if block.iter().all(|b| *b == 0) { + match out.last_mut() { + Some(last) if last.end == at => last.end = next, + _ => out.push(at..next), + } + } + at = next; + } + } + Ok(out) +} + +/// The whole file as parts: each finished range with the gap after it. +fn parts(runs: &[Range], size: u64) -> Vec { + let mut out = vec![]; + if let Some(first) = runs.first().filter(|r| r.start > 0) { + out.push(Part { start: 0, end: Some(first.start), done: 0 }); + } + for (i, r) in runs.iter().enumerate() { + let end = runs.get(i + 1).map_or(size, |next| next.start); + out.push(Part { start: r.start, end: Some(end), done: r.end - r.start }); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 10 pieces of 64 KiB, the last one short; pieces 0, 1 and 9 done, and two blocks of piece 4. + pub fn control(total: u64) -> Vec { + let mut b = vec![0, 1, 0, 0, 0, 0, 0, 0, 0, 0]; + b.extend(65536u32.to_be_bytes()); + b.extend(total.to_be_bytes()); + b.extend(0u64.to_be_bytes()); + b.extend(2u32.to_be_bytes()); + b.extend([0b1100_0000, 0b0100_0000]); + b.extend(1u32.to_be_bytes()); + b.extend(4u32.to_be_bytes()); + b.extend(65536u32.to_be_bytes()); + b.extend(1u32.to_be_bytes()); + b.push(0b1010_0000); + b + } + + #[test] + fn reads_the_list_of_aria2() { + let dir = tempfile::tempdir().unwrap(); + let (file, list) = (dir.path().join("a.zip"), dir.path().join("a.zip.aria2")); + let total = 9 * 65536 + 100; + std::fs::write(&file, vec![1; total as usize]).unwrap(); + std::fs::write(&list, control(total)).unwrap(); + let found = look(&list).unwrap(); + assert_eq!(found, look(&file).unwrap()); + let k = 16384; + assert_eq!(found.runs, [0..8 * k, 16 * k..17 * k, 18 * k..19 * k, 36 * k..36 * k + 100]); + assert_eq!((found.total, found.listed, found.name.as_deref()), (Some(total), true, Some("a.zip"))); + let parts = parts(&found.runs, total); + assert_eq!(parts.first(), Some(&Part { start: 0, end: Some(16 * k), done: 8 * k })); + assert!(parts.windows(2).all(|w| w[0].end == Some(w[1].start)) && parts.last().unwrap().end == Some(total)); + // Broken ones count for nothing. + for cut in 0..control(total).len() { + std::fs::write(&list, &control(total)[..cut]).unwrap(); + assert!(!look(&file).unwrap().listed, "{cut}"); + } + for i in 0..control(total).len() { + let mut bad = control(total); + bad[i] ^= 0xff; + std::fs::write(&list, bad).unwrap(); + let found = look(&file).unwrap(); + assert!(found.runs.iter().all(|r| r.end <= total)); + } + } + + #[test] + fn names_of_unfinished_files() { + let dir = tempfile::tempdir().unwrap(); + for (file, name) in [ + ("a.zip.part", Some("a.zip")), + ("b.iso.crdownload", Some("b.iso")), + ("Unconfirmed 1234.crdownload", None), + ("c.tar.gz", Some("c.tar.gz")), + ("d.bin.medlar", Some("d.bin")), + ] { + let path = dir.path().join(file); + std::fs::write(&path, "xy").unwrap(); + let found = look(&path).unwrap(); + assert_eq!((found.name.as_deref(), &found.runs[..]), (name, std::slice::from_ref(&(0..2))), "{file}"); + } + assert!(look(dir.path()).is_err() && look(&dir.path().join("none")).is_err()); + } + + #[test] + fn parts_begin_with_the_gap() { + let p = |start, end, done| Part { start, end: Some(end), done }; + assert_eq!(parts(&[5..7, 9..10], 12), [p(0, 5, 0), p(5, 9, 2), p(9, 12, 1)]); + assert_eq!(parts(std::slice::from_ref(&(0..4)), 4), [p(0, 4, 4)]); + } +} diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index f3e089e..da6deb9 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -95,7 +95,7 @@ impl ErrorKind { ReadOnly | FolderGone | DriveGone | Denied => (Blocked, Retry::Disk, Fix::ChangeFolder), FileGone => (Blocked, Retry::Disk, Fix::Restart), Login => (Blocked, Retry::Never, Fix::SignIn), - Forbidden | Expired | WrongContent => (Blocked, Retry::Never, Fix::NewLink), + Forbidden | Expired | WrongContent | Link => (Blocked, Retry::Never, Fix::NewLink), NotFound | Rejected | BadLink => (Blocked, Retry::Never, Fix::EditLink), Changed | NoResume => (Blocked, Retry::Never, Fix::Choose), Killed => (Passing, Retry::Never, Fix::Resume), diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index bc11a47..cdbce82 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -121,7 +121,7 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt } /// The server sent a web page, and the task is for something else. -fn is_page(task: &Task, source: &Source, probe: &Probe) -> bool { +pub(crate) fn is_page(task: &Task, source: &Source, probe: &Probe) -> bool { let mime = probe.mime.as_deref(); let names = [Some(task.name.clone()).filter(|n| !n.is_empty()), name::from_url(&source.url)]; let was_page = task.mime.as_deref().is_some_and(|m| page(Some(m))); diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index 306749f..32a01eb 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -163,15 +163,31 @@ async fn whole(link: &Link, part: &LivePart, body: Option, stop: &mut /// Compares `len` finished bytes at `at` with the server's. pub async fn compare(link: &Link, file: &PartialFile, at: u64, len: u64, stop: &mut Stop) -> Result<()> { let known = file.read_at(len as usize, at).await?; - let mut response = send_range(link, at, Some(at + len), stop).await?; - let mut seen = vec![]; - while seen.len() < known.len() { + if same_bytes(link, &known, at, stop).await? { Ok(()) } else { Err(Error::Changed) } +} + +/// Whether the server has `known` at `at`. +pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> Result { + let len = known.len() as u64; + same_body(send_range(link, at, Some(at + len), stop).await?, known, stop).await +} + +/// Whether the body begins with `known`. +pub(crate) async fn same_body(mut response: Response, known: &[u8], stop: &mut Stop) -> Result { + let mut rest = known; + while !rest.is_empty() { let chunk = tokio::select! { _ = stopped(stop) => return Err(Error::Stopped), chunk = response.chunk() => chunk?, }; - let Some(chunk) = chunk else { return Err(Error::Cut { got: seen.len() as u64, expected: Some(len) }) }; - seen.extend_from_slice(&chunk); + let Some(chunk) = chunk else { + return Err(Error::Cut { got: (known.len() - rest.len()) as u64, expected: Some(known.len() as u64) }); + }; + let (now, later) = rest.split_at(chunk.len().min(rest.len())); + if !chunk.starts_with(now) { + return Ok(false); + } + rest = later; } - if seen == known { Ok(()) } else { Err(Error::Changed) } + Ok(true) } diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 9c81542..885ba88 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -8,14 +8,17 @@ mod parts; mod probe; pub use download::{Options, Shared, download}; -pub use fetch::{Link, OVERLAP, compare, fetch}; +pub(crate) use download::is_page; +pub(crate) use fetch::same_body; +pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes}; pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot}; pub use name::safe as safe_name; pub use probe::{Probe, probe}; use crate::{disk, store}; use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; -use reqwest::{Certificate, Client, Response, StatusCode, redirect}; +pub(crate) use reqwest::{Client, Response}; +use reqwest::{Certificate, StatusCode, redirect}; use std::sync::Once; use std::time::Duration; use tokio::sync::watch; diff --git a/crates/core/src/http/name.rs b/crates/core/src/http/name.rs index ae90da5..c8ef1aa 100644 --- a/crates/core/src/http/name.rs +++ b/crates/core/src/http/name.rs @@ -97,7 +97,7 @@ fn extension_of(mime: &str) -> Option<&'static str> { } /// The extension stands for a kind of file that Medlar knows. -pub(super) fn is_file_type(ext: &str) -> bool { +pub(crate) fn is_file_type(ext: &str) -> bool { let ext = ext.to_lowercase(); let more = ["appimage", "bin", "dmg", "exe", "img", "jar", "msi", "torrent"]; TYPES.iter().any(|(_, e)| *e == ext) || more.contains(&ext.as_str()) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c379dd1..7c55fe4 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,6 +1,7 @@ //! Medlar's engine, limits, queues, store and settings. No UI code. pub mod adapt; +pub mod adopt; pub mod disk; pub mod error; pub mod events; @@ -14,6 +15,7 @@ pub mod part; pub mod paths; pub mod recover; pub mod redact; +pub mod relink; pub mod segment; pub mod settings; pub mod snapshot; diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 7dd6c96..dfdaf06 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -6,6 +6,7 @@ use super::bin::Binned; use super::pick::{Candidate, pick}; use super::{Answer, Command, Config, Error, Files, Msg, Result, files}; +use crate::adopt::Found; use crate::error::{Failure, Place, Retry}; use crate::events::Event; use crate::http::{self, Monitor, PartState, PartView, Source, download, safe_name}; @@ -13,14 +14,15 @@ use crate::model::*; use crate::net_state::{self, Network}; use crate::recover::sleep::{self, Sleep}; use crate::recover::{Breakers, DiskNeed, Gate}; +use crate::relink::{self, Checked, NewLink, Verdict}; use crate::settings::Limits; use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals}; use crate::speed::{History, Meter}; use crate::store::{self, Store}; -use crate::{host, redact, strings, tr}; +use crate::{adopt, disk, host, redact, strings, tr}; use arc_swap::ArcSwap; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, mpsc}; use std::time::{Duration, Instant}; @@ -46,6 +48,11 @@ pub enum Why { pub enum Worked { Plain, Binned(Option), + Continued, + /// Out of the way of this one. + Aside(Box), + /// With the state it should be in. Nothing is left of it if it failed. + Adopted(Result), } enum Work { @@ -73,6 +80,7 @@ enum Hold { /// For a look at its folder; None while one is under way. Disk(Option), Wake, + Link, } /// What waits for a task's work to end. @@ -282,10 +290,11 @@ impl Actor { actor.store.delete_task(task.id)?; continue; } + let awaits = task.state == State::Waiting && task.error.as_ref().is_some_and(|e| e.kind == Some(ErrorKind::Link)); // The program ended in the middle of it. let cut = matches!(task.state, State::Running | State::Checking | State::Finishing); // It waited for a retry, the network or a disk: that is found out anew. - if cut || (task.state == State::Waiting && task.error.as_ref().is_some_and(|e| e.kind.is_some())) { + if cut || (task.state == State::Waiting && !awaits && task.error.as_ref().is_some_and(|e| e.kind.is_some())) { actor.store.set_state(task.id, State::Queued, None)?; (task.state, task.error) = (State::Queued, None); if !actor.config.recovery.auto_resume { @@ -301,6 +310,10 @@ impl Actor { if unfinished { entry.took(Some(actor.store.parts(id)?)); } + if awaits { + entry.hold = Some(Hold::Link); + actor.held.insert(id); + } actor.entries.insert(id, entry); actor.dirty.insert(id); } @@ -356,6 +369,8 @@ impl Actor { fn take(&mut self, msg: Msg) { match msg { 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::Limits(limits) => self.set_limits(limits), Msg::OnChange(call) => self.on_change.push(call), Msg::Ended(id, result) => self.ended(id, result), @@ -433,9 +448,14 @@ impl Actor { fn command(&mut self, command: Command, answer: Option) { let Some(id) = command.id() else { - let Command::Add(task) = command else { unreachable!("only it has no id") }; - let result = self.add(*task); - return self.answer(answer, result); + return match command { + Command::Add(task) => { + let result = self.add(*task); + self.answer(answer, result); + } + Command::Adopt { task, found } => self.adopt(*task, *found, answer), + _ => unreachable!("they have an id"), + }; }; let Some(e) = self.entries.get(&id) else { let removed = matches!(command, Command::Remove { .. }); @@ -443,7 +463,7 @@ impl Actor { }; match command { Command::KeepBoth(_) if !e.removed() => { - let again = Task { state: State::Queued, size: None, etag: None, last_modified: None, mime: None, position: 0.0, ..(*e.task).clone() }; + let again = Task { state: State::Queued, size: None, etag: None, last_modified: None, mime: None, position: 0.0, replaces: None, ..(*e.task).clone() }; let result = self.add(again); self.answer(answer, result); } @@ -465,6 +485,7 @@ impl Actor { } match command { Command::Restore(_) => (!e.removed()).then_some(Ok(())), + Command::Continue { checked, .. } if checked.verdict() == Verdict::Different => Some(Err(Error::Different)), _ if e.removed() => Some(Err(store::Error::NotFound.into())), Command::Move { folder, .. } if !folder.is_absolute() => Some(Err(Error::Folder)), Command::Move { folder, .. } => (*folder == e.task.folder).then_some(Ok(())), @@ -479,7 +500,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(_)); + let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | Restore(_) | Continue { .. }); !e.todo.is_empty() || match e.work { None => false, @@ -574,8 +595,10 @@ impl Actor { None => result = Err(Error::Name), }, Command::Edit { edit, .. } => result = self.change(id, edit), + Command::AwaitLink(_) => result = self.await_link(id), + Command::Continue { checked, .. } => return self.go_on(id, *checked, answer), Command::Remove { .. } | Command::KeepBoth(_) => {} - Command::Add(_) => unreachable!("has no id"), + Command::Add(_) | Command::Adopt { .. } => unreachable!("have no id"), } self.answer(answer, result.map(|()| id)); } @@ -603,6 +626,111 @@ impl Actor { Ok(id) } + // New links. + + /// Off this thread, until it is done or nobody waits for it any more. + fn look(&self, mut answer: oneshot::Sender>, server: Arc, work: impl Future> + Send + 'static) { + self.runtime().spawn(async move { + let result = tokio::select! { + _ = answer.closed() => return, + result = work => result, + }; + let place = Place { server: &server, folder: Path::new("/"), begun: false }; + let _ = answer.send(result.map_err(|e| Error::Link(Box::new(Failure::of(&e, place))))); + }); + } + + fn check(&self, id: TaskId, link: NewLink, answer: oneshot::Sender>) { + let Some(e) = self.entries.get(&id).filter(|e| !e.removed()) else { + let _ = answer.send(Err(store::Error::NotFound.into())); + return; + }; + let (task, shared) = (e.task.clone(), self.config.shared.clone()); + self.look(answer, host_of(&link.url), async move { + let (_keep, mut stop) = watch::channel(false); + let store = shared.store.clone(); + let parts = disk::blocking(move || store.parts(id)).await?; + let source = Source::new(&link.url)?.with_headers(&link.headers); + relink::check(&shared.client, &task, &parts, link, source, &mut stop).await + }); + } + + fn check_partial(&self, path: PathBuf, link: NewLink, answer: oneshot::Sender>) { + let shared = self.config.shared.clone(); + self.look(answer, host_of(&link.url), async move { + let (_keep, mut stop) = watch::channel(false); + let partial = disk::blocking(move || adopt::look(&path)).await.map_err(disk::Error::Io)?; + let source = Source::new(&link.url)?.with_headers(&link.headers); + adopt::check(&shared.client, partial, link, source, &mut stop).await + }); + } + + fn await_link(&mut self, id: TaskId) -> Result<()> { + if matches!(self.entries[&id].task.state, State::Checking | State::Finishing | State::Done | State::Gone) { + return Ok(()); + } + self.hold(id)?; + self.held.remove(&id); + let error = Failure::new(ErrorKind::Link, self.place(id)).error(); + self.set_state(id, State::Waiting, Some(error))?; + self.held.insert(id); + self.entry(id).hold = Some(Hold::Link); + Ok(()) + } + + fn go_on(&mut self, id: TaskId, checked: Checked, answer: Option) { + let e = &self.entries[&id]; + if matches!(e.task.state, State::Checking | State::Finishing | State::Done | State::Gone) { + return self.answer(answer, Ok(id)); + } + if checked.ranges || e.downloaded == 0 { + return self.work(id, answer, move |store, _| files::relink(store, id, checked).map(|()| Worked::Continued)); + } + let mut again = (*e.task).clone(); + again.replaces = Some(id); + (again.state, again.position) = (State::Queued, e.task.position); + checked.put_in(&mut again); + (again.size, again.etag, again.last_modified, again.mime) = (None, None, None, None); + if let Err(e) = self.hold(id) { + return self.answer(answer, Err(e)); + } + self.work(id, answer, move |store, cancel| files::step_aside(store, id, cancel).map(|()| Worked::Aside(Box::new(again)))); + } + + fn adopt(&mut self, mut task: Task, found: Found, answer: Option) { + let checked = &found.checked; + let refused = match checked.verdict() { + Verdict::Different => Some(Error::Different), + _ if !checked.ranges || found.partial.runs.is_empty() => Some(Error::Partial(checked.text())), + _ => None, + }; + if let Some(refused) = refused { + return self.answer(answer, Err(refused)); + } + // It must not begin before the file is there. + let wanted = std::mem::replace(&mut task.state, State::Paused); + checked.link.put_in(&mut task); + match self.add(task) { + Ok(id) => { + let path = redact::text(&found.partial.path.display().to_string()); + self.entry(id).log(&tr!("log.adopted", path = path)); + self.work(id, answer, move |store, cancel| Ok(Worked::Adopted(files::adopt(store, id, &found, cancel).map(|()| wanted)))); + } + Err(e) => self.answer(answer, Err(e)), + } + } + + /// The new one is whole: those it started over for may go. + fn replace(&mut self, id: TaskId) { + let mut old = self.entries[&id].task.replaces; + while let Some((id, e)) = old.and_then(|id| Some((id, self.entries.get(&id)?))) { + old = e.task.replaces; + if !e.removed() && !matches!(e.task.state, State::Done | State::Gone) { + self.command(Command::Remove { id, files: Files::Bin }, None); + } + } + } + fn resume(&mut self, id: TaskId) -> Result<()> { match self.entries[&id].task.state { State::Paused | State::Waiting | State::Failed => { @@ -881,6 +1009,7 @@ impl Actor { e.counters.finished += 1; (e.forced, e.fails) = (0, 0); e.took(None); + self.replace(id); } fn failed(&mut self, id: TaskId, why: &Why) { @@ -1062,10 +1191,30 @@ impl Actor { let Some(Work::Files { answer, .. }) = self.entry(id).work.take() else { return }; let was = self.entries[&id].task.clone(); let result = result.and_then(|worked| self.reload(id, true).map(|()| worked)); + let mut answers = id; + let result = match result { + Ok(Worked::Continued) => { + let e = self.entry(id); + let url = e.task.url.clone(); + e.log(&tr!("log.continued", url = url)); + self.resume(id).map(|()| Worked::Plain) + } + Ok(Worked::Aside(task)) => self.add(*task).map(|new| { + answers = new; + Worked::Plain + }), + Ok(Worked::Adopted(Ok(State::Queued))) => self.resume(id).map(|()| Worked::Plain), + Ok(Worked::Adopted(Ok(_))) => Ok(Worked::Plain), + Ok(Worked::Adopted(Err(e))) => { + self.remove(id, Files::Keep, None); + Err(e) + } + other => other, + }; let e = self.entry(id); match &result { Ok(Worked::Binned(binned)) => e.binned = binned.clone(), - Ok(Worked::Plain) => { + Ok(_) => { if was.folder != e.task.folder { e.log(&tr!("log.moved", folder = e.task.folder.display())); } @@ -1080,7 +1229,7 @@ impl Actor { self.removed.remove(&id); self.happened.push(Event::Restored(id)); } - self.answer(answer, result.map(|_| id)); + self.answer(answer, result.map(|_| answers)); self.next(id); } diff --git a/crates/core/src/manager/files.rs b/crates/core/src/manager/files.rs index e960064..b86c9d1 100644 --- a/crates/core/src/manager/files.rs +++ b/crates/core/src/manager/files.rs @@ -2,12 +2,15 @@ use super::bin::{Bin, Binned}; use super::{Error, Result}; +use crate::adopt::Found; use crate::disk::{self, PartialFile, exists, partial_path, rename_new, variants}; +use crate::http::safe_name; use crate::model::{Part, State, Task, TaskId}; +use crate::relink::Checked; use crate::store::Store; use std::collections::HashSet; use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Write}; +use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -184,6 +187,73 @@ pub fn discard(store: &Store, id: TaskId) -> Result<()> { Ok(()) } +/// Copies the finished ranges of another program's file. Nothing is left behind when it fails. +pub fn adopt(store: &Store, id: TaskId, found: &Found, cancel: &AtomicBool) -> Result<()> { + let task = store.task(id)?; + let disk_error = |e| match e { + disk::Error::Io(e) => Error::File(e), + disk::Error::NoSpace { .. } => Error::File(io::ErrorKind::StorageFull.into()), + disk::Error::Busy => Error::File(io::ErrorKind::ResourceBusy.into()), + }; + let wanted = safe_name(&task.name).unwrap_or(found.checked.name.clone()); + let (file, checked) = { + let _names = disk::names(); + let (file, name) = PartialFile::create(&task.folder, &wanted, &store.used_names(&task.folder, id)?).map_err(disk_error)?; + let checked = found.checked.clone(); + store.edit_task(id, move |t| t.name = name)?; + (file, checked) + }; + let work = || -> Result<()> { + if let Some(size) = checked.size { + file.reserve(size).map_err(disk_error)?; + } + let mut from = File::open(&found.partial.path).map_err(Error::File)?; + let mut to = OpenOptions::new().write(true).open(file.path()).map_err(Error::File)?; + for run in &found.partial.runs { + from.seek(SeekFrom::Start(run.start)).map_err(Error::File)?; + to.seek(SeekFrom::Start(run.start)).map_err(Error::File)?; + let mut left = run.end - run.start; + while left > 0 { + if cancel.load(Ordering::Relaxed) { + return Err(Error::File(io::ErrorKind::Interrupted.into())); + } + let n = left.min(64 << 20); + // Shorter than it was. + if io::copy(&mut (&from).take(n), &mut to).map_err(Error::File)? != n { + return Err(Error::File(io::ErrorKind::UnexpectedEof.into())); + } + left -= n; + } + } + file.sync().map_err(disk_error)?; + // The data goes first, so that the record never claims more than there is. + store.save_parts(id, found.parts())?; + store.edit_task(id, move |t| checked.put_in(t))?; + Ok(()) + }; + work().inspect_err(|_| { + let _ = fs::remove_file(file.path()); + let _ = store.save_parts(id, vec![]); + }) +} + +/// Takes a new link. What is here stays. +pub fn relink(store: &Store, id: TaskId, checked: Checked) -> Result<()> { + // Nothing to keep; its parts may not fit the new size. + if store.task(id)?.downloaded == 0 { + discard(store, id)?; + } + store.edit_task(id, move |t| checked.put_in(t))?; + Ok(()) +} + +/// Leaves the task's name to another. +pub fn step_aside(store: &Store, id: TaskId, cancel: &AtomicBool) -> Result<()> { + let name = store.task(id)?.name; + let other = variants(&name).nth(1).expect("variants never end"); + relocate(store, id, None, Some(&other), cancel) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index 2ce24c3..217127b 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -9,12 +9,15 @@ mod pick; pub use bin::Bin; +use crate::adopt::Found; +use crate::error::Failure; use crate::events::Event; use crate::http::{Options, Shared}; use crate::model::{Task, TaskId}; use crate::net_state::Network; use crate::recover::Recovery; use crate::recover::sleep::Sleep; +use crate::relink::{Checked, NewLink}; use crate::settings::Limits; use crate::snapshot::Snapshot; use crate::{store, tr}; @@ -39,6 +42,12 @@ pub enum Error { Folder, File(io::Error), Bin(io::Error), + /// The link leads to another file. + Different, + /// Nothing can be taken over; `Checked::text` says why. + Partial(String), + /// The link could not be checked. + Link(Box), /// Medlar is closing. Closed, } @@ -59,6 +68,9 @@ impl fmt::Display for Error { Error::Folder => tr!("manager.folder"), Error::File(e) => tr!("manager.file", why = e), Error::Bin(e) => tr!("manager.bin", why = e), + Error::Different => tr!("manager.different"), + Error::Partial(why) => tr!("manager.partial", why = why), + Error::Link(failure) => failure.text.clone(), Error::Closed => tr!("manager.closed"), }) } @@ -101,15 +113,24 @@ pub enum Command { /// 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 }, + /// Waits for a link from the source page; `relink::find` puts it first. Pause and Resume end the wait. + AwaitLink(TaskId), + /// Goes on from a link that `Manager::check` looked at, with that link's headers and login instead of the old ones. Refused + /// when it is another file. If the server can't continue, a new download starts over and answers; the old one keeps what it + /// has and is binned when the new one is whole. + Continue { id: TaskId, checked: Box }, + /// Adds a download that goes on from a file `Manager::check_partial` looked at. The link and what the server said come from + /// there, the rest from the task. + Adopt { task: Box, found: Box }, } impl Command { fn id(&self) -> Option { use Command::*; match self { - Add(_) => None, - Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) | KeepBoth(id) => Some(*id), - Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } => Some(*id), + Add(_) | Adopt { .. } => None, + Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id), + Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id), } } } @@ -117,11 +138,11 @@ impl Command { /// The answer to a command, when the snapshot shows what it did. Needn't be looked at. #[derive(Debug)] #[must_use = "errors come only this way; drop it to ignore them"] -pub struct Reply(oneshot::Receiver>); +pub struct Reply(oneshot::Receiver>); -impl Reply { +impl Reply { /// None while there is no answer. Never waits; ask no more after the answer. - pub fn try_get(&mut self) -> Option> { + pub fn try_get(&mut self) -> Option> { match self.0.try_recv() { Ok(result) => Some(result), Err(oneshot::error::TryRecvError::Empty) => None, @@ -130,13 +151,13 @@ impl Reply { } /// Not for the thread of the window, nor inside async code. - pub fn wait(self) -> Result { + pub fn wait(self) -> Result { self.0.blocking_recv().unwrap_or(Err(Error::Closed)) } } -impl Future for Reply { - type Output = Result; +impl Future for Reply { + type Output = Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { Poll::Ready(ready!(Pin::new(&mut self.0).poll(cx)).unwrap_or(Err(Error::Closed))) @@ -173,6 +194,8 @@ type Answer = oneshot::Sender>; enum Msg { Command(Command, Option), + Check(TaskId, NewLink, oneshot::Sender>), + CheckPartial(PathBuf, NewLink, oneshot::Sender>), Limits(Limits), OnChange(Box), /// A download ended. @@ -214,6 +237,20 @@ impl Manager { Reply(reply) } + /// Compares what a download has with what a new link leads to; nothing changes. Dropping the reply ends it. + pub fn check(&self, id: TaskId, link: NewLink) -> Reply { + let (answer, reply) = oneshot::channel(); + let _ = self.to.send(Msg::Check(id, link, answer)); + Reply(reply) + } + + /// The same for an unfinished file of another program. + pub fn check_partial(&self, path: PathBuf, link: NewLink) -> Reply { + let (answer, reply) = oneshot::channel(); + let _ = self.to.send(Msg::CheckPartial(path, link, answer)); + Reply(reply) + } + /// Takes effect at once, also on running downloads. 0 is no limit. The speed is not its business. pub fn set_limits(&self, limits: Limits) { let _ = self.to.send(Msg::Limits(limits)); diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index f163b8c..e109a72 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -126,6 +126,8 @@ named_enum!( List = "list", Sleep = "sleep", Killed = "killed", + /// Waits for a link from its page. + Link = "link", Crashed = "crashed", } ); @@ -174,6 +176,8 @@ pub struct Task { /// Keyring item with the cookies and login. pub secret: Option, pub after: Option, + /// The unfinished one this starts over. Removed when this is done. + pub replaces: Option, pub start_at: Option