From d4c492095086bb5c868e2cb82f8386dfff19db79 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 12:34:59 -0600 Subject: [PATCH 01/70] S000: branch of the new orchestrator Co-Authored-By: Claude Opus 5.5 --- docs/DECISIONS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index a9410b9..8f03492 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -51,3 +51,4 @@ - D-049 — 2026-11-25 — FTP and SFTP answer like a HTTP server (`transport`): `Source` gives a made-up reply with 206, Content-Range and Last-Modified, so parts, resume, limits and relinking are the same. FTP is Medlar's own, not suppaftp: that one gives TLS errors as text, can't go through a proxy with TLS from the start and brings a date library. Passive and binary only; the address in a PASV answer is ignored. `ftps` is TLS from the start, `ftpes` AUTH TLS; no silent fall back to plain. A path counts from the login's folder, `%2F` in front from the root. A refused login that worked a moment ago means too many connections. - D-050 — 2026-11-25 — One listing type for all (`listing::Entry`), with the link made of the raw bytes of the name; entries whose names could leave their folder are dropped. SFTP is russh with ring (no aws-lc-rs) and russh-sftp: a connection per part, 2 to 64 reads of 32 KiB under way, more only when they come too late. - D-051 — 2026-11-25 — Keys of SSH servers are in Medlar's own file (`Paths::known_hosts`), never in `~/.ssh`. An unknown or changed key stops the download before any login is sent; a key of another kind than the known one counts as changed. Only `host_keys.accept` adds one, and it replaces the server's old ones. With a key file, the login's password is its passphrase and is not sent to the server if it unlocked the key. +- D-052 — 2026-11-25 — From here on the plans run on the branch `claude/orchestrate-0ad55c` (a new worktree); the rest of D-014 holds: sessions push only the branch, the orchestrator fast-forwards `main` after each validated category. — New orchestrator session. — all From d26c59ee2655e55f4829eb9c0cabb8520579bd62 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 13:18:25 -0600 Subject: [PATCH 02/70] S012: HLS, DASH, RTSP and MMS Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 + crates/core/Cargo.toml | 5 +- crates/core/lang/en.json | 10 + crates/core/src/error.rs | 3 + crates/core/src/http/mod.rs | 9 +- crates/core/src/http/monitor.rs | 16 +- crates/core/src/http/piece.rs | 74 +++ crates/core/src/lib.rs | 1 + crates/core/src/manager/actor.rs | 31 ++ crates/core/src/manager/mod.rs | 4 +- crates/core/src/model.rs | 6 + crates/core/src/stream/dash.rs | 479 ++++++++++++++++++++ crates/core/src/stream/fetch.rs | 388 ++++++++++++++++ crates/core/src/stream/ffmpeg.rs | 306 +++++++++++++ crates/core/src/stream/hls.rs | 304 +++++++++++++ crates/core/src/stream/join.rs | 163 +++++++ crates/core/src/stream/list.rs | 156 +++++++ crates/core/src/stream/mod.rs | 507 +++++++++++++++++++++ crates/core/src/stream/record.rs | 223 +++++++++ crates/core/src/stream/tape.rs | 174 +++++++ crates/core/tests/stream.rs | 750 +++++++++++++++++++++++++++++++ docs/RECOVERY.md | 3 + 22 files changed, 3608 insertions(+), 7 deletions(-) create mode 100644 crates/core/src/http/piece.rs create mode 100644 crates/core/src/stream/dash.rs create mode 100644 crates/core/src/stream/fetch.rs create mode 100644 crates/core/src/stream/ffmpeg.rs create mode 100644 crates/core/src/stream/hls.rs create mode 100644 crates/core/src/stream/join.rs create mode 100644 crates/core/src/stream/list.rs create mode 100644 crates/core/src/stream/mod.rs create mode 100644 crates/core/src/stream/record.rs create mode 100644 crates/core/src/stream/tape.rs create mode 100644 crates/core/tests/stream.rs diff --git a/Cargo.lock b/Cargo.lock index d43965f..e62fe95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2768,9 +2768,11 @@ dependencies = [ name = "medlar-core" version = "0.1.0" dependencies = [ + "aes", "arc-swap", "base64 0.23.1", "bytes", + "cbc", "chrono", "dirs", "fastrand", @@ -2785,6 +2787,7 @@ dependencies = [ "rcgen", "regex", "reqwest", + "roxmltree 0.21.2", "rusqlite", "russh", "russh-sftp", diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 99fdc61..d3deb28 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -6,9 +6,11 @@ license.workspace = true description = "Medlar's engine, store and settings" [dependencies] +aes = "0.9" arc-swap = "1.9.5" base64 = "0.23" bytes = "1.10" +cbc = "0.2" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } dirs = "6" futures-lite = "2.6" @@ -19,6 +21,7 @@ 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"] } +roxmltree = "0.21" # Pinned: D-017. reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider", "socks"] } # ring, as everywhere else: aws-lc-rs would be a second one. @@ -32,7 +35,7 @@ rustls-platform-verifier = "0.7.1" serde.workspace = true serde_json.workspace = true sha2 = "0.11.1" -tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util"] } +tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "process"] } tokio-rustls = { version = "0.26", default-features = false } tower-service = "0.3" url = "2" diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index ac5627c..5a652cc 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -270,6 +270,16 @@ "error.wrong_content.why": "{server} sent a web page instead of the file. The link may be old, or need a login.", "error.no_resume": "Can't be continued", "error.no_resume.why": "{server} no longer sends the rest of a file, only all of it. What is here was kept.", + "error.tool": "A program is missing", + "error.tool.why": "A program this download needs is not on this computer. Install it, then try again.", + "error.tool.ffmpeg": "Streams need the program ffmpeg, which is not on this computer. Install it, then try again.", + "error.drm": "Copy protected", + "error.drm.why": "{server} sends this stream with copy protection. Medlar does not get around it, so nothing was downloaded.", + "error.media": "Stream can't be saved", + "error.media.why": "ffmpeg could not make a file of what {server} sent.", + "error.media.choice": "{server} no longer offers the chosen quality or language.", + "error.media.empty": "{server} sent no sound or picture.", + "error.proxy.stream": "The stream from {server} can't go through the proxy, and Medlar does not connect without it.", "error.disk_full": "Disk is full", "error.disk_full.why": "There is not enough space in {folder}. The download goes on when there is.", "error.read_only": "Disk is read-only", diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index ed066d8..7017aee 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -102,6 +102,9 @@ impl ErrorKind { Tls => (Serious, Retry::Never, Fix::TryAgain), Disk => (Serious, later(30, 600), Fix::ChangeFolder), List => (Serious, later(30, 600), Fix::TryAgain), + Drm => (Blocked, Retry::Never, Fix::EditLink), + Tool => (Blocked, Retry::Never, Fix::TryAgain), + Media => (Serious, Retry::Never, Fix::TryAgain), Crashed => (Serious, Retry::Never, Fix::TryAgain), } } diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 953c736..272180c 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -5,6 +5,7 @@ mod fetch; mod monitor; pub(crate) mod name; mod parts; +mod piece; mod probe; pub use download::{Options, Shared, download}; @@ -13,6 +14,7 @@ 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(crate) use piece::piece; pub use probe::{Probe, probe}; use crate::model::ErrorKind; @@ -20,7 +22,7 @@ use crate::sftp::HostKeys; use crate::site::{Access, same_site}; use crate::tls::Trust; use crate::transport::{Remote, Way}; -use crate::{disk, redact, store}; +use crate::{disk, redact, store, stream}; use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; pub(crate) use reqwest::Response; use reqwest::{RequestBuilder, StatusCode, redirect}; @@ -209,7 +211,7 @@ impl Source { pub fn new(url: &str) -> Result { let url = Url::parse(url).map_err(|_| Error::Link)?; let remote = Remote::of(&url).map(Arc::new); - if !(remote.is_some() || matches!(url.scheme(), "http" | "https")) || url.host_str().is_none_or(str::is_empty) { + if !(remote.is_some() || matches!(url.scheme(), "http" | "https") || stream::recorded(&url)) || url.host_str().is_none_or(str::is_empty) { return Err(Error::Link); } Ok(Source { url, headers: HeaderMap::new(), access: None, remote }) @@ -270,6 +272,9 @@ impl Source { if let Some(remote) = &self.remote { return remote.respond(client, self, range).await; } + if stream::recorded(&self.url) { + return Err(Error::Link); + } let mut here = self.clone(); for _ in 0..=HOPS { let request = |client: &Client, headers: &HeaderMap| -> RequestBuilder { diff --git a/crates/core/src/http/monitor.rs b/crates/core/src/http/monitor.rs index 8c670b1..7e32173 100644 --- a/crates/core/src/http/monitor.rs +++ b/crates/core/src/http/monitor.rs @@ -66,6 +66,7 @@ pub struct Monitor { events: broadcast::Sender, state: Mutex<(Snapshot, Vec>)>, flow: Arc, + finish: watch::Sender, } impl Monitor { @@ -75,7 +76,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) } + Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow), finish: watch::Sender::new(false) } } /// The limits that count for it. @@ -88,6 +89,15 @@ impl Monitor { self.cap.send_replace(cap); } + /// What has no end of its own ends here, and is made a whole file of. + pub fn finish(&self) { + self.finish.send_replace(true); + } + + pub(crate) fn finishing(&self) -> watch::Receiver { + self.finish.subscribe() + } + pub fn subscribe(&self) -> broadcast::Receiver { self.events.subscribe() } @@ -103,12 +113,12 @@ impl Monitor { shot } - pub(super) fn cap(&self) -> watch::Receiver { + pub(crate) fn cap(&self) -> watch::Receiver { self.cap.subscribe() } /// The snapshot first: whoever sees the events finds them in it. - pub(super) fn publish(&self, shot: Snapshot, parts: Vec>, events: impl Iterator) { + pub(crate) fn publish(&self, shot: Snapshot, parts: Vec>, events: impl Iterator) { *self.state.lock().unwrap() = (shot, parts); for e in events { // Nobody has to listen. diff --git a/crates/core/src/http/piece.rs b/crates/core/src/http/piece.rs new file mode 100644 index 0000000..a935081 --- /dev/null +++ b/crates/core/src/http/piece.rs @@ -0,0 +1,74 @@ +//! Something small, whole and in memory: lists, keys and pieces of streams. + +use super::*; +use crate::limit::Flow; +use std::sync::atomic::{AtomicU64, Ordering}; + +#[derive(Debug)] +pub(crate) struct Piece { + /// Where the redirects ended. + pub url: Url, + pub mime: Option, + pub body: Vec, +} + +/// Fails when it is larger than `most`. `range` is the first byte and the one after the last. Adds to `received` what comes. +pub(crate) async fn piece( + client: &Client, + source: &Source, + range: Option<(u64, u64)>, + most: u64, + flow: &Flow, + received: &AtomicU64, + stop: &mut Stop, +) -> Result { + let asked = range.map(|(first, end)| format!("bytes={first}-{}", end - 1)); + let mut response = source.get(client, asked, None, stop).await?; + let headers = response.headers(); + let expected = match (range, response.status()) { + (None, StatusCode::OK) => content_length(headers), + (Some((first, end)), StatusCode::PARTIAL_CONTENT) => { + let got = ContentRange::of(headers).filter(|r| r.first == first && r.last < end); + let got = got.ok_or_else(|| Error::BadReply("another range than asked for".into()))?; + if got.last + 1 < end && got.total.is_none_or(|total| got.last + 1 < total) { + return Err(Error::BadReply("less than asked for".into())); + } + Some(got.len()) + } + (Some(_), StatusCode::OK) => return Err(Error::RangeIgnored), + _ => return Err(status_error(&response)), + }; + let url = response.url().clone(); + check_encoding(headers, &url)?; + let too_large = || Error::BadReply(format!("larger than {most}")); + if expected.is_some_and(|n| n > most) { + return Err(too_large()); + } + let mime = name::mime(headers); + let mut body = Vec::with_capacity(expected.unwrap_or(0) as usize); + let work = async { + let cut = |e: reqwest::Error, got| if e.is_timeout() { e.into() } else { Error::Cut { got, expected } }; + while let Some(chunk) = client.wait(async { response.chunk().await.map_err(|e| cut(e, body.len() as u64)) }).await? { + let mut rest = &chunk[..]; + while !rest.is_empty() { + let (now, later) = rest.split_at(flow.take(rest.len() as u64).await as usize); + body.extend_from_slice(now); + received.fetch_add(now.len() as u64, Ordering::Relaxed); + rest = later; + } + if body.len() as u64 > most { + return Err(too_large()); + } + } + Ok(()) + }; + tokio::select! { + biased; + _ = stopped(stop) => return Err(Error::Stopped), + done = work => done?, + } + match expected { + Some(n) if n != body.len() as u64 => Err(Error::Cut { got: body.len() as u64, expected }), + _ => Ok(Piece { url, mime, body }), + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 6aaae21..415ae11 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -30,6 +30,7 @@ pub mod site; pub mod snapshot; pub mod speed; pub mod store; +pub mod stream; pub mod strings; pub mod tls; mod transport; diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 20bfdc4..603a84b 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -20,6 +20,7 @@ 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::stream::{self, Tools}; use crate::{adopt, disk, host, redact, site, strings, tr}; use arc_swap::ArcSwap; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; @@ -108,6 +109,8 @@ struct Entry { connections: u32, wanted: u32, resumable: Option, + /// Its next run ends a stream at once. + finish: bool, meter: Meter, history: Arc, /// Bytes of the second that isn't over. @@ -135,6 +138,7 @@ impl Entry { connections: 0, wanted: 0, resumable: None, + finish: false, meter: Meter::default(), history: Arc::default(), second: 0, @@ -556,6 +560,7 @@ impl Actor { } Command::Resume(_) => result = self.resume(id), Command::Pause(_) => result = self.hold(id), + Command::Finish(_) => result = self.finish(id), Command::Stop(_) => { result = self.hold(id).and_then(|()| { if matches!(state, Done | Gone) { @@ -874,6 +879,25 @@ impl Actor { } } + /// Ends a stream: now, or in a run of its own when it doesn't run. + fn finish(&mut self, id: TaskId) -> Result<()> { + let e = &self.entries[&id]; + if stream::kind_of(&e.task).is_none() || matches!(e.task.state, State::Checking | State::Finishing | State::Done | State::Gone) { + return Ok(()); + } + match &e.work { + Some(Work::Run(run)) if e.task.state == State::Running => run.monitor.finish(), + _ => { + self.entry(id).finish = true; + self.resume(id)?; + self.forces += 1; + self.entry(id).forced = self.forces; + self.choose = true; + } + } + Ok(()) + } + /// Takes a running one's place away. fn suspend(&mut self, id: TaskId) { if self.entries[&id].task.state == State::Running { @@ -959,11 +983,18 @@ impl Actor { 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 }; + if std::mem::take(&mut self.entry(id).finish) { + monitor.finish(); + } let (shared, options, to) = (self.config.shared.clone(), self.config.options.clone(), self.to.clone()); let sites = self.config.sites.clone(); self.runtime().spawn(async move { let work = tokio::spawn(async move { let source = site::source(sites.as_ref(), &task, &stopped).await?; + if stream::kind_of(&task).is_some() { + let request = stream::Request { id, source, choice: Default::default(), tools: &Tools::find(), options: &options }; + return stream::download(&shared, request, &monitor, stopped).await; + } download(&shared, id, source, &options, &monitor, stopped).await }); let result = match work.await { diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index acbc018..88b8ea4 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -98,6 +98,8 @@ pub enum Command { Pause(TaskId), /// Back in line, also after a failure. Resume(TaskId), + /// What goes on until it is stopped, like a live stream, ends here: what there is becomes the file. + Finish(TaskId), /// Pauses it and puts it last. Stop(TaskId), /// Can be undone for `Config::undo`, and until the program ends. @@ -131,7 +133,7 @@ impl Command { use Command::*; match self { Add(_) | Adopt { .. } => None, - Start(id) | Pause(id) | Resume(id) | Stop(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) | KeepBoth(id) | AwaitLink(id) => Some(*id), Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id), } } diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index d3d8ee1..15c0a3e 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -129,6 +129,12 @@ named_enum!( Killed = "killed", /// Waits for a link from its page. Link = "link", + /// A program that is needed is not on this computer. + Tool = "tool", + /// Copy protection, which is never worked around. + Drm = "drm", + /// Sound and picture that can't be made a file of. + Media = "media", Crashed = "crashed", } ); diff --git a/crates/core/src/stream/dash.rs b/crates/core/src/stream/dash.rs new file mode 100644 index 0000000..8649e52 --- /dev/null +++ b/crates/core/src/stream/dash.rs @@ -0,0 +1,479 @@ +//! DASH manifests (ISO/IEC 23009-1): those that are whole, and simple ones that grow. + +use super::list::*; +use super::{drm, odd}; +use crate::http::Result; +use roxmltree::{Document, Node}; +use url::Url; + +/// More than any film has. Numbers in a manifest must not make us count for ever. +const MOST: u64 = 200_000; +/// Pieces taken of a file that has all in one. +pub(super) const CHUNK: u64 = 4 << 20; + +#[derive(Debug)] +pub(super) struct Manifest { + pub found: Found, + periods: Vec, + pace: f64, + /// Seconds since 1970. + begins: Option, + depth: Option, +} + +#[derive(Debug)] +struct Period { + start: f64, + length: Option, + sets: Vec, +} + +#[derive(Debug)] +struct Rendition { + variant: Variant, + /// Not video. + sound: bool, + base: Url, + segments: Segments, +} + +#[derive(Debug)] +enum Segments { + Template { init: Option, media: String, number: u64, end_number: Option, scale: f64, each: Option, times: Vec<(u64, u64)>, offset: u64 }, + List { init: Option, media: Vec, seconds: f64 }, + Whole, +} + +pub(super) fn parse(text: &str, base: &Url) -> Result { + let doc = Document::parse(text.trim_start_matches('\u{feff}')).map_err(|_| odd("manifest"))?; + let mpd = doc.root_element(); + if mpd.tag_name().name() != "MPD" { + return Err(odd("no manifest")); + } + // Widevine, PlayReady, FairPlay, ClearKey: all announce themselves like this. + if doc.descendants().any(|n| n.tag_name().name() == "ContentProtection") { + return Err(drm()); + } + let live = mpd.attribute("type") == Some("dynamic"); + let length = mpd.attribute("mediaPresentationDuration").and_then(seconds); + let base = base_url(mpd, base)?; + let mut periods: Vec = vec![]; + for p in children(mpd, "Period") { + if p.attributes().any(|a| a.name() == "href") { + return Err(odd("a period elsewhere")); + } + let own = p.attribute("start").and_then(seconds); + let start = own.or_else(|| periods.last().map_or(Some(0.0), |l| Some(l.start + l.length?))).ok_or_else(|| odd("period"))?; + if let Some(last) = periods.last_mut().filter(|l| l.length.is_none()) { + last.length = Some(start - last.start); + } + let mut period = Period { start, length: p.attribute("duration").and_then(seconds), sets: vec![] }; + let base = base_url(p, &base)?; + for set in children(p, "AdaptationSet") { + let base = base_url(set, &base)?; + for r in children(set, "Representation") { + period.sets.extend(rendition(p, set, r, &base)?); + } + } + periods.push(period); + } + if let Some(last) = periods.last_mut().filter(|l| l.length.is_none() && !live) { + last.length = length.map(|n| n - last.start); + } + let first = periods.iter().find(|p| !p.sets.is_empty()).ok_or_else(|| odd("no streams"))?; + let mut found = Found { kind: Kind::Dash, live, duration: length.filter(|_| !live), videos: vec![], audios: vec![] }; + for r in &first.sets { + let list = if r.sound { &mut found.audios } else { &mut found.videos }; + if !list.iter().any(|v| v.id == r.variant.id) { + list.push(r.variant.clone()); + } + } + sort(&mut found.videos); + sort(&mut found.audios); + Ok(Manifest { + found, + periods, + pace: mpd.attribute("minimumUpdatePeriod").and_then(seconds).unwrap_or(4.0).clamp(0.5, 60.0), + begins: mpd.attribute("availabilityStartTime").and_then(date), + depth: mpd.attribute("timeShiftBufferDepth").and_then(seconds), + }) +} + +fn children<'a, 'b: 'a>(node: Node<'a, 'b>, name: &'static str) -> impl Iterator> { + node.children().filter(move |n| n.tag_name().name() == name) +} + +fn child<'a, 'b: 'a>(node: Node<'a, 'b>, name: &'static str) -> Option> { + children(node, name).next() +} + +/// The first of several: the others are the same on other servers. +fn base_url(node: Node, base: &Url) -> Result { + match child(node, "BaseURL").and_then(|b| b.text()) { + Some(text) => web(base, text).ok_or_else(|| odd("base")), + None => Ok(base.clone()), + } +} + +/// None for what is neither picture nor sound. +fn rendition(period: Node, set: Node, r: Node, base: &Url) -> Result> { + let either = |name| r.attribute(name).or(set.attribute(name)); + let mime = either("mimeType").or(set.attribute("contentType")).unwrap_or_default(); + let sound = match mime.split('/').next() { + Some("video") => false, + Some("audio") => true, + _ => return Ok(None), + }; + // Pictures for the seek bar. + if children(set, "EssentialProperty").chain(children(r, "EssentialProperty")).any(|p| p.attribute("schemeIdUri").is_some_and(|s| s.contains("trick"))) { + return Ok(None); + } + let number = |name| either(name).and_then(|n| n.parse::().ok()); + let id = r.attribute("id").unwrap_or_default().to_string(); + let bandwidth = r.attribute("bandwidth").and_then(|b| b.parse().ok()).unwrap_or(0); + let main = children(set, "Role").any(|role| role.attribute("value") == Some("main")); + let variant = Variant { + bandwidth, + size: number("width").zip(number("height")), + codecs: either("codecs").unwrap_or_default().to_string(), + language: set.attribute("lang").map(String::from), + preferred: sound && main, + ..Variant::new(id) + }; + let base = base_url(r, base)?; + let levels = [r, set, period]; + let template: Vec = levels.iter().filter_map(|n| child(*n, "SegmentTemplate")).collect(); + let list: Vec = levels.iter().filter_map(|n| child(*n, "SegmentList")).collect(); + fn attr<'a>(nodes: &[Node<'a, 'a>], name: &str) -> Option<&'a str> { + nodes.iter().find_map(|n| n.attribute(name)) + } + let segments = if !template.is_empty() { + let int = |name, or| attr(&template, name).map_or(Some(or), |n| n.parse().ok()).ok_or_else(|| odd("template")); + let times = template.iter().find_map(|n| child(*n, "SegmentTimeline")).map(|t| timeline(t, period)).transpose()?; + let each = attr(&template, "duration").and_then(|d| d.parse().ok()).filter(|d| *d > 0); + if each.is_none() && times.is_none() { + return Err(odd("template")); + } + let scale: u64 = int("timescale", 1)?; + Segments::Template { + init: attr(&template, "initialization").map(|t| fill(t, &variant, 0, 0)).transpose()?, + media: attr(&template, "media").ok_or_else(|| odd("template"))?.to_string(), + number: int("startNumber", 1)?, + end_number: attr(&template, "endNumber").and_then(|n| n.parse().ok()), + scale: scale.max(1) as f64, + each: each.filter(|_| times.is_none()), + times: times.unwrap_or_default(), + offset: int("presentationTimeOffset", 0)?, + } + } else if !list.is_empty() { + let piece = |link: Option<&str>, range: Option<&str>| -> Result { + let url = link.map_or(Some(base.clone()), |l| web(&base, l)).ok_or_else(|| odd("link"))?; + Ok(Piece { url, range: range.map(|r| byte_range(r).ok_or_else(|| odd("range"))).transpose()? }) + }; + let init = list.iter().find_map(|n| child(*n, "Initialization")); + let media = list.iter().map(|n| children(*n, "SegmentURL").collect::>()).find(|m| !m.is_empty()).unwrap_or_default(); + let scale = attr(&list, "timescale").and_then(|n| n.parse().ok()).filter(|n: &f64| *n > 0.0).unwrap_or(1.0); + Segments::List { + init: init.map(|i| piece(i.attribute("sourceURL"), i.attribute("range"))).transpose()?, + media: media.iter().map(|m| piece(m.attribute("media"), m.attribute("mediaRange"))).collect::>()?, + seconds: attr(&list, "duration").and_then(|n| n.parse::().ok()).unwrap_or(0.0) / scale, + } + } else { + Segments::Whole + }; + Ok(Some(Rendition { variant, sound, base, segments })) +} + +/// Start and length of each. +fn timeline(node: Node, period: Node) -> Result> { + let mut times: Vec<(u64, u64)> = vec![]; + let entries: Vec = children(node, "S").collect(); + let mut t = 0u64; + for (i, s) in entries.iter().enumerate() { + let int = |name| s.attribute(name).and_then(|n| n.parse::().ok()); + let d = int("d").filter(|d| *d > 0).ok_or_else(|| odd("timeline"))?; + t = int("t").unwrap_or(t); + let more = match s.attribute("r").map(|r| r.parse::()) { + None => 0, + Some(Ok(r)) if r >= 0 => r as u64, + // Up to the next one, or the end of the period. + Some(Ok(_)) => { + let next = entries.get(i + 1).and_then(|n| n.attribute("t")).and_then(|n| n.parse::().ok()); + let scale = node.parent_element().and_then(|p| p.attribute("timescale")).and_then(|n| n.parse::().ok()).unwrap_or(1.0); + let of_period = || Some((period.attribute("duration").and_then(seconds)? * scale) as u64 + entries[0].attribute("t").and_then(|t| t.parse().ok()).unwrap_or(0)); + let end = next.or_else(of_period).ok_or_else(|| odd("timeline"))?; + end.saturating_sub(t).div_ceil(d).saturating_sub(1) + } + Some(Err(_)) => return Err(odd("timeline")), + }; + if more >= MOST || times.len() as u64 + more >= MOST { + return Err(odd("timeline")); + } + for _ in 0..=more { + times.push((t, d)); + t = t.checked_add(d).ok_or_else(|| odd("timeline"))?; + } + } + Ok(times) +} + +/// `$Number%05d$` and the like. +fn fill(template: &str, v: &Variant, number: u64, time: u64) -> Result { + let mut out = String::new(); + let mut rest = template; + while let Some((before, after)) = rest.split_once('$') { + out += before; + let (name, after) = after.split_once('$').ok_or_else(|| odd("template"))?; + rest = after; + let (name, format) = name.split_once('%').unwrap_or((name, "")); + let width: usize = match format.strip_suffix('d') { + Some(w) => w.parse().ok().filter(|w| *w <= 32).ok_or_else(|| odd("template"))?, + None => 0, + }; + match name { + "" => out.push('$'), + "RepresentationID" => out += &v.id, + "Number" => out += &format!("{number:0width$}"), + "Time" => out += &format!("{time:0width$}"), + "Bandwidth" => out += &format!("{:0width$}", v.bandwidth), + _ => return Err(odd("template")), + } + } + Ok(out + rest) +} + +fn byte_range(text: &str) -> Option<(u64, u64)> { + let (first, last) = text.split_once('-')?; + let (first, last): (u64, u64) = (first.trim().parse().ok()?, last.trim().parse().ok()?); + (first <= last).then_some((first, last.checked_add(1)?)) +} + +/// `P1DT2H3M4.5S` +fn seconds(text: &str) -> Option { + let (days, time) = text.trim().strip_prefix('P')?.split_once('T').unwrap_or((text.trim().strip_prefix('P')?, "")); + let mut total = 0.0; + for (text, units) in [(days, &[('D', 86400.0)][..]), (time, &[('H', 3600.0), ('M', 60.0), ('S', 1.0)])] { + let mut digits = String::new(); + for c in text.chars() { + if c.is_ascii_digit() || c == '.' { + digits.push(c); + } else { + let unit = units.iter().find(|(u, _)| *u == c)?.1; + total += std::mem::take(&mut digits).parse::().ok()? * unit; + } + } + } + Some(total) +} + +fn date(text: &str) -> Option { + let parsed = chrono::DateTime::parse_from_rfc3339(text).or_else(|_| chrono::DateTime::parse_from_rfc3339(&format!("{text}Z"))).ok()?; + Some(parsed.timestamp_millis() as f64 / 1000.0) +} + +impl Manifest { + /// `now` in seconds since 1970. + pub fn media(&self, variant: &Variant, now: f64) -> Result { + let live = self.found.live; + let sound = self.found.audios.iter().any(|a| a.id == variant.id); + let mut media = Media { ended: !live, pace: self.pace, ..Media::default() }; + for period in &self.periods { + let Some(r) = period.closest(variant, sound) else { continue }; + // The start tells periods apart, also when old ones are dropped from the manifest. + let stretch = (period.start * 1000.0) as u64; + if matches!(r.segments, Segments::Whole) { + if self.periods.len() > 1 || live { + return Err(odd("several files")); + } + media.whole = Some(r.base.clone()); + return Ok(media); + } + media.segments.extend(r.expand(period, stretch, live.then(|| self.window(period, now)).flatten())?); + } + if media.segments.len() as u64 > MOST { + return Err(odd("too many")); + } + if !live { + // The place in the list is what stays. + for (i, s) in media.segments.iter_mut().enumerate() { + (s.seq, s.next) = (i as u64, i as u64 + 1); + } + } + Ok(media) + } + + /// What of a growing period is there: from and to, in seconds since its start. + fn window(&self, period: &Period, now: f64) -> Option<(f64, f64)> { + let to = now - self.begins? - period.start; + let to = period.length.map_or(to, |n| to.min(n)); + Some((self.depth.map_or(0.0, |d| (to - d).max(0.0)), to)) + } +} + +impl Period { + /// The same one, or what comes next to it. + fn closest(&self, variant: &Variant, sound: bool) -> Option<&Rendition> { + let same = self.sets.iter().find(|r| r.variant.id == variant.id && r.sound == sound); + let mut fit: Vec<&Rendition> = self.sets.iter().filter(|r| r.sound == sound).collect(); + fit.sort_by_key(|r| (r.variant.language != variant.language, r.variant.bandwidth.abs_diff(variant.bandwidth))); + same.or(fit.first().copied()) + } +} + +impl Rendition { + fn expand(&self, period: &Period, stretch: u64, window: Option<(f64, f64)>) -> Result> { + let segment = |seq, next, seconds, piece, init: &Option| Segment { stretch, seq, next, seconds, piece, key: None, init: init.clone(), init_key: None }; + match &self.segments { + Segments::Whole => Ok(vec![]), + Segments::List { init, media, seconds } => { + let numbered = media.iter().enumerate().map(|(i, p)| (i as u64, p)); + Ok(numbered.map(|(i, p)| segment(i, i + 1, *seconds, p.clone(), init)).collect()) + } + Segments::Template { init, media, number, end_number, scale, each, times, offset } => { + let at = |number, time| -> Result { + let url = web(&self.base, &fill(media, &self.variant, number, time)?).ok_or_else(|| odd("link"))?; + Ok(Piece { url, range: None }) + }; + let init = match init { + Some(link) => Some(Piece { url: web(&self.base, link).ok_or_else(|| odd("link"))?, range: None }), + None => None, + }; + let Some(each) = each else { + let numbered = times.iter().zip(*number..); + return numbered.map(|(&(t, d), n)| Ok(segment(t, t + d, d as f64 / scale, at(n, t)?, &init))).collect(); + }; + let long = *each as f64 / scale; + let (from, to) = match window { + // Only those that are whole. + Some((from, to)) => ((from / long).ceil().max(0.0) as u64, (to / long).floor().max(0.0) as u64), + None => (0, (period.length.ok_or_else(|| odd("period"))? / long - 1e-6).ceil().max(0.0) as u64), + }; + let to = end_number.map_or(to, |e| to.min((e + 1).saturating_sub(*number))); + if to.saturating_sub(from) > MOST { + return Err(odd("too many")); + } + (from..to).map(|i| Ok(segment(i, i + 1, long, at(number + i, offset + i * each)?, &init))).collect() + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::Error; + use crate::model::ErrorKind; + + fn base() -> Url { + Url::parse("https://h/a/m.mpd").unwrap() + } + + fn manifest(text: &str) -> Manifest { + parse(text, &base()).unwrap() + } + + fn paths(m: &Media) -> Vec<&str> { + m.segments.iter().map(|s| s.piece.url.path()).collect() + } + + const NUMBERED: &str = r#" + + + sound/ + + "#; + + #[test] + fn templates() { + let m = manifest(NUMBERED); + assert_eq!(m.found.duration, Some(9.5)); + let picked = m.found.pick(&Choice::default()).unwrap(); + assert_eq!(picked.iter().map(|v| v.id.as_str()).collect::>(), ["high", "s"]); + let video = m.media(&picked[0], 0.0).unwrap(); + assert!(video.ended); + assert_eq!(paths(&video), ["/a/high/001.m4s", "/a/high/002.m4s", "/a/high/003.m4s"]); + assert_eq!(video.segments[0].init.as_ref().unwrap().url.path(), "/a/high/i.mp4"); + let sound = m.media(&picked[1], 0.0).unwrap(); + assert_eq!(paths(&sound), ["/a/sound/5$.m4s", "/a/sound/45$.m4s", "/a/sound/85$.m4s"]); + assert_eq!(sound.segments[2].seconds, 1.5); + let small = Choice { max_height: Some(480), audio: Pick::None, ..Choice::default() }; + assert_eq!(m.found.pick(&small).unwrap()[0].id, "low"); + } + + #[test] + fn lists_and_single_files() { + let m = manifest( + r#"v.mp4 + + a.mp4"#, + ); + let v = m.media(&m.found.videos[0], 0.0).unwrap(); + assert_eq!(v.segments[0].piece.range, Some((10, 20))); + assert_eq!(paths(&v), ["/a/v.mp4", "/a/x.mp4"]); + assert_eq!(v.segments[0].init.as_ref().unwrap().range, Some((0, 10))); + assert_eq!(m.media(&m.found.audios[0], 0.0).unwrap().whole.unwrap().path(), "/a/a.mp4"); + } + + #[test] + fn periods_follow_each_other() { + let set = |id: &str| format!(r#""#); + let m = manifest(&format!( + r#"{}{}"#, + set("a"), + set("b") + )); + let v = m.media(&m.found.videos[0], 0.0).unwrap(); + assert_eq!(paths(&v), ["/a/a1", "/a/a2", "/a/b1", "/a/b2", "/a/b3"]); + assert_eq!(v.segments.iter().map(|s| (s.stretch, s.seq)).collect::>(), [(0, 0), (0, 1), (4000, 2), (4000, 3), (4000, 4)]); + } + + #[test] + fn growing_ones() { + let m = manifest( + r#" + "#, + ); + assert!(m.found.live); + let v = m.media(&m.found.videos[0], 121.0).unwrap(); + assert!(!v.ended); + assert_eq!(paths(&v), ["/a/8", "/a/9"], "those of the last 6 seconds that are whole"); + } + + #[test] + fn protected_ones_are_refused() { + for uuid in ["edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", "9a04f079-9840-4286-ab92-e65be0885f95", "94ce86fb-07ff-4f43-adb8-93d2fa968ca2"] { + let text = NUMBERED.replace("", &format!(r#""#)); + assert!(matches!(parse(&text, &base()), Err(Error::Conn { kind: ErrorKind::Drm, .. }))); + } + } + + #[test] + fn nonsense_is_no_manifest() { + let with = |inner: &str| format!(r#"{inner}"#); + let media = |text: &str| parse(text, &base()).and_then(|m| m.media(&m.found.videos[0].clone(), 0.0)); + for text in [ + "", + "", + "", + r#"]>&a;"#, + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#"file:///etc/"#), + ] { + assert!(matches!(media(text), Err(Error::BadReply(_))), "{text}"); + } + } + + #[test] + fn times() { + assert_eq!(seconds("P1DT2H3M4.5S"), Some(86400.0 + 7200.0 + 180.0 + 4.5)); + assert_eq!(seconds("PT0S"), Some(0.0)); + assert_eq!(seconds("5"), None); + assert_eq!(date("1970-01-01T00:00:01"), Some(1.0)); + assert_eq!(date("1970-01-01T01:00:01.5+01:00"), Some(1.5)); + } +} diff --git a/crates/core/src/stream/fetch.rs b/crates/core/src/stream/fetch.rs new file mode 100644 index 0000000..1bc9802 --- /dev/null +++ b/crates/core/src/stream/fetch.rs @@ -0,0 +1,388 @@ +//! Lists and pieces from the server, and which pieces are still wanted. + +use super::list::*; +use super::tape::{Record, Tape}; +use super::{PARALLEL, dash, drm, hls, odd}; +use crate::host::{self, Hosts, Member, Permit}; +use crate::http::{self, Client, Error, Monitor, Options, Result, Shared, Source, Stop, stopped}; +use crate::limit::{Flow, Group}; +use crate::model::HostProfile; +use crate::store::Store; +use aes::cipher::block_padding::Pkcs7; +use aes::cipher::{BlockModeDecrypt, KeyIvInit}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use url::Url; + +const MOST_LIST: u64 = 32 << 20; +/// Held in memory. +const MOST_PIECE: u64 = 256 << 20; +/// What a growing list is joined at, from its end. +const FROM_END: usize = 3; + +pub(super) fn now() -> f64 { + crate::model::now() as f64 / 1000.0 +} + +/// Worth another try. +pub(super) fn passing(e: &Error) -> bool { + match e { + Error::Net(_) | Error::Idle | Error::Cut { .. } => true, + Error::Status { code, .. } => matches!(code, 408 | 425 | 429 | 500..=599), + _ => false, + } +} + +pub(super) struct Opened { + pub found: Found, + pub manifest: Option, + /// The link itself was the list of one variant. + pub media: Option, +} + +/// One download's way to its servers. +pub(super) struct Net { + client: Client, + pub source: Source, + options: Options, + flow: Arc, + received: Arc, + places: Option, + width: AtomicU32, + /// Held while one is asked for: the others wait for it. + keys: tokio::sync::Mutex>, +} + +/// Connections are shared with the other downloads. +struct Places { + hosts: Arc, + store: Arc, + members: Mutex>>, + /// Connections between two pieces. + idle: Mutex>, +} + +impl Net { + pub fn new(shared: &Shared, source: &Source, options: &Options, monitor: &Monitor, received: Arc) -> Net { + let places = Places { hosts: shared.hosts.clone(), store: shared.store.clone(), members: Mutex::default(), idle: Mutex::default() }; + Net { + client: shared.client.clone(), + source: source.clone(), + options: options.clone(), + flow: monitor.flow().clone(), + received, + places: Some(places), + width: AtomicU32::new(PARALLEL), + keys: tokio::sync::Mutex::default(), + } + } + + /// For a look at what there is. + pub fn plain(client: &Client, source: &Source) -> Net { + Net { + client: client.clone(), + source: source.clone(), + options: Options { tries: 1, ..Options::default() }, + flow: Arc::new(Flow::free()), + received: Arc::default(), + places: None, + width: AtomicU32::new(1), + keys: tokio::sync::Mutex::default(), + } + } + + /// As many pieces at once as the server stands. + pub fn width(&self) -> u32 { + self.width.load(Ordering::Relaxed) + } + + async fn text(&self, url: &Url, stop: &mut Stop) -> Result<(Url, String)> { + let at = if *url == self.source.url { self.source.clone() } else { self.source.at(url) }; + let got = http::piece(&self.client, &at, None, MOST_LIST, &self.flow, &AtomicU64::new(0), stop).await?; + if got.mime.as_deref() == Some("text/html") { + return Err(Error::Page); + } + Ok((got.url, String::from_utf8_lossy(&got.body).into_owned())) + } + + pub async fn open(&self, stop: &mut Stop) -> Result { + let (base, text) = self.text(&self.source.url, stop).await?; + if text.trim_start_matches('\u{feff}').trim_start().starts_with('<') { + let manifest = dash::parse(&text, &base)?; + return Ok(Opened { found: manifest.found.clone(), manifest: Some(manifest), media: None }); + } + Ok(match hls::parse(&text, &base)? { + hls::List::Master(found) => Opened { found, manifest: None, media: None }, + hls::List::Media(media) => { + let only = Variant { url: Some(self.source.url.clone()), ..Variant::new(String::new()) }; + let found = Found { kind: Kind::Hls, live: !media.ended, duration: None, videos: vec![only], audios: vec![] }; + Opened { found, manifest: None, media: Some(media) } + } + }) + } + + /// The lists of the variants, as they are now. `root` is the kind of the first link, unless it is a list of lists. + pub async fn refresh(&self, root: &Option, variants: &[Variant], stop: &mut Stop) -> Result> { + if *root == Some(Kind::Dash) { + let (base, text) = self.text(&self.source.url, stop).await?; + let manifest = dash::parse(&text, &base)?; + return variants.iter().map(|v| manifest.media(v, now())).collect(); + } + let mut media = vec![]; + for v in variants { + let (base, text) = self.text(v.url.as_ref().ok_or_else(|| odd("link"))?, stop).await?; + match hls::parse(&text, &base)? { + hls::List::Media(m) => media.push(m), + hls::List::Master(_) => return Err(odd("a list of lists in a list")), + } + } + Ok(media) + } + + /// A single file is taken in pieces too. + pub async fn split(&self, media: &mut Media, stop: &mut Stop) -> Result<()> { + let Some(url) = media.whole.take() else { return Ok(()) }; + let probe = http::probe(&self.client, &self.source.at(&url), stop).await?; + let size = probe.version.size.filter(|n| probe.ranges && *n > 0); + let ranges: Vec> = match size { + Some(size) => (0..size.div_ceil(dash::CHUNK)).map(|i| Some((i * dash::CHUNK, ((i + 1) * dash::CHUNK).min(size)))).collect(), + None => vec![None], + }; + let each = |(i, range): (usize, Option<(u64, u64)>)| Segment { + stretch: 0, + seq: i as u64, + next: i as u64 + 1, + // Not known, but the same for all. + seconds: range.map_or(1.0, |(a, b)| (b - a) as f64 / dash::CHUNK as f64), + piece: Piece { url: url.clone(), range }, + key: None, + init: None, + init_key: None, + }; + media.segments = ranges.into_iter().enumerate().map(each).collect(); + media.ended = true; + Ok(()) + } + + /// Tries again where that may help. + pub async fn piece(&self, want: &Want, stop: &mut Stop) -> Result> { + let mut data = self.get(&want.piece, MOST_PIECE, stop).await?; + if let Some(key) = &want.key { + let bytes = self.key(&key.url, stop).await?; + let plain = cbc::Decryptor::::new(&bytes.into(), &key.iv.into()).decrypt_padded::(&mut data); + let n = plain.map_err(|_| odd("the key does not fit"))?.len(); + data.truncate(n); + } + if want.record.init && [b"pssh", b"encv", b"enca"].iter().any(|name| data.windows(4).any(|w| w == *name)) { + return Err(drm()); + } + Ok(data) + } + + async fn key(&self, url: &Url, stop: &mut Stop) -> Result<[u8; 16]> { + let mut keys = self.keys.lock().await; + if let Some(key) = keys.get(url) { + return Ok(*key); + } + let got = self.get(&Piece { url: url.clone(), range: None }, 1 << 10, stop).await?; + let key: [u8; 16] = got.try_into().map_err(|_| odd("no key"))?; + keys.insert(url.clone(), key); + Ok(key) + } + + async fn get(&self, piece: &Piece, most: u64, stop: &mut Stop) -> Result> { + let mut fails = 0; + loop { + let permit = self.permit(&piece.url, stop).await?; + let got = http::piece(&self.client, &self.source.at(&piece.url), piece.range, most, &self.flow, &self.received, stop).await; + let e = match got { + Ok(got) => { + self.back(&piece.url, permit); + return Ok(got.body); + } + Err(e) => e, + }; + drop(permit); + fails += 1; + if !passing(&e) || fails >= self.options.tries { + return Err(e); + } + let mut wait = self.options.backoff.saturating_mul(1 << (fails - 1).min(10)).min(self.options.max_wait); + if let Error::Status { code, retry_after } = &e { + if matches!(code, 429 | 503) { + let _ = self.width.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| (n > 1).then_some(n - 1)); + } + match retry_after { + Some(asked) if *asked > self.options.max_wait => return Err(e), + Some(asked) => wait = wait.max(*asked), + None => {} + } + } + tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + _ = tokio::time::sleep(wait) => {} + } + } + } + + /// A place for a connection to the host of `url`. + async fn permit(&self, url: &Url, stop: &mut Stop) -> Result> { + let Some(places) = &self.places else { return Ok(None) }; + let host = host::key(url); + { + let mut idle = places.idle.lock().unwrap(); + idle.retain(|(_, permit)| !permit.revoked()); + if let Some(i) = idle.iter().position(|(h, _)| *h == host) { + return Ok(Some(idle.swap_remove(i).1)); + } + // It goes to others meanwhile. + idle.clear(); + } + let member = places.members.lock().unwrap().get(&host).cloned(); + let member = match member { + Some(member) => member, + None => { + let (store, asked) = (places.store.clone(), host.clone()); + let known: HostProfile = super::run(&store, move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default(); + let at = self.source.at(url); + places.hosts.set_host_cap(&host, at.max_connections().or(known.max_connections)); + self.flow.put_limited(Group::Host(host.clone()), at.speed_limit().or(known.speed_limit)); + places.members.lock().unwrap().entry(host.clone()).or_insert_with(|| Arc::new(places.hosts.join(&host))).clone() + } + }; + loop { + if let Some(permit) = member.open(self.width(), self.flow.weight(), Instant::now()) { + return Ok(Some(permit)); + } + tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + _ = tokio::time::sleep(Duration::from_millis(50)) => {} + } + } + } + + /// The connection can bring the next one. + fn back(&self, url: &Url, permit: Option) { + if let (Some(places), Some(permit)) = (&self.places, permit) + && !permit.revoked() + { + places.idle.lock().unwrap().push((host::key(url), permit)); + } + } + + /// Nothing is wanted for a while. + pub fn rest(&self) { + if let Some(places) = &self.places { + places.idle.lock().unwrap().clear(); + for member in places.members.lock().unwrap().values() { + member.wants(0, self.flow.weight()); + } + } + } +} + +/// A piece to download, and where it belongs. +pub(super) struct Want { + pub record: Record, + pub piece: Piece, + pub key: Option, + /// Seconds from the start, in milliseconds: tracks go on side by side. + pub place: u64, +} + +/// What of one track is wanted. +pub(super) struct Feed { + track: u32, + group: u32, + /// The last one: its stretch and number, and the number that should follow. + last: Option<(u64, u64, u64)>, + /// What the group starts with. None: not known any more. + init: Option>, + have: HashSet<(bool, u32, u64)>, + /// How often the numbers of a growing list began anew. + epoch: u64, + taken: u64, + most: Option, +} + +const EPOCH: u32 = 48; + +impl Feed { + pub fn new(track: u32, tape: &Tape, seconds: Option) -> Feed { + let mine = || tape.records.iter().filter(|r| r.track == track); + let last = mine().filter(|r| !r.init).max_by_key(|r| (r.stretch, r.seq)); + Feed { + track, + group: mine().map(|r| r.group).max().unwrap_or(0), + last: last.map(|r| (r.stretch, r.seq, r.seq + 1)), + init: None, + have: mine().map(|r| (r.init, r.group, r.seq)).collect(), + epoch: last.map_or(0, |r| r.stretch >> EPOCH), + taken: tape.length(track), + most: seconds.filter(|_| tape.head.live).map(|s| s * 1000), + } + } + + pub fn full(&self) -> bool { + self.most.is_some_and(|most| self.taken >= most) + } + + pub fn take(&mut self, media: &Media, live: bool, queue: &mut VecDeque) { + if !live { + return self.all(media, queue); + } + let first = self.last.is_none(); + if let (Some((stretch, seq, _)), Some(end)) = (self.last, media.segments.last()) + && (end.stretch + (self.epoch << EPOCH), end.seq + media.segments.len() as u64) < (stretch, seq) + { + self.epoch += 1; + } + let skip = if first && !media.from_start && !media.ended { media.segments.len().saturating_sub(FROM_END) } else { 0 }; + for s in &media.segments[skip..] { + if self.full() { + return; + } + let stretch = s.stretch + (self.epoch << EPOCH); + if self.last.is_some_and(|(st, seq, _)| (stretch, s.seq) <= (st, seq)) { + continue; + } + let follows = self.last.is_none_or(|(st, _, next)| st == stretch && next == s.seq) && self.init.as_ref().is_none_or(|i| *i == s.init); + if !follows { + self.group += 1; + } + let fresh = !follows || first && !self.have.contains(&(true, self.group, 0)); + self.want(s, stretch, fresh, queue); + self.last = Some((stretch, s.seq, s.next)); + self.init = Some(s.init.clone()); + self.taken += (s.seconds * 1000.0) as u64; + } + } + + /// The same groups each time. + fn all(&mut self, media: &Media, queue: &mut VecDeque) { + let mut before: Option<&Segment> = None; + let (mut group, mut place) = (0, 0); + for s in &media.segments { + let fresh = before.is_none_or(|b| b.stretch != s.stretch || b.init != s.init); + group += u32::from(fresh && before.is_some()); + self.group = group; + let at = queue.len(); + self.want(s, s.stretch, fresh && !self.have.contains(&(true, group, 0)), queue); + queue.range_mut(at..).for_each(|w| w.place = place); + place += (s.seconds * 1000.0) as u64; + before = Some(s); + } + } + + fn want(&mut self, s: &Segment, stretch: u64, fresh: bool, queue: &mut VecDeque) { + let record = Record { track: self.track, group: self.group, init: false, stretch, seq: s.seq, ms: (s.seconds * 1000.0) as u32, at: 0, len: 0 }; + if fresh && let Some(init) = &s.init { + queue.push_back(Want { record: Record { init: true, seq: 0, ms: 0, ..record }, piece: init.clone(), key: s.init_key.clone(), place: 0 }); + } + if self.have.insert((false, self.group, s.seq)) { + queue.push_back(Want { record, piece: s.piece.clone(), key: s.key.clone(), place: 0 }); + } + } +} diff --git a/crates/core/src/stream/ffmpeg.rs b/crates/core/src/stream/ffmpeg.rs new file mode 100644 index 0000000..23a6068 --- /dev/null +++ b/crates/core/src/stream/ffmpeg.rs @@ -0,0 +1,306 @@ +//! The ffmpeg that is on this computer: finding it, running it, stopping it. +//! +//! It gets lists of arguments, never a shell. What must not be seen among the arguments goes through its standard input. + +use crate::http::{Error, Result}; +use crate::model::ErrorKind; +use crate::redact; +use std::collections::VecDeque; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdout, Command}; +use tokio::sync::watch; +use tokio::task::JoinHandle; + +/// Lines of its log that are kept. +const TAIL: usize = 40; +/// Longer ones are cut. +const LINE: u64 = 4096; + +/// Programs that other people make. +#[derive(Debug, Clone, Default)] +pub struct Tools { + pub ffmpeg: Option, +} + +impl Tools { + /// Next to Medlar first, then where programs are. + pub fn find() -> Tools { + let beside = std::env::current_exe().ok().and_then(|exe| Some(exe.parent()?.to_path_buf())); + let path = std::env::var_os("PATH").unwrap_or_default(); + Tools { ffmpeg: find("ffmpeg", beside.as_deref(), &path) } + } + + pub fn ffmpeg(&self) -> Result<&Path> { + self.ffmpeg.as_deref().ok_or(Error::because(ErrorKind::Tool, "error.tool.ffmpeg")) + } +} + +fn find(name: &str, beside: Option<&Path>, path: &OsStr) -> Option { + let runs = |p: &PathBuf| p.is_absolute() && p.is_file() && rustix::fs::access(p, rustix::fs::Access::EXEC_OK).is_ok(); + beside.map(Path::to_path_buf).into_iter().chain(std::env::split_paths(path)).map(|dir| dir.join(name)).find(runs) +} + +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct Progress { + /// Where in the recording or film it is. + pub time: Duration, + /// Bytes written. + pub bytes: u64, +} + +/// What to run. Use `input` for links: it says which protocols may follow. +#[derive(Default)] +pub struct Job { + args: Vec, + stdin: Option>, + output: bool, +} + +/// Without what goes to its standard input. +impl fmt::Debug for Job { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}", self.args) + } +} + +impl Job { + pub fn new() -> Job { + let mut job = Job::default(); + job.args(["-hide_banner", "-nostdin", "-nostats", "-loglevel", "warning", "-progress", "pipe:2", "-y"]); + job + } + + pub fn arg(&mut self, arg: impl AsRef) -> &mut Job { + self.args.push(arg.as_ref().into()); + self + } + + pub fn args>(&mut self, args: impl IntoIterator) -> &mut Job { + self.args.extend(args.into_iter().map(|a| a.as_ref().into())); + self + } + + /// With the protocols it may use, also through what it finds in there. + pub fn input(&mut self, protocols: &str, input: impl AsRef) -> &mut Job { + self.args(["-protocol_whitelist", protocols, "-i"]).arg(input) + } + + /// What it reads as `pipe:0`. + pub fn stdin(&mut self, bytes: impl Into>) -> &mut Job { + self.stdin = Some(bytes.into()); + self + } + + /// The file it makes. `muxer` is ffmpeg's name of the format. + pub fn file(&mut self, muxer: &str, path: &Path) -> &mut Job { + let mut url = OsString::from("file:"); + url.push(path); + self.args(["-f", muxer]).arg(url) + } + + /// What it makes is read from `Running::output`. + pub fn pipe(&mut self, muxer: &str) -> &mut Job { + self.output = true; + self.args(["-f", muxer, "pipe:1"]) + } + + #[cfg(test)] + pub(super) fn script(&self) -> Option<&[u8]> { + self.stdin.as_deref() + } + + pub fn start(self, ffmpeg: &Path) -> Result { + let mut command = Command::new(ffmpeg); + command.args(&self.args).env("AV_LOG_FORCE_NOCOLOR", "1").process_group(0).kill_on_drop(true); + // The user's proxy is never passed on by accident. + for name in ["http_proxy", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"] { + command.env_remove(name); + } + command.stdin(if self.stdin.is_some() { Stdio::piped() } else { Stdio::null() }); + command.stdout(if self.output { Stdio::piped() } else { Stdio::null() }).stderr(Stdio::piped()); + let mut child = command.spawn().map_err(|e| { + log::warn!("{} does not start: {e}", ffmpeg.display()); + Error::because(ErrorKind::Tool, "error.tool.ffmpeg") + })?; + if let (Some(mut stdin), Some(bytes)) = (child.stdin.take(), self.stdin) { + // It may end without reading all of it. + tokio::spawn(async move { drop(stdin.write_all(&bytes).await) }); + } + let (progress, seen) = watch::channel(Progress::default()); + let tail = Arc::new(Mutex::new(VecDeque::new())); + let stderr = child.stderr.take().expect("it is piped"); + let reader = tokio::spawn(listen(stderr, progress, tail.clone())); + Ok(Running { output: child.stdout.take(), child, seen, tail, reader }) + } +} + +/// Reads to the end, so that it never waits for us. +async fn listen(stderr: impl tokio::io::AsyncRead + Unpin, progress: watch::Sender, tail: Arc>>) { + let mut lines = BufReader::new(stderr); + let mut line = vec![]; + let mut now = Progress::default(); + loop { + line.clear(); + let mut short = tokio::io::AsyncReadExt::take(&mut lines, LINE); + match short.read_until(b'\n', &mut line).await { + Ok(0) | Err(_) => return, + Ok(_) => {} + } + let text = String::from_utf8_lossy(&line); + let text = text.trim(); + if text.is_empty() { + continue; + } + if now.read(text) { + if text.starts_with("progress=") { + progress.send_replace(now); + } + continue; + } + let mut tail = tail.lock().unwrap(); + if tail.len() == TAIL { + tail.pop_front(); + } + tail.push_back(redact::text(text)); + } +} + +impl Progress { + /// Whether the line is one of its reports. + fn read(&mut self, line: &str) -> bool { + let Some((key, value)) = line.split_once('=') else { return false }; + let value = value.trim(); + match key { + "out_time_us" => self.time = value.parse().map_or(self.time, Duration::from_micros), + "total_size" => self.bytes = value.parse().unwrap_or(self.bytes), + "frame" | "fps" | "bitrate" | "out_time_ms" | "out_time" | "dup_frames" | "drop_frames" | "speed" | "progress" => {} + _ => return key.starts_with("stream_") && key.ends_with("_q"), + } + true + } +} + +/// Killed when it is dropped. +#[derive(Debug)] +pub struct Running { + pub output: Option, + child: Child, + seen: watch::Receiver, + tail: Arc>>, + reader: JoinHandle<()>, +} + +/// How it failed. +#[derive(Debug)] +pub struct Failed { + /// The end of its log, without secrets. + pub tail: Vec, +} + +impl Running { + pub fn progress(&self) -> watch::Receiver { + self.seen.clone() + } + + /// Asks it to end what it makes properly. `end` tells when it did. + pub fn finish(&self) { + let pid = self.child.id().and_then(|id| rustix::process::Pid::from_raw(id.cast_signed())); + if let Some(pid) = pid { + let _ = rustix::process::kill_process(pid, rustix::process::Signal::INT); + } + } + + pub async fn kill(mut self) { + let _ = self.child.kill().await; + } + + /// Waits for its end. Read all of `output` before. + pub async fn end(&mut self) -> io::Result> { + drop(self.output.take()); + let status = self.child.wait().await?; + let _ = tokio::time::timeout(Duration::from_secs(1), &mut self.reader).await; + if status.success() { + return Ok(Ok(())); + } + let tail: Vec = self.tail.lock().unwrap().iter().cloned().collect(); + log::debug!("ffmpeg failed ({status}): {}", tail.join(" / ")); + Ok(Err(Failed { tail })) + } +} + +impl Failed { + pub fn says(&self, what: &str) -> bool { + self.tail.iter().any(|line| line.contains(what)) + } + + /// What its messages mean. They themselves are for the log only. + pub fn error(&self) -> Error { + use ErrorKind::*; + let known = [ + ("No space left", DiskFull), + ("401 Unauthorized", Login), + ("403 Forbidden", Forbidden), + ("404 Not Found", NotFound), + ("Connection refused", Refused), + ("timed out", Timeout), + ("Failed to resolve", Dns), + ("No route to host", Unreachable), + ("Network is unreachable", Unreachable), + ]; + let Some((_, kind)) = known.iter().find(|(text, _)| self.says(text)) else { return Error::conn(Media) }; + match kind { + DiskFull => Error::Disk(io::Error::from(io::ErrorKind::StorageFull).into()), + Login => Error::conn(Login), + Forbidden => Error::because(Forbidden, "error.forbidden.plain"), + NotFound => Error::because(NotFound, "error.not_found.plain"), + kind => Error::conn(*kind), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn programs_are_found() { + let dir = tempfile::tempdir().unwrap(); + let here = dir.path().join("tool"); + assert_eq!(find("tool", None, dir.path().as_os_str()), None); + std::fs::write(&here, "").unwrap(); + assert_eq!(find("tool", None, dir.path().as_os_str()), None, "it can't be run"); + rustix::fs::chmod(&here, rustix::fs::Mode::RWXU).unwrap(); + assert_eq!(find("tool", None, dir.path().as_os_str()).as_ref(), Some(&here)); + assert_eq!(find("tool", Some(dir.path()), OsStr::new("")).as_ref(), Some(&here)); + // Never from the current folder. + assert_eq!(find("tool", None, OsStr::new(".:")), None); + assert!(matches!(Tools::default().ffmpeg(), Err(Error::Conn { kind: ErrorKind::Tool, .. }))); + } + + #[test] + fn reports_are_told_from_messages() { + let mut p = Progress::default(); + for line in ["frame=10", "out_time_us=2500000", "out_time=00:00:02.500000", "total_size=77", "speed=1x", "stream_0_0_q=-1.0", "out_time_us=N/A"] { + assert!(p.read(line), "{line}"); + } + assert_eq!(p, Progress { time: Duration::from_millis(2500), bytes: 77 }); + assert!(!p.read("Error opening a=b")); + assert!(!p.read("Invalid data found")); + } + + #[test] + fn its_messages_are_understood() { + let of = |text: &str| Failed { tail: vec!["x".into(), text.into()] }.error(); + assert!(matches!(of("Server returned 401 Unauthorized (authorization failed)"), Error::Conn { kind: ErrorKind::Login, .. })); + assert!(matches!(of("rtsp://h: Connection refused"), Error::Conn { kind: ErrorKind::Refused, .. })); + assert!(matches!(of("av_interleaved_write_frame(): No space left on device"), Error::Disk(_))); + assert!(matches!(of("something else"), Error::Conn { kind: ErrorKind::Media, .. })); + } +} diff --git a/crates/core/src/stream/hls.rs b/crates/core/src/stream/hls.rs new file mode 100644 index 0000000..9e6ebf3 --- /dev/null +++ b/crates/core/src/stream/hls.rs @@ -0,0 +1,304 @@ +//! HLS lists (RFC 8216). + +use super::list::*; +use super::{drm, odd}; +use crate::http::Result; +use std::collections::HashMap; +use url::Url; + +pub(super) enum List { + Master(Found), + Media(Media), +} + +pub(super) fn parse(text: &str, base: &Url) -> Result { + let text = text.trim_start_matches('\u{feff}'); + if !text.trim_start().starts_with("#EXTM3U") { + return Err(odd("no list of streams")); + } + if text.lines().any(|l| l.starts_with("#EXT-X-STREAM-INF:")) { master(text, base).map(List::Master) } else { media(text, base).map(List::Media) } +} + +fn tag<'a>(line: &'a str, name: &str) -> Option<&'a str> { + line.strip_prefix(name)?.strip_prefix(':').map(str::trim) +} + +/// `A=1,B="x,y"` +fn attributes(text: &str) -> HashMap<&str, &str> { + let mut found = HashMap::new(); + let mut rest = text; + while let Some((name, after)) = rest.split_once('=') { + let (value, after) = match after.strip_prefix('"').and_then(|a| a.split_once('"')) { + Some((value, after)) => (value, after.split_once(',').map_or("", |(_, a)| a)), + None => after.split_once(',').unwrap_or((after, "")), + }; + found.insert(name.trim(), value.trim()); + rest = after; + } + found +} + +/// Keys that the list itself offers are fine, anything else is copy protection. +fn check_key(a: &HashMap<&str, &str>) -> Result { + let format = a.get("KEYFORMAT").copied().unwrap_or("identity"); + match a.get("METHOD").copied() { + Some("NONE") => Ok(false), + Some("AES-128") if format == "identity" => Ok(true), + _ => Err(drm()), + } +} + +fn check_protection(line: &str) -> Result<()> { + if let Some(a) = tag(line, "#EXT-X-SESSION-KEY") { + check_key(&attributes(a))?; + } + // Adobe's. + if line.starts_with("#EXT-X-FAXS-CM") { Err(drm()) } else { Ok(()) } +} + +fn master(text: &str, base: &Url) -> Result { + let mut found = Found { kind: Kind::Hls, live: false, duration: None, videos: vec![], audios: vec![] }; + let mut info: Option> = None; + for line in text.lines().map(str::trim) { + check_protection(line)?; + if let Some(a) = tag(line, "#EXT-X-STREAM-INF") { + info = Some(attributes(a)); + } else if let Some(a) = tag(line, "#EXT-X-MEDIA") { + let a = attributes(a); + let text = |name| a.get(name).map(|v: &&str| v.to_string()); + // Without a link it is in the video. + let Some(url) = a.get("URI").filter(|_| a.get("TYPE") == Some(&"AUDIO")) else { continue }; + let Some(url) = web(base, url) else { continue }; + let (group, name) = (text("GROUP-ID").unwrap_or_default(), text("NAME").unwrap_or_default()); + let id = format!("{group}/{name}/{}", text("LANGUAGE").unwrap_or_default()); + found.audios.push(Variant { + language: text("LANGUAGE"), + name: Some(name), + sound: Some(group), + preferred: a.get("DEFAULT") == Some(&"YES"), + url: Some(url), + ..Variant::new(id) + }); + } else if !line.is_empty() && !line.starts_with('#') + && let Some(a) = info.take() + { + let Some(url) = web(base, line) else { continue }; + let bandwidth = a.get("BANDWIDTH").and_then(|b| b.parse().ok()).unwrap_or(0); + let size = a.get("RESOLUTION").and_then(|r| r.split_once('x')).and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))); + let (w, h) = size.unwrap_or_default(); + found.videos.push(Variant { + bandwidth, + size, + codecs: a.get("CODECS").map(|c| c.to_string()).unwrap_or_default(), + sound: a.get("AUDIO").map(|g| g.to_string()), + url: Some(url), + ..Variant::new(format!("{w}x{h}@{bandwidth}")) + }); + } + } + // A video whose sound has no link of its own has it inside. + for v in &mut found.videos { + v.sound = v.sound.take().filter(|g| found.audios.iter().any(|a| a.sound.as_ref() == Some(g))); + } + sort(&mut found.videos); + // The same again on another server. + found.videos.dedup_by(|b, a| a.id == b.id && a.sound == b.sound && a.codecs == b.codecs); + if found.videos.is_empty() { Err(odd("no variants")) } else { Ok(found) } +} + +fn media(text: &str, base: &Url) -> Result { + let mut media = Media { pace: 6.0, ..Media::default() }; + let (mut seq, mut breaks) = (0u64, 0u64); + let (mut key, mut init, mut seconds, mut range, mut gap) = (None::<(Url, Option<[u8; 16]>)>, None, 0.0, None, false); + let mut init_key = None; + // Where the last range of each file ended. + let mut ends: HashMap = HashMap::new(); + for line in text.lines().map(str::trim) { + check_protection(line)?; + if let Some(n) = tag(line, "#EXT-X-TARGETDURATION") { + media.pace = n.parse::().ok().filter(|n| n.is_finite()).unwrap_or(media.pace).clamp(0.5, 60.0); + } else if let Some(n) = tag(line, "#EXT-X-MEDIA-SEQUENCE") { + seq = n.parse().map_err(|_| odd("sequence"))?; + } else if let Some(n) = tag(line, "#EXT-X-DISCONTINUITY-SEQUENCE") { + breaks = n.parse().map_err(|_| odd("sequence"))?; + } else if line == "#EXT-X-DISCONTINUITY" { + breaks += 1; + } else if line == "#EXT-X-ENDLIST" { + media.ended = true; + } else if line == "#EXT-X-GAP" { + gap = true; + } else if let Some(kind) = tag(line, "#EXT-X-PLAYLIST-TYPE") { + media.from_start = kind == "EVENT"; + } else if let Some(a) = tag(line, "#EXT-X-KEY") { + let a = attributes(a); + key = if check_key(&a)? { + let url = a.get("URI").and_then(|u| web(base, u)).ok_or_else(|| odd("key"))?; + Some((url, a.get("IV").map(|iv| parse_iv(iv).ok_or_else(|| odd("iv"))).transpose()?)) + } else { + None + }; + } else if let Some(a) = tag(line, "#EXT-X-MAP") { + let a = attributes(a); + let url = a.get("URI").and_then(|u| web(base, u)).ok_or_else(|| odd("map"))?; + let range = match a.get("BYTERANGE") { + Some(text) => Some(byte_range(text, 0).ok_or_else(|| odd("range"))?), + None => None, + }; + init = Some(Piece { url, range }); + // RFC 8216 4.3.2.5: an encrypted one has to say its IV. + init_key = key.clone().map(|(url, iv)| Key { url, iv: iv.unwrap_or_default() }); + } else if let Some(text) = tag(line, "#EXTINF") { + seconds = text.split(',').next().and_then(|s| s.trim().parse().ok()).filter(|s: &f64| s.is_finite() && *s >= 0.0).unwrap_or(0.0); + } else if let Some(text) = tag(line, "#EXT-X-BYTERANGE") { + range = Some(text.to_string()); + } else if !line.is_empty() && !line.starts_with('#') { + let url = web(base, line).ok_or_else(|| odd("link"))?; + let range = match range.take() { + Some(text) => Some(byte_range(&text, ends.get(&url).copied().unwrap_or(0)).ok_or_else(|| odd("range"))?), + None => None, + }; + if let Some((_, end)) = range { + ends.insert(url.clone(), end); + } + let key = key.clone().map(|(url, iv)| Key { url, iv: iv.unwrap_or(u128::from(seq).to_be_bytes()) }); + if !std::mem::take(&mut gap) { + let piece = Piece { url, range }; + media.segments.push(Segment { stretch: breaks, seq, next: seq.wrapping_add(1), seconds, piece, key, init: init.clone(), init_key: init_key.clone() }); + } + seq = seq.checked_add(1).ok_or_else(|| odd("sequence"))?; + } + } + if media.ended { + // Servers count these as they like; the place in the list is what stays. + for (i, s) in media.segments.iter_mut().enumerate() { + (s.seq, s.next) = (i as u64, i as u64 + 1); + } + } + Ok(media) +} + +/// `length[@start]` +fn byte_range(text: &str, after: u64) -> Option<(u64, u64)> { + let (len, start) = match text.split_once('@') { + Some((len, start)) => (len, start.trim().parse().ok()?), + None => (text, after), + }; + let len: u64 = len.trim().parse().ok().filter(|n| *n > 0)?; + Some((start, start.checked_add(len)?)) +} + +fn parse_iv(text: &str) -> Option<[u8; 16]> { + let hex = text.strip_prefix("0x").or(text.strip_prefix("0X"))?; + Some(u128::from_str_radix(hex, 16).ok()?.to_be_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::Error; + use crate::model::ErrorKind; + + fn base() -> Url { + Url::parse("https://h/a/list.m3u8?t=1").unwrap() + } + + fn list(text: &str) -> Media { + match parse(text, &base()) { + Ok(List::Media(m)) => m, + _ => panic!("no media list: {text}"), + } + } + + fn found(text: &str) -> Found { + match parse(text, &base()) { + Ok(List::Master(f)) => f, + _ => panic!("no master list: {text}"), + } + } + + fn refused(text: &str) -> bool { + matches!(parse(text, &base()), Err(Error::Conn { kind: ErrorKind::Drm, .. })) + } + + #[test] + fn variants_and_sound() { + let f = found( + "#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",NAME=\"English, plain\",LANGUAGE=\"en\",URI=\"en.m3u8\"\n\ + #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",NAME=\"Deutsch\",LANGUAGE=\"de\",DEFAULT=YES,URI=\"de.m3u8\"\n\ + #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"in\",NAME=\"x\"\n\ + #EXT-X-STREAM-INF:BANDWIDTH=100,RESOLUTION=640x360,CODECS=\"avc1,mp4a\",AUDIO=\"a\"\nlow.m3u8\n\ + #EXT-X-STREAM-INF:BANDWIDTH=300,RESOLUTION=1920x1080,AUDIO=\"a\"\nhigh.m3u8\n\ + #EXT-X-STREAM-INF:BANDWIDTH=300,RESOLUTION=1920x1080,AUDIO=\"a\"\nhttps://other/high.m3u8\n\ + #EXT-X-STREAM-INF:BANDWIDTH=200,RESOLUTION=1280x720,AUDIO=\"in\"\nmid.m3u8\n", + ); + let ids: Vec<&str> = f.videos.iter().map(|v| v.id.as_str()).collect(); + assert_eq!(ids, ["1920x1080@300", "1280x720@200", "640x360@100"]); + assert_eq!(f.audios[0].name.as_deref(), Some("English, plain")); + let picked = |choice: Choice| f.pick(&choice).map(|v| v.into_iter().map(|v| v.url.unwrap().path().to_string()).collect::>()); + assert_eq!(picked(Choice::default()).unwrap(), ["/a/high.m3u8", "/a/de.m3u8"]); + assert_eq!(picked(Choice { max_height: Some(720), ..Choice::default() }).unwrap(), ["/a/mid.m3u8"], "its sound is inside"); + assert_eq!(picked(Choice { max_height: Some(100), ..Choice::default() }).unwrap()[0], "/a/low.m3u8"); + let english = Pick::One(f.audios[0].id.clone()); + assert_eq!(picked(Choice { video: Pick::None, audio: english, ..Choice::default() }).unwrap(), ["/a/en.m3u8"]); + assert_eq!(picked(Choice { video: Pick::One("gone".into()), ..Choice::default() }), None); + } + + #[test] + fn segments() { + let m = list( + "#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-MEDIA-SEQUENCE:7\n#EXT-X-MAP:URI=\"i.mp4\",BYTERANGE=\"10@5\"\n\ + #EXTINF:3.5,title\n#EXT-X-BYTERANGE:100@20\nall.m4s\n#EXTINF:4,\n#EXT-X-BYTERANGE:50\nall.m4s\n\ + #EXT-X-DISCONTINUITY\n#EXT-X-GAP\n#EXTINF:4,\nnone.m4s\n#EXTINF:1,\n../x.m4s\n", + ); + assert!(!m.ended && !m.from_start); + assert_eq!(m.pace, 4.0); + let seen: Vec<_> = m.segments.iter().map(|s| (s.stretch, s.seq, s.seconds, s.piece.url.path(), s.piece.range)).collect(); + assert_eq!(seen, [(0, 7, 3.5, "/a/all.m4s", Some((20, 120))), (0, 8, 4.0, "/a/all.m4s", Some((120, 170))), (1, 10, 1.0, "/x.m4s", None)]); + assert_eq!(m.segments[0].init.as_ref().unwrap().range, Some((5, 15))); + } + + #[test] + fn keys() { + let m = list( + "#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:5\n#EXT-X-KEY:METHOD=AES-128,URI=\"k\"\n#EXTINF:1,\na\n\ + #EXT-X-KEY:METHOD=AES-128,URI=\"k2\",IV=0x0102\n#EXTINF:1,\nb\n#EXT-X-KEY:METHOD=NONE\n#EXTINF:1,\nc\n#EXT-X-ENDLIST\n", + ); + let iv = |n: u128| n.to_be_bytes(); + assert_eq!(m.segments[0].key.as_ref().unwrap().iv, iv(5), "the sequence number of the server"); + assert_eq!(m.segments[1].key.as_ref().unwrap().iv, iv(0x102)); + assert_eq!(m.segments[2].key, None); + assert_eq!(m.segments[2].seq, 2); + } + + #[test] + fn protected_ones_are_refused() { + for key in [ + "METHOD=SAMPLE-AES,URI=\"skd://x\",KEYFORMAT=\"com.apple.streamingkeydelivery\"", + "METHOD=SAMPLE-AES,URI=\"k\"", + "METHOD=SAMPLE-AES-CTR,URI=\"data:x\",KEYFORMAT=\"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed\"", + "METHOD=AES-128,URI=\"k\",KEYFORMAT=\"com.microsoft.playready\"", + "METHOD=ISO-23001-7,URI=\"k\"", + ] { + assert!(refused(&format!("#EXTM3U\n#EXT-X-KEY:{key}\n#EXTINF:1,\na\n")), "{key}"); + assert!(refused(&format!("#EXTM3U\n#EXT-X-SESSION-KEY:{key}\n#EXT-X-STREAM-INF:BANDWIDTH=1\na\n")), "{key}"); + } + assert!(refused("#EXTM3U\n#EXT-X-FAXS-CM:URI=\"x\"\n#EXTINF:1,\na\n")); + } + + #[test] + fn nonsense_is_no_list() { + let bad = |text: &str| matches!(parse(text, &base()), Err(Error::BadReply(_))); + for text in [ + "", + "", + "#EXTM3U\n#EXTINF:1,\nfile:///etc/passwd\n", + "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"file:///k\"\n#EXTINF:1,\na\n", + "#EXTM3U\n#EXT-X-BYTERANGE:x\na\n", + "#EXTM3U\n#EXT-X-BYTERANGE:18446744073709551615@5\na\n", + "#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:18446744073709551615\n#EXTINF:1,\na\n", + "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\n", + ] { + assert!(bad(text), "{text}"); + } + } +} diff --git a/crates/core/src/stream/join.rs b/crates/core/src/stream/join.rs new file mode 100644 index 0000000..adc72ce --- /dev/null +++ b/crates/core/src/stream/join.rs @@ -0,0 +1,163 @@ +//! Makes one file of all that arrived, without changing sound or picture. +//! +//! ffmpeg reads the pieces from sockets that only this user can open, so that they need no second place on disk. + +use super::ffmpeg::{Job, Running}; +use super::disk_error; +use super::tape::{Record, Tape}; +use crate::disk::{PartialFile, blocking}; +use crate::http::{Error, Result, Stop, stopped}; +use crate::model::ErrorKind; +use std::io; +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; +use tokio::io::AsyncWriteExt; +use tokio::net::UnixListener; +use tokio::task::JoinSet; + +/// What streams are made of. Keeps pieces from pretending to be lists that lead to other files. +const FORMATS: &str = "mpegts,mov,mp4,m4a,3gp,3g2,mj2,matroska,webm,aac,ac3,eac3,mp3,flac,ogg,asf,concat"; +const BLOCK: u64 = 1 << 20; + +/// Gone with everything in it when dropped. +struct Sockets { + dir: PathBuf, + serving: JoinSet<()>, + next: u32, +} + +impl Sockets { + fn new() -> io::Result { + static NEXT: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|d| d.is_dir()).unwrap_or_else(std::env::temp_dir); + loop { + let name = format!("medlar-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)); + let dir = base.join(name); + match std::fs::DirBuilder::new().mode(0o700).create(&dir) { + Ok(()) => return Ok(Sockets { dir, serving: JoinSet::new(), next: 0 }), + // Left by one that was killed, with the same number. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + } + + /// The address of a socket that gives out what `pieces` say, once. + fn serve(&mut self, what: Served) -> Result { + let path = self.dir.join(self.next.to_string()); + self.next += 1; + let listener = UnixListener::bind(&path).map_err(disk_error)?; + self.serving.spawn(async move { + let Ok((mut to, _)) = listener.accept().await else { return }; + let sent = match what { + Served::Text(text) => to.write_all(text.as_bytes()).await.map_err(disk_error), + Served::Pieces(file, pieces) => send(&file, &pieces, &mut to).await, + }; + if let Err(e) = sent { + log::debug!("joining: {e:?}"); + } + let _ = to.shutdown().await; + }); + Ok(format!("unix:{}", path.display())) + } +} + +impl Drop for Sockets { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +enum Served { + Text(String), + Pieces(Arc, Vec), +} + +async fn send(file: &PartialFile, pieces: &[Record], to: &mut (impl AsyncWriteExt + Unpin)) -> Result<()> { + for p in pieces { + let mut at = p.at; + while at < p.at + p.len { + let n = BLOCK.min(p.at + p.len - at); + to.write_all(&file.read_at(n as usize, at).await?).await.map_err(disk_error)?; + at += n; + } + } + Ok(()) +} + +/// ffmpeg's name for the format a file name asks for. +pub(super) fn muxer(ext: &str) -> Option<&'static str> { + Some(match ext.to_ascii_lowercase().as_str() { + "mp4" | "m4v" => "mp4", + "m4a" => "ipod", + "mkv" | "mka" => "matroska", + "webm" => "webm", + "mov" => "mov", + "ts" => "mpegts", + _ => return None, + }) +} + +/// What holds anything. +pub(super) const ANYTHING: &str = "matroska"; + +/// Writes `to`, in the format of `muxer` or, where that can't hold it, in `ANYTHING`. Nothing is left there when it fails. +pub(super) async fn join(ffmpeg: &Path, tape: &Tape, muxer: &str, to: &Path, stop: &mut Stop) -> Result<()> { + let mut result = once(ffmpeg, tape, muxer, to, stop).await; + if muxer != ANYTHING && matches!(result, Err(Error::Conn { kind: ErrorKind::Media, .. })) { + log::debug!("{muxer} can't hold it"); + result = once(ffmpeg, tape, ANYTHING, to, stop).await; + } + if result.is_err() { + let _ = std::fs::remove_file(to); + } + result +} + +async fn once(ffmpeg: &Path, tape: &Tape, muxer: &str, to: &Path, stop: &mut Stop) -> Result<()> { + let mut sockets = Sockets::new().map_err(disk_error)?; + let tracks: Vec>> = (0..tape.head.tracks.len() as u32).map(|t| tape.groups(t)).filter(|g| !g.is_empty()).collect(); + if tracks.is_empty() { + return Err(Error::because(ErrorKind::Media, "error.media.empty")); + } + let single = tracks.iter().all(|groups| groups.len() == 1); + let mut job = Job::new(); + for (i, groups) in tracks.iter().enumerate() { + let mut addresses = vec![]; + for group in groups { + addresses.push(sockets.serve(Served::Pieces(tape.file.clone(), group.clone()))?); + } + // Their clocks are the same one. + if i > 0 && single { + job.args(["-isync", "0"]); + } + job.args(["-format_whitelist", FORMATS]); + match &addresses[..] { + [one] => job.input("unix", one), + many => { + let list = many.iter().map(|a| format!("file '{a}'\n")).collect::(); + let list = sockets.serve(Served::Text(format!("ffconcat version 1.0\n{list}")))?; + job.args(["-f", "concat", "-safe", "0"]).input("unix", list) + } + }; + } + match tracks.len() { + 1 => job.args(["-map", "0:v?", "-map", "0:a?"]), + _ => job.args(["-map", "0:v?", "-map", "1:a?"]), + }; + job.args(["-c", "copy"]).file(muxer, to); + let mut running = job.start(ffmpeg)?; + ended(&mut running, stop).await?; + let to = to.to_path_buf(); + blocking(move || std::fs::File::open(to).and_then(|f| f.sync_all()).map_err(disk_error)).await +} + +async fn ended(running: &mut Running, stop: &mut Stop) -> Result<()> { + tokio::select! { + biased; + _ = stopped(stop) => Err(Error::Stopped), + end = running.end() => end?.map_err(|failed| failed.error()), + } +} diff --git a/crates/core/src/stream/list.rs b/crates/core/src/stream/list.rs new file mode 100644 index 0000000..317a381 --- /dev/null +++ b/crates/core/src/stream/list.rs @@ -0,0 +1,156 @@ +//! What lists of streams have in common. + +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Kind { + Hls, + Dash, + Rtsp, + Mms, +} + +/// What can be downloaded from a link. +#[derive(Debug, Clone)] +pub struct Found { + pub kind: Kind, + /// Goes on until it is stopped. + pub live: bool, + /// Seconds. + pub duration: Option, + /// Best first. With sound in them, unless they name their `sound`. + pub videos: Vec, + /// Sound that comes on its own. Best first. + pub audios: Vec, +} + +/// One quality or language. +#[derive(Debug, Clone, PartialEq)] +pub struct Variant { + /// Stays the same when the list is read again. + pub id: String, + /// Bits per second. + pub bandwidth: u64, + pub size: Option<(u32, u32)>, + pub codecs: String, + pub language: Option, + pub name: Option, + /// The group of `audios` that goes with it, or the one it is in. + pub sound: Option, + /// The one to take when none is asked for. + pub preferred: bool, + /// Where its own list is (HLS). + pub(super) url: Option, +} + +impl Variant { + pub(super) fn new(id: String) -> Variant { + Variant { id, bandwidth: 0, size: None, codecs: String::new(), language: None, name: None, sound: None, preferred: false, url: None } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Pick { + #[default] + Best, + None, + /// `Variant::id` + One(String), +} + +/// What the user chose of a stream. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Choice { + pub video: Pick, + pub audio: Pick, + /// The best that is no higher, for `Pick::Best`. + pub max_height: Option, + /// A recording ends by itself after so many seconds or bytes. + pub seconds: Option, + pub bytes: Option, +} + +impl Found { + /// What to download. None when the choice doesn't fit, or there is nothing. + pub(super) fn pick(&self, choice: &Choice) -> Option> { + let by_id = |from: &[Variant], id: &str| from.iter().find(|v| v.id == id).cloned(); + let video = match &choice.video { + Pick::None => None, + Pick::One(id) => Some(by_id(&self.videos, id)?), + Pick::Best => { + let fits = |v: &&Variant| choice.max_height.is_none_or(|max| v.size.is_none_or(|(_, h)| h <= max)); + self.videos.iter().find(fits).or(self.videos.last()).cloned() + } + }; + let audio = match &choice.audio { + Pick::None => None, + Pick::One(id) => Some(by_id(&self.audios, id)?), + Pick::Best => { + let group = video.as_ref().and_then(|v| v.sound.as_ref()); + // A video that names no group has its sound in it, unless there is none of it (DASH). + let apart = self.kind == Kind::Dash || video.is_none(); + let fits = |a: &&Variant| apart || (group.is_some() && a.sound.as_ref() == group); + let best = self.audios.iter().filter(fits); + best.clone().find(|a| a.preferred).or(best.clone().next()).cloned() + } + }; + let picked: Vec = video.into_iter().chain(audio).collect(); + (!picked.is_empty()).then_some(picked) + } +} + +/// A piece of a file, or all of it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Piece { + pub url: Url, + /// First byte and the one after the last. + pub range: Option<(u64, u64)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Key { + pub url: Url, + pub iv: [u8; 16], +} + +#[derive(Debug, Clone, PartialEq)] +pub(super) struct Segment { + /// Pieces with the same one can be put together as they are. + pub stretch: u64, + pub seq: u64, + /// The `seq` of the one after it. + pub next: u64, + pub seconds: f64, + pub piece: Piece, + pub key: Option, + /// Comes before all others of the stretch. + pub init: Option, + pub init_key: Option, +} + +/// One variant, as its list is now. +#[derive(Debug, Clone, Default)] +pub(super) struct Media { + pub segments: Vec, + /// There will be no more. + pub ended: bool, + /// All since the start, though it goes on. + pub from_start: bool, + /// Seconds between two looks. + pub pace: f64, + /// All of it is in one file. + pub whole: Option, +} + +/// Lists may lead to the web only. +pub(super) fn web(base: &Url, link: &str) -> Option { + let url = base.join(link.trim()).ok()?; + (matches!(url.scheme(), "http" | "https") && url.has_host()).then_some(url) +} + +/// Best first: the higher picture, then more bits. +pub(super) fn sort(variants: &mut [Variant]) { + variants.sort_by_key(|v| std::cmp::Reverse((v.size.map_or(0, |(_, h)| h), v.bandwidth))); +} diff --git a/crates/core/src/stream/mod.rs b/crates/core/src/stream/mod.rs new file mode 100644 index 0000000..c11fb00 --- /dev/null +++ b/crates/core/src/stream/mod.rs @@ -0,0 +1,507 @@ +//! Streams: HLS and DASH in pieces that are joined, RTSP and MMS recorded through ffmpeg. Nothing is converted. +//! +//! Copy protection is recognised and refused. The only keys used are those a list hands to everyone (AES-128). + +mod dash; +pub mod ffmpeg; +mod fetch; +mod hls; +mod join; +mod list; +mod record; +mod tape; + +pub use ffmpeg::Tools; +pub use list::{Choice, Found, Kind, Pick, Variant}; + +use crate::disk::{self, PartialFile, blocking}; +use crate::http::{Client, Error, Monitor, Options, PartState, PartView, Result, Shared, Snapshot, Source, Stop, safe_name, stopped}; +use crate::model::{ErrorKind, Part, Task, TaskId}; +use crate::store::Store; +use fetch::{Feed, Net, Want}; +use list::Media; +use std::collections::VecDeque; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use tape::{Head, Tape, Track}; +use tokio::task::JoinSet; +use tokio::time::Instant; +use url::Url; + +/// Pieces that are downloaded at once. +const PARALLEL: u32 = 4; +/// Ending of what ffmpeg is making, after that of the unfinished file. +const JOINING: &str = ".join"; + +fn odd(what: &str) -> Error { + Error::BadReply(format!("stream: {what}")) +} + +fn drm() -> Error { + Error::conn(ErrorKind::Drm) +} + +fn disk_error(e: io::Error) -> Error { + Error::Disk(e.into()) +} + +/// Links that ffmpeg has to open. +pub(crate) fn recorded(url: &Url) -> bool { + matches!(url.scheme(), "rtsp" | "mms" | "mmsh" | "mmst") +} + +/// What kind of stream a link is, if it is one. `mime` is what the server called it, if that is known. +pub fn kind(url: &Url, mime: Option<&str>) -> Option { + if recorded(url) { + return Some(if url.scheme() == "rtsp" { Kind::Rtsp } else { Kind::Mms }); + } + if !matches!(url.scheme(), "http" | "https") { + return None; + } + let path = url.path().to_ascii_lowercase(); + match mime.map(str::to_ascii_lowercase).as_deref() { + Some("application/vnd.apple.mpegurl" | "application/x-mpegurl" | "audio/mpegurl" | "audio/x-mpegurl") if !path.ends_with(".m3u") => Some(Kind::Hls), + Some("application/dash+xml") => Some(Kind::Dash), + _ if path.ends_with(".m3u8") => Some(Kind::Hls), + _ if path.ends_with(".mpd") => Some(Kind::Dash), + _ => None, + } +} + +/// Of a task, as far as it is known. +pub fn kind_of(task: &Task) -> Option { + kind(&Url::parse(&task.url).ok()?, task.mime.as_deref()) +} + +/// What there is to choose from. Nothing is known of a stream that ffmpeg has to open. +pub async fn probe(client: &Client, source: &Source, stop: &mut Stop) -> Result { + if let Some(kind) = kind(&source.url, None).filter(|k| matches!(k, Kind::Rtsp | Kind::Mms)) { + return Ok(Found { kind, live: true, duration: None, videos: vec![], audios: vec![] }); + } + let net = Net::plain(client, source); + let mut opened = net.open(stop).await?; + // A master list doesn't say whether what it leads to goes on. + if opened.found.kind == Kind::Hls && opened.media.is_none() { + let first = opened.found.videos.first().cloned().ok_or_else(|| odd("no variants"))?; + opened.media = net.refresh(&None, &[first], stop).await?.pop(); + } + if let Some(media) = &opened.media { + opened.found.live = !media.ended; + opened.found.duration = media.ended.then(|| media.segments.iter().map(|s| s.seconds).sum()); + } + Ok(opened.found) +} + +/// What a download of a stream needs to know. +pub struct Request<'a> { + pub id: TaskId, + pub source: Source, + pub choice: Choice, + pub tools: &'a Tools, + pub options: &'a Options, +} + +/// Starts or continues the task and returns the finished file. Doesn't touch the task's state. A stream that goes on ends with +/// `monitor.finish`, or at the limits of the choice; stopping it keeps what is there, to go on later. +pub async fn download(shared: &Shared, request: Request<'_>, monitor: &Monitor, mut stop: Stop) -> Result { + let Request { id, source, choice, tools, options } = request; + let ffmpeg = tools.ffmpeg()?.to_path_buf(); + let store = &shared.store; + let (task, parts) = run(store, move |s| Ok((s.task(id)?, s.parts(id)?))).await?; + let partial = { + let (folder, name) = (task.folder.clone(), task.name.clone()); + let begun = !parts.is_empty(); + blocking(move || if begun { PartialFile::reopen(&folder, &name) } else { Ok(None) }).await? + }; + let done: u64 = parts.iter().map(|p| p.done).sum(); + let mut tape = None; + let mut empty = None; + match partial { + Some(file) if Tape::is(&file).await? => { + let file = Arc::new(file); + match Tape::open(file.clone(), done).await? { + Some(found) => tape = Some(found), + // Killed before anything of it was safe. + None if done == 0 => empty = Some(file), + None => return Err(Error::Changed), + } + } + Some(file) if done == 0 && file.size()? == 0 => empty = Some(Arc::new(file)), + // Joined already, and then interrupted. + Some(file) if file.size()? > 0 => return finish(store, id, file).await, + Some(_) => return Err(Error::Missing), + None if done > 0 => { + let path = task.folder.join(&task.name); + let whole = parts.iter().all(|p| p.end == Some(p.start + p.done)); + if whole && path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == done) { + return Ok(path); + } + return Err(Error::Missing); + } + None => {} + } + + let mut meter = Meter::new(store.clone(), id, options); + let finishing = *monitor.finishing().borrow(); + let kind = kind_of(&task).unwrap_or(Kind::Hls); + let mut job = Work { shared, task: &task, options, choice: &choice, monitor, ffmpeg: &ffmpeg }; + let mut tape = match tape { + // The user wants what there is. + Some(tape) if finishing && tape.head.live && !tape.records.is_empty() => tape, + tape if matches!(kind, Kind::Rtsp | Kind::Mms) => { + let mut tape = match tape { + Some(tape) => tape, + None => job.create(empty, Head { live: true, tracks: vec![Track { id: String::new(), total: None }] }, &source.url, false).await?, + }; + let result = record::record(&ffmpeg, &shared.client, &source, &choice, &mut tape, &mut meter, monitor, &mut stop).await; + meter.save(&tape).await?; + result?; + tape + } + tape => { + let net = Arc::new(Net::new(shared, &source, options, monitor, meter.received.clone())); + job.pieces(net, tape, empty, &mut meter, &mut stop).await? + } + }; + meter.save(&tape).await?; + let file = job.join(&mut tape, &mut stop).await?; + drop(tape); + finish(store, id, file).await +} + +async fn run(store: &Arc, work: impl FnOnce(&Store) -> Result + Send + 'static) -> Result { + let store = store.clone(); + blocking(move || work(&store)).await +} + +/// Gives a joined file its name. +async fn finish(store: &Arc, id: TaskId, file: PartialFile) -> Result { + let matroska = file.read_at(4, 0).await.is_ok_and(|start| start == [0x1a, 0x45, 0xdf, 0xa3]); + run(store, move |store| { + let size = file.size()?; + store.save_parts(id, vec![Part { start: 0, end: Some(size), done: size }])?; + let task = store.task(id)?; + let (stem, ext) = crate::http::name::split(&task.name); + // The format that was asked for could not hold it. + let name = match ext { + Some(ext) if matroska && !matches!(join::muxer(ext), Some(join::ANYTHING | "webm")) => format!("{stem}.mkv"), + _ => task.name.clone(), + }; + file.finish(&name, size, |name| { + let name = name.to_string(); + store.edit_task(id, move |task| (task.name, task.size) = (name, Some(size)))?; + Ok(()) + }) + }) + .await +} + +struct Work<'a> { + shared: &'a Shared, + task: &'a Task, + options: &'a Options, + choice: &'a Choice, + monitor: &'a Monitor, + ffmpeg: &'a Path, +} + +impl Work<'_> { + /// A new tape, under a free name. + async fn create(&self, empty: Option>, head: Head, url: &Url, sound: bool) -> Result { + let file = match empty { + Some(file) => { + file.clear()?; + file + } + None => { + let wanted = name(&self.task.name, url, if sound { "m4a" } else { "mp4" }); + let (id, folder) = (self.task.id, self.task.folder.clone()); + let file = run(&self.shared.store, move |store| { + let _names = disk::names(); + let (file, name) = PartialFile::create(&folder, &wanted, &store.used_names(&folder, id)?)?; + store.edit_task(id, move |task| task.name = name)?; + store.save_parts(id, vec![Part { start: 0, end: None, done: 0 }])?; + Ok(file) + }); + Arc::new(file.await?) + } + }; + Tape::create(file, head).await + } + + /// Downloads the pieces of a list, until it ends or is told to. + async fn pieces(&mut self, net: Arc, tape: Option, empty: Option>, meter: &mut Meter, stop: &mut Stop) -> Result { + let opened = net.open(stop).await?; + let picked = opened.found.pick(self.choice).ok_or(Error::because(ErrorKind::Media, "error.media.choice"))?; + let sound = !picked.iter().any(|p| opened.found.videos.contains(p)); + let is_master = opened.media.is_none() && opened.manifest.is_none(); + let root = if is_master { None } else { Some(opened.found.kind) }; + let mut media = match (&opened.manifest, opened.media) { + (Some(manifest), _) => picked.iter().map(|v| manifest.media(v, fetch::now())).collect::>>()?, + (None, Some(media)) => vec![media], + (None, None) => net.refresh(&root, &picked, stop).await?, + }; + for m in &mut media { + net.split(m, stop).await?; + } + let live = media.iter().any(|m| !m.ended); + if media.iter().any(|m| m.segments.is_empty()) && !live { + return Err(odd("no segments")); + } + let total = |m: &Media| (!live).then_some(m.segments.len() as u64); + let head = Head { live, tracks: picked.iter().zip(&media).map(|(v, m)| Track { id: v.id.clone(), total: total(m) }).collect() }; + let mut tape = match tape { + Some(tape) => { + // A recording may have ended meanwhile. + let same = if tape.head.live { tape.head.tracks.iter().map(|t| &t.id).eq(head.tracks.iter().map(|t| &t.id)) } else { tape.head == head }; + if !same { + return Err(Error::Changed); + } + tape + } + None => self.create(empty, head, &net.source.url, sound).await?, + }; + let live = tape.head.live; + meter.whole = (!live).then(|| media.iter().flat_map(|m| &m.segments).map(|s| (s.seconds * 1000.0) as u64).sum()); + let mut feeds: Vec = (0..picked.len() as u32).map(|track| Feed::new(track, &tape, self.choice.seconds)).collect(); + let mut queue: VecDeque = VecDeque::new(); + let mut ended = add(&mut feeds, &media, live, &mut queue); + // Picture and sound side by side. + queue.make_contiguous().sort_by_key(|w| w.place); + let (mut running, mut lists) = (JoinSet::new(), JoinSet::new()); + let mut finish = self.monitor.finishing(); + let cap = self.monitor.cap(); + let (mut failed, mut silent) = (None, 0); + let mut pace = wait_of(&media, false); + let mut look = Instant::now() + pace; + loop { + let full = live && self.choice.bytes.is_some_and(|most| tape.end >= most); + if failed.is_some() || full { + queue.clear(); + } + ended |= full; + let width = (*cap.borrow()).min(net.width()).min(self.monitor.flow().connections()).max(1) as usize; + while running.len() < width && let Some(want) = queue.pop_front() { + let (net, mut stop) = (net.clone(), stop.clone()); + running.spawn(async move { + let got = net.piece(&want, &mut stop).await; + (want, got) + }); + } + if running.is_empty() && queue.is_empty() { + if ended || failed.is_some() { + break; + } + net.rest(); + } + if live && !ended && failed.is_none() && lists.is_empty() && Instant::now() >= look { + let (net, picked, mut stop) = (net.clone(), picked.clone(), stop.clone()); + lists.spawn(async move { net.refresh(&root, &picked, &mut stop).await }); + } + tokio::select! { + biased; + _ = stopped(stop) => { + failed = Some(Error::Stopped); + break; + } + _ = stopped(&mut finish), if live && !ended => { + ended = true; + queue.clear(); + } + Some(got) = running.join_next() => match got { + Ok((want, Ok(data))) => tape.append(want.record, &data).await?, + // It is gone already, the rest goes on. + Ok((_, Err(Error::Status { code: 404 | 410, .. }))) if live => {} + Ok((_, Err(e))) => failed = failed.or(Some(e)), + Err(e) => std::panic::resume_unwind(e.into_panic()), + }, + Some(list) = lists.join_next() => match list { + Ok(Ok(now)) => { + silent = 0; + let changed = now.iter().zip(&media).any(|(a, b)| a.segments.last() != b.segments.last()); + media = now; + pace = wait_of(&media, !changed); + ended |= add(&mut feeds, &media, live, &mut queue); + look = Instant::now() + pace; + } + Ok(Err(Error::Stopped)) => {} + // The end of many. + Ok(Err(Error::Status { code: 404 | 410, .. })) if !tape.records.is_empty() => ended = true, + Ok(Err(e)) => { + silent += 1; + if silent >= self.options.tries || !fetch::passing(&e) { + failed = failed.or(Some(e)); + } + look = Instant::now() + pace; + } + Err(e) => std::panic::resume_unwind(e.into_panic()), + }, + _ = tokio::time::sleep(meter.tick()) => {} + } + meter.look(&tape, running.len() as u32, self.monitor).await?; + } + // Ends the requests, not what is on the tape. + running.shutdown().await; + meter.save(&tape).await?; + meter.show(&tape, 0, self.monitor); + match failed { + Some(e) => Err(e), + None => Ok(tape), + } + } + + /// The joined file takes the place of the tape. + async fn join(&self, tape: &mut Tape, stop: &mut Stop) -> Result { + let from = tape.file.path().to_path_buf(); + let mut to = from.clone().into_os_string(); + to.push(JOINING); + let to = PathBuf::from(to); + let ext = self.shared.store.task(self.task.id)?.name; + let muxer = crate::http::name::split(&ext).1.and_then(join::muxer).unwrap_or(join::ANYTHING); + join::join(self.ffmpeg, tape, muxer, &to, stop).await?; + blocking(move || { + std::fs::rename(&to, &from).map_err(disk_error)?; + PartialFile::hold(from)?.ok_or(Error::Missing) + }) + .await + } +} + +/// Puts what is new in the queue. True when there will be no more. +fn add(feeds: &mut [Feed], media: &[Media], live: bool, queue: &mut VecDeque) -> bool { + let mut over = true; + for (feed, media) in feeds.iter_mut().zip(media) { + feed.take(media, live, queue); + over &= media.ended || feed.full(); + } + over +} + +/// Until the next look at lists that grow. +fn wait_of(media: &[Media], same: bool) -> Duration { + let pace = media.iter().map(|m| m.pace).fold(60.0, f64::min); + Duration::from_secs_f64(if same { pace / 2.0 } else { pace }) +} + +/// Names that say nothing. +const PLAIN: &[&str] = &["master", "index", "playlist", "manifest", "chunklist", "main", "stream", "live", "video", "prog_index", "media"]; + +/// The name for a stream without one, with an ending for what it becomes. +fn name(given: &str, url: &Url, ext: &str) -> String { + let given = safe_name(given).filter(|n| !n.is_empty()); + let mut words: Vec = url.path_segments().into_iter().flatten().rev().filter_map(decoded).collect(); + words.extend(url.host_str().and_then(safe_name)); + let stem = |n: &str| n.rsplit_once('.').filter(|(s, e)| !s.is_empty() && matches!(e.to_ascii_lowercase().as_str(), "m3u8" | "m3u" | "mpd" | "sdp")).map_or(n.to_string(), |(s, _)| s.to_string()); + let telling = words.iter().map(|w| stem(w)).find(|w| !PLAIN.contains(&w.to_ascii_lowercase().as_str())); + let name = given.map(|n| stem(&n)).filter(|n| !PLAIN.contains(&n.to_ascii_lowercase().as_str())).or(telling).unwrap_or_else(|| "stream".into()); + match crate::http::name::split(&name).1.and_then(join::muxer) { + Some(_) => name, + None => safe_name(&format!("{name}.{ext}")).unwrap_or_else(|| format!("stream.{ext}")), + } +} + +fn decoded(segment: &str) -> Option { + safe_name(&percent_encoding::percent_decode_str(segment).decode_utf8_lossy()) +} + +/// What others see of it, and what is safe on disk. +struct Meter { + store: Arc, + id: TaskId, + received: Arc, + /// Milliseconds of all tracks, when that is known. + whole: Option, + tick: Duration, + checkpoint: Duration, + saved: (u64, Instant), + shown: (u64, Instant), + speed: f64, +} + +impl Meter { + fn new(store: Arc, id: TaskId, options: &Options) -> Meter { + let now = Instant::now(); + let (tick, checkpoint) = (options.tick, options.checkpoint); + Meter { store, id, received: Arc::default(), whole: None, tick, checkpoint, saved: (0, now), shown: (0, now), speed: 0.0 } + } + + fn tick(&self) -> Duration { + self.tick + } + + fn came(&self, n: u64) { + self.received.fetch_add(n, Ordering::Relaxed); + } + + async fn look(&mut self, tape: &Tape, connections: u32, monitor: &Monitor) -> Result<()> { + if self.shown.1.elapsed() >= self.tick { + self.show(tape, connections, monitor); + } + if self.saved.1.elapsed() >= self.checkpoint { + self.save(tape).await?; + } + Ok(()) + } + + fn show(&mut self, tape: &Tape, connections: u32, monitor: &Monitor) { + let received = self.received.load(Ordering::Relaxed); + let dt = self.shown.1.elapsed().as_secs_f64().max(0.001); + let now = received.saturating_sub(self.shown.0) as f64 / dt; + self.speed = self.speed * 0.7 + now * 0.3; + self.shown = (received, Instant::now()); + // Its size is a guess from how long it is, so that there is something to show. + let here: u64 = tape.records.iter().map(|r| u64::from(r.ms)).sum(); + let size = self.whole.filter(|_| here > 0).map(|whole| (tape.end as f64 * (whole as f64 / here as f64).max(1.0)) as u64); + let state = if connections > 0 { PartState::Running } else { PartState::Waiting }; + let part = PartView { id: 0, start: 0, end: size, done: tape.end, state, speed: self.speed, fails: 0 }; + let shot = Snapshot { size, parts: vec![part], connections, wanted: connections, received, speed: self.speed, ..Default::default() }; + monitor.publish(shot, vec![], std::iter::empty()); + } + + /// Data first, then the record of it. + async fn save(&mut self, tape: &Tape) -> Result<()> { + let (end, file, id) = (tape.end, tape.file.clone(), self.id); + if self.saved.0 != end { + run(&self.store, move |store| { + file.sync()?; + Ok(store.save_parts(id, vec![Part { start: 0, end: None, done: end }])?) + }) + .await?; + } + self.saved = (end, Instant::now()); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kinds() { + let of = |url: &str, mime| kind(&Url::parse(url).unwrap(), mime); + assert_eq!(of("https://h/a/Master.M3U8?x=1", None), Some(Kind::Hls)); + assert_eq!(of("https://h/a", Some("application/vnd.apple.mpegURL")), Some(Kind::Hls)); + assert_eq!(of("https://h/a.mpd", None), Some(Kind::Dash)); + assert_eq!(of("rtsp://h/a", None), Some(Kind::Rtsp)); + assert_eq!(of("mms://h/a.wmv", None), Some(Kind::Mms)); + for (url, mime) in [("https://h/songs.m3u", Some("audio/x-mpegurl")), ("https://h/a.mp4", Some("video/mp4")), ("ftp://h/a.m3u8", None)] { + assert_eq!(of(url, mime), None, "{url}"); + } + } + + #[test] + fn names() { + let of = |given: &str, url: &str| name(given, &Url::parse(url).unwrap(), "mp4"); + assert_eq!(of("", "https://h/my%20film/master.m3u8?t=1"), "my film.mp4"); + assert_eq!(of("", "https://h/film.m3u8"), "film.mp4"); + assert_eq!(of("", "https://h.org/index.m3u8"), "h.org.mp4"); + assert_eq!(of("index.m3u8", "https://h.org/a/index.m3u8"), "a.mp4"); + assert_eq!(of("Mine.mkv", "https://h/x.m3u8"), "Mine.mkv"); + assert_eq!(of("Part 1.5", "https://h/x.m3u8"), "Part 1.5.mp4"); + assert_eq!(of("../../x", "rtsp://h/cam"), "x.mp4"); + } +} diff --git a/crates/core/src/stream/record.rs b/crates/core/src/stream/record.rs new file mode 100644 index 0000000..be46fac --- /dev/null +++ b/crates/core/src/stream/record.rs @@ -0,0 +1,223 @@ +//! Streams that ffmpeg has to receive itself: RTSP and MMS. + +use super::ffmpeg::Job; +use super::list::Choice; +use super::tape::{Record, Tape}; +use super::{Meter, disk_error, odd}; +use crate::auth::Login; +use crate::http::{Error, Monitor, Result, Source, Stop, Client, stopped}; +use crate::model::ErrorKind; +use std::path::Path; +use std::time::Duration; +use tokio::io::AsyncReadExt; +use tokio::time::{Instant, timeout}; +use url::Url; + +/// What ffmpeg writes is kept in pieces of this size, or of a second. +const PIECE: usize = 256 << 10; +const EVERY: Duration = Duration::from_secs(1); +/// Nothing comes for so long: the stream is gone. +const SILENCE: Duration = Duration::from_secs(20); +/// For ffmpeg to end properly when the download is paused. +const GRACE: Duration = Duration::from_millis(800); + +/// Where to ask, in this order. +fn addresses(url: &Url) -> Vec<(String, &'static str)> { + let with = |scheme: &str| format!("{scheme}{}", &url.as_str()[url.scheme().len()..]); + let (http, tcp) = ((with("mmsh"), "mmsh,http,tcp"), (with("mmst"), "mmst,tcp")); + match url.scheme() { + "rtsp" => vec![(url.to_string(), "rtsp,rtp,udp,tcp")], + "mmsh" => vec![http], + "mmst" => vec![tcp], + // The old name for both. Its own port is that of the second. + _ if url.port() == Some(1755) => vec![tcp, http], + _ => vec![http, tcp], + } +} + +/// A login must not be among the arguments, where everyone can read them. +fn input(job: &mut Job, address: &str, protocols: &str, login: Option<&Login>) -> Result<()> { + let wait = &SILENCE.as_micros().to_string()[..]; + let options = if address.starts_with("rtsp:") { &[("rtsp_flags", "prefer_tcp"), ("timeout", wait)][..] } else { &[] }; + let Some(login) = login else { + for (name, value) in options { + job.arg(format!("-{name}")).arg(value); + } + job.input(protocols, address); + return Ok(()); + }; + let encode = |text: &str| percent_encoding::utf8_percent_encode(text, percent_encoding::NON_ALPHANUMERIC).to_string(); + let (scheme, rest) = address.split_once("://").ok_or(Error::Link)?; + let with = format!("{scheme}://{}:{}@{rest}", encode(&login.user), encode(&login.password)).replace('\'', r"'\''"); + if with.contains(['\n', '\r']) { + return Err(Error::Link); + } + let options: String = options.iter().map(|(name, value)| format!("option {name} {value}\n")).collect(); + job.args(["-f", "concat", "-safe", "0"]).input(&format!("pipe,{protocols}"), "pipe:0"); + job.stdin(format!("ffconcat version 1.0\nfile '{with}'\n{options}")); + Ok(()) +} + +/// Adds to the tape until the stream ends, a limit is reached or `monitor.finish` is called. +#[allow(clippy::too_many_arguments)] +pub(super) async fn record( + ffmpeg: &Path, + client: &Client, + source: &Source, + choice: &Choice, + tape: &mut Tape, + meter: &mut Meter, + monitor: &Monitor, + stop: &mut Stop, +) -> Result<()> { + let way = tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + way = source.way(client) => way?, + }; + // Straight to the server would show it who asks. + if way.proxy.is_some() { + return Err(Error::because(ErrorKind::Proxy, "error.proxy.stream")); + } + let had = tape.records.len(); + let mut first = None; + for (address, protocols) in addresses(&source.url) { + let mut job = Job::new(); + input(&mut job, &address, protocols, way.login.as_ref())?; + let result = run(ffmpeg, job, choice, tape, meter, monitor, stop).await; + use ErrorKind::{Login, Dns, Tool}; + let other_way = match &result { + Err(Error::Conn { kind, .. }) => !matches!(kind, Login | Dns | Tool), + Err(Error::Idle) => true, + _ => false, + }; + if !other_way || tape.records.len() > had { + return result; + } + first = first.or(result.err()); + } + Err(first.unwrap_or(Error::Link)) +} + +async fn run(ffmpeg: &Path, mut job: Job, choice: &Choice, tape: &mut Tape, meter: &mut Meter, monitor: &Monitor, stop: &mut Stop) -> Result<()> { + let had = tape.length(0); + let full = |tape: &Tape| choice.bytes.is_some_and(|most| tape.records.iter().map(|r| r.len).sum::() >= most); + if let Some(seconds) = choice.seconds { + let left = (seconds * 1000).saturating_sub(had); + if left == 0 { + return Ok(()); + } + job.args(["-t", &format!("{}ms", left)]); + } + if full(tape) { + return Ok(()); + } + job.args(["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-flush_packets", "1"]).pipe("matroska"); + let mut running = job.start(ffmpeg)?; + let mut output = running.output.take().ok_or_else(|| odd("no output"))?; + let group = tape.records.iter().map(|r| r.group + 1).max().unwrap_or(0); + let progress = running.progress(); + let mut finish = monitor.finishing(); + let (mut seq, mut ms, mut buf) = (0u64, 0u64, Vec::with_capacity(PIECE)); + let (mut asked, mut paused, mut since, mut came) = (false, false, Instant::now(), Instant::now()); + let mut kill_at = None; + loop { + let mut chunk = [0; 16 << 10]; + let read = tokio::select! { + biased; + _ = stopped(stop), if !paused => { + paused = true; + running.finish(); + kill_at = Some(Instant::now() + GRACE); + None + } + _ = stopped(&mut finish), if !asked && !paused => { + asked = true; + running.finish(); + kill_at = Some(Instant::now() + SILENCE); + None + } + n = output.read(&mut chunk) => Some(n.map_err(disk_error)?), + _ = tokio::time::sleep(meter.tick()) => None, + }; + if let Some(n) = read { + let mut rest = &chunk[..n]; + while !rest.is_empty() { + // What is here is kept, whatever the limits say. + let n = tokio::select! { + biased; + _ = stopped(stop), if !paused => rest.len(), + n = monitor.flow().take(rest.len() as u64) => n as usize, + }; + buf.extend_from_slice(&rest[..n]); + meter.came(n as u64); + rest = &rest[n..]; + } + came = Instant::now(); + } + let over = read == Some(0); + if !buf.is_empty() && (over || buf.len() >= PIECE || since.elapsed() >= EVERY) { + let now = progress.borrow().time.as_millis() as u64; + // The end of the last report comes late. + let record = Record { track: 0, group, init: false, stretch: u64::from(group), seq, ms: now.saturating_sub(ms) as u32, at: 0, len: 0 }; + tape.append(record, &buf).await?; + (seq, ms, since) = (seq + 1, ms.max(now), Instant::now()); + buf.clear(); + if full(tape) && !asked && !paused { + asked = true; + running.finish(); + kill_at = Some(Instant::now() + SILENCE); + } + } + meter.look(tape, 1, monitor).await?; + if over { + break; + } + let late = kill_at.is_some_and(|at| Instant::now() >= at); + if late || (!asked && !paused && came.elapsed() > SILENCE + EVERY) { + running.kill().await; + if !buf.is_empty() { + let record = Record { track: 0, group, init: false, stretch: u64::from(group), seq, ms: 0, at: 0, len: 0 }; + tape.append(record, &buf).await?; + } + return if paused { Err(Error::Stopped) } else if asked { Ok(()) } else { Err(Error::Idle) }; + } + } + let end = timeout(GRACE, running.end()).await; + if paused { + return Err(Error::Stopped); + } + if asked { + return Ok(()); + } + match end { + Ok(Ok(Ok(()))) if seq > 0 => Ok(()), + Ok(Ok(Ok(()))) => Err(Error::because(ErrorKind::Media, "error.media.empty")), + Ok(Ok(Err(failed))) if seq == 0 => Err(failed.error()), + Ok(Err(e)) => Err(disk_error(e)), + _ => Err(Error::Cut { got: tape.end, expected: None }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn where_to_ask() { + let of = |url: &str| addresses(&Url::parse(url).unwrap()).into_iter().map(|a| a.0).collect::>(); + assert_eq!(of("rtsp://h:8554/a?b"), ["rtsp://h:8554/a?b"]); + assert_eq!(of("mms://h/a.wmv"), ["mmsh://h/a.wmv", "mmst://h/a.wmv"]); + assert_eq!(of("mms://h:1755/a"), ["mmst://h:1755/a", "mmsh://h:1755/a"]); + } + + #[test] + fn logins_stay_off_the_arguments() { + let login = Login { user: "me@x".into(), password: "S3CRET'\n".into() }; + let mut job = Job::new(); + input(&mut job, "rtsp://h/it's", "rtsp,tcp", Some(&login)).unwrap(); + let shown = format!("{job:?}"); + let script = String::from_utf8(job.script().unwrap().to_vec()).unwrap(); + assert!(script.contains(r"file 'rtsp://me%40x:S3CRET%27%0A@h/it'\''s'"), "{script}"); + assert!(!shown.contains("S3CRET"), "{shown}"); + } +} diff --git a/crates/core/src/stream/tape.rs b/crates/core/src/stream/tape.rs new file mode 100644 index 0000000..69cff3d --- /dev/null +++ b/crates/core/src/stream/tape.rs @@ -0,0 +1,174 @@ +//! The unfinished file of a stream: what arrived, in the order it arrived, with what belongs where. +//! +//! One file, so that moving, renaming and binning it is the same as for any other download. + +use crate::disk::PartialFile; +use crate::http::Result; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +const MAGIC: &[u8; 8] = b"MedlarS1"; +const RECORD: u64 = 48; +const MARK: u32 = 0x4d64_6c52; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct Head { + pub live: bool, + /// What it is of, to notice when the server has another one now. + pub tracks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct Track { + pub id: String, + /// Segments. None while it grows. + pub total: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Record { + pub track: u32, + /// Put together as they are. + pub group: u32, + pub init: bool, + pub stretch: u64, + pub seq: u64, + /// Length of the recording in it, in milliseconds. + pub ms: u32, + pub at: u64, + pub len: u64, +} + +#[derive(Debug)] +pub(super) struct Tape { + pub file: Arc, + pub head: Head, + pub records: Vec, + /// Where the next one goes. + pub end: u64, +} + +impl Tape { + /// Whether the file is one. An empty one may become one. + pub async fn is(file: &PartialFile) -> Result { + Ok(file.size()? >= MAGIC.len() as u64 && file.read_at(MAGIC.len(), 0).await? == MAGIC) + } + + pub async fn create(file: Arc, head: Head) -> Result { + let text = serde_json::to_vec(&head).expect("plain data"); + let mut buf = MAGIC.to_vec(); + buf.extend((text.len() as u32).to_le_bytes()); + buf.extend(text); + let end = buf.len() as u64; + file.write_at(buf, end as usize, 0).await?; + Ok(Tape { file, head, records: vec![], end }) + } + + /// `safe` is how much of it was safe on disk. What came after may be half there: it is written over. + /// None when even the head is not whole. + pub async fn open(file: Arc, safe: u64) -> Result> { + let safe = safe.min(file.size()?); + let start = MAGIC.len() as u64 + 4; + if safe < start { + return Ok(None); + } + let len = file.read_at(4, start - 4).await?; + let len = u64::from(u32::from_le_bytes(len.try_into().expect("four"))); + if safe < start + len { + return Ok(None); + } + let Ok(head) = serde_json::from_slice(&file.read_at(len as usize, start).await?) else { return Ok(None) }; + let mut tape = Tape { file, head, records: vec![], end: start + len }; + while tape.end + RECORD <= safe { + let bytes = tape.file.read_at(RECORD as usize, tape.end).await?; + let Some(record) = Record::read(&bytes, tape.end + RECORD).filter(|r| r.at.checked_add(r.len).is_some_and(|end| end <= safe)) else { break }; + tape.end = record.at + record.len; + tape.records.push(record); + } + Ok(Some(tape)) + } + + /// `at` and `len` are filled in. + pub async fn append(&mut self, mut record: Record, data: &[u8]) -> Result<()> { + (record.at, record.len) = (self.end + RECORD, data.len() as u64); + let mut buf = record.bytes(); + buf.extend_from_slice(data); + let n = buf.len(); + self.file.write_at(buf, n, self.end).await?; + self.end += n as u64; + self.records.push(record); + Ok(()) + } + + /// The groups of a track, each in order with what comes first at its start. + pub fn groups(&self, track: u32) -> Vec> { + let mut mine: Vec = self.records.iter().copied().filter(|r| r.track == track).collect(); + mine.sort_by_key(|r| (r.group, !r.init, r.seq)); + mine.dedup_by_key(|r| (r.group, r.init, r.seq)); + let groups = mine.chunk_by(|a, b| a.group == b.group).map(<[Record]>::to_vec); + groups.filter(|g| g.iter().any(|r| !r.init)).collect() + } + + /// Milliseconds of the track. + pub fn length(&self, track: u32) -> u64 { + self.records.iter().filter(|r| r.track == track).map(|r| u64::from(r.ms)).sum() + } +} + +impl Record { + fn bytes(&self) -> Vec { + let mut b = Vec::with_capacity(RECORD as usize + self.len as usize); + for n in [MARK, self.track, self.group, u32::from(self.init), self.ms, 0] { + b.extend(n.to_le_bytes()); + } + for n in [self.stretch, self.seq, self.len] { + b.extend(n.to_le_bytes()); + } + b + } + + fn read(b: &[u8], at: u64) -> Option { + let small = |i: usize| u32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().expect("four")); + let big = |i: usize| u64::from_le_bytes(b[24 + i * 8..32 + i * 8].try_into().expect("eight")); + (small(0) == MARK).then(|| Record { track: small(1), group: small(2), init: small(3) == 1, ms: small(4), stretch: big(0), seq: big(1), at, len: big(2) }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + + fn record(track: u32, group: u32, init: bool, seq: u64) -> Record { + Record { track, group, init, stretch: 0, seq, ms: 500, at: 0, len: 0 } + } + + #[tokio::test] + async fn goes_on_after_a_torn_end() { + let dir = tempfile::tempdir().unwrap(); + let (file, name) = PartialFile::create(dir.path(), "a.mp4", &HashSet::new()).unwrap(); + assert!(!Tape::is(&file).await.unwrap()); + let head = Head { live: false, tracks: vec![Track { id: "v".into(), total: Some(3) }] }; + let mut tape = Tape::create(Arc::new(file), head.clone()).await.unwrap(); + for (r, data) in [(record(0, 1, false, 5), "two"), (record(0, 0, false, 1), "one"), (record(0, 0, true, 0), "i"), (record(1, 0, true, 0), "only")] { + tape.append(r, data.as_bytes()).await.unwrap(); + } + let (whole, records) = (tape.end, tape.records.clone()); + tape.append(record(0, 1, false, 6), &[7; 1000]).await.unwrap(); + let end = tape.end; + drop(tape); + let file = Arc::new(PartialFile::reopen(dir.path(), &name).unwrap().unwrap()); + assert!(Tape::is(&file).await.unwrap()); + for safe in [whole, whole + 10, end - 1] { + let tape = Tape::open(file.clone(), safe).await.unwrap().unwrap(); + assert_eq!((tape.end, &tape.records, &tape.head), (whole, &records, &head)); + } + assert!(Tape::open(file.clone(), 5).await.unwrap().is_none()); + let tape = Tape::open(file, end).await.unwrap().unwrap(); + assert_eq!(tape.records.len(), 5); + let order: Vec> = tape.groups(0).iter().map(|g| g.iter().map(|r| (r.init, r.seq)).collect()).collect(); + assert_eq!(order, [vec![(true, 0), (false, 1)], vec![(false, 5), (false, 6)]]); + assert!(tape.groups(1).is_empty()); + assert_eq!(tape.length(0), 2000); + } +} diff --git a/crates/core/tests/stream.rs b/crates/core/tests/stream.rs new file mode 100644 index 0000000..24a94f4 --- /dev/null +++ b/crates/core/tests/stream.rs @@ -0,0 +1,750 @@ +//! Streams: HLS and DASH in pieces, RTSP and MMS through ffmpeg. The fixtures are made by ffmpeg, the results looked at by ffprobe. + +use medlar_core::auth::Login; +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::{ClientOptions, Error, Monitor, Options, Shared, Source, client}; +use medlar_core::model::*; +use medlar_core::net_state::Bus; +use medlar_core::secret::{Secret, Secrets}; +use medlar_core::settings::Settings; +use medlar_core::site::Sites; +use medlar_core::store::Store; +use medlar_core::stream::{self, Choice, Pick, Request, Tools}; +use medlar_testserver::{Faults, TestServer}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::sync::watch; +use tokio::task::JoinHandle; +use tokio::time::sleep; + +type Result = std::result::Result; + +/// Seconds of the fixtures. +const LENGTH: f64 = 6.0; + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +fn ffmpeg(dir: &Path, args: &[&str]) { + let out = Command::new("/usr/bin/ffmpeg").current_dir(dir).args(["-y", "-nostdin", "-loglevel", "error"]).args(args).output().unwrap(); + assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +/// Picture and sound of `LENGTH` seconds. +fn input<'a>(to: &[&'a str]) -> Vec<&'a str> { + let mut args = vec!["-f", "lavfi", "-i", "testsrc=size=160x120:rate=10:duration=6", "-f", "lavfi", "-i", "sine=440:duration=6"]; + args.extend(["-c:v", "libx264", "-preset", "ultrafast", "-g", "10", "-c:a", "aac"]); + args.extend(to); + args +} + +struct Bench { + server: TestServer, + media: PathBuf, + dir: tempfile::TempDir, + shared: Shared, + options: Options, + sites: Option>, +} + +struct Going { + stop: watch::Sender, + monitor: Arc, + work: JoinHandle>, +} + +impl Going { + async fn end(self) -> Result { + tokio::time::timeout(Duration::from_secs(60), self.work).await.expect("it ends").unwrap() + } + + async fn stop(self) { + self.stop.send_replace(true); + assert!(matches!(self.end().await, Err(Error::Stopped))); + } + + /// Bytes that are here. + fn here(&self) -> u64 { + self.monitor.snapshot().parts.iter().map(|p| p.done).sum() + } +} + +impl Bench { + async fn new() -> Bench { + let server = TestServer::start().await; + server.build_media().await.unwrap(); + let media = std::env::temp_dir().join(format!("medlar-testserver-{}-{}", std::process::id(), server.port())); + let dir = tempfile::tempdir().unwrap(); + let shared = Bench::shared(dir.path()); + let options = Options { tick: ms(25), tries: 3, backoff: ms(20), max_wait: ms(1500), checkpoint: ms(50), ..Options::default() }; + Bench { server, media, dir, shared, options, sites: None } + } + + fn shared(dir: &Path) -> Shared { + let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap()); + let client = client(&ClientOptions { idle_timeout: ms(2000), ..ClientOptions::default() }).unwrap(); + Shared { client, store, hosts: Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() }) } + } + + /// Runs ffmpeg where the server has its files. + fn make(&self, to: &[&str]) { + ffmpeg(&self.media, &input(to)); + } + + fn write(&self, name: &str, text: &str) { + // Whole or not at all, as it is read meanwhile. + std::fs::write(self.media.join("new"), text).unwrap(); + std::fs::rename(self.media.join("new"), self.media.join(name)).unwrap(); + } + + fn read(&self, name: &str) -> String { + std::fs::read_to_string(self.media.join(name)).unwrap() + } + + fn url(&self, name: &str) -> String { + self.server.url(&format!("/media/{name}")) + } + + fn add(&self, url: &str, name: &str) -> TaskId { + let task = Task { url: url.into(), name: name.into(), folder: self.dir.path().join("files"), ..Task::default() }; + self.shared.store.add_task(task).unwrap() + } + + async fn go(&self, id: TaskId, choice: Choice) -> Going { + self.go_with(id, choice, Arc::new(Monitor::new(16))).await + } + + async fn go_with(&self, id: TaskId, choice: Choice, monitor: Arc) -> Going { + let task = self.shared.store.task(id).unwrap(); + let source = match &self.sites { + Some(sites) => sites.source(&task).await.unwrap(), + None => Source::new(&task.url).unwrap(), + }; + let (stop, stopped) = watch::channel(false); + let (shared, options, seen) = (self.shared.clone(), self.options.clone(), monitor.clone()); + let work = tokio::spawn(async move { + let request = Request { id, source, choice, tools: &Tools::find(), options: &options }; + stream::download(&shared, request, &seen, stopped).await + }); + Going { stop, monitor, work } + } + + async fn get(&self, name: &str, choice: Choice) -> Result { + let id = self.add(&self.url(name), ""); + self.go(id, choice).await.end().await + } + + /// Nothing is left but the files themselves. + fn clean(&self, files: usize) { + let names: Vec<_> = std::fs::read_dir(self.dir.path().join("files")).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names.len(), files, "{names:?}"); + } +} + +async fn until(what: &str, is: impl Fn() -> bool) { + let end = Instant::now() + Duration::from_secs(30); + while !is() { + assert!(Instant::now() < end, "never {what}"); + sleep(ms(10)).await; + } +} + +struct Seen { + seconds: f64, + format: String, + /// Kinds of streams and their names. + codecs: Vec, + packets: u64, +} + +fn look(file: &Path) -> Seen { + let args = ["-v", "error", "-count_packets", "-show_entries", "format=duration,format_name:stream=codec_name,nb_read_packets", "-of", "flat"]; + let out = Command::new("/usr/bin/ffprobe").args(args).arg(file).output().unwrap(); + let text = String::from_utf8(out.stdout).unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{}", String::from_utf8_lossy(&out.stderr)); + let pairs: Vec<(String, String)> = text.lines().filter_map(|l| l.split_once('=')).map(|(k, v)| (k.into(), v.trim_matches('"').into())).collect(); + let all = |end: &str| pairs.iter().filter(|(k, _)| k.ends_with(end)).map(|(_, v)| v.clone()).collect::>(); + Seen { + seconds: all("format.duration")[0].parse().unwrap(), + format: all("format_name")[0].clone(), + codecs: all("codec_name"), + packets: all("nb_read_packets").iter().map(|n| n.parse::().unwrap()).sum(), + } +} + +/// All of it is there, and decodes without a complaint. +fn check(file: &Path, seconds: f64, codecs: &[&str]) -> Seen { + let seen = look(file); + assert!((seen.seconds - seconds).abs() < 0.2, "{} s instead of {seconds}", seen.seconds); + assert_eq!(seen.codecs, codecs); + let out = Command::new("/usr/bin/ffmpeg").args(["-nostdin", "-v", "error", "-i"]).arg(file).args(["-f", "null", "-"]).output().unwrap(); + assert!(out.stderr.is_empty(), "{}", String::from_utf8_lossy(&out.stderr)); + seen +} + +fn kind_of(result: Result) -> ErrorKind { + match result { + Err(Error::Conn { kind, .. }) => kind, + other => panic!("{other:?}"), + } +} + +const HLS: &[&str] = &["-f", "hls", "-hls_time", "1", "-hls_list_size", "0", "-hls_segment_filename", "h%d.ts", "h.m3u8"]; + +#[tokio::test(flavor = "multi_thread")] +async fn hls_whole() { + let b = Bench::new().await; + b.make(HLS); + let file = b.get("h.m3u8", Choice::default()).await.unwrap(); + assert_eq!(file.file_name().unwrap(), "h.mp4"); + check(&file, LENGTH, &["h264", "aac"]); + let task = b.shared.store.tasks().unwrap().remove(0); + assert_eq!((task.name.as_str(), task.size), ("h.mp4", Some(file.metadata().unwrap().len()))); + b.clean(1); + // Every piece was asked for once. + for i in 0..6 { + assert_eq!(b.server.requests_for(&format!("/media/h{i}.ts")).len(), 1); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn hls_variants_and_sound_apart() { + let b = Bench::new().await; + let streams = ["-map", "0:v", "-map", "0:v", "-map", "1:a", "-s:v:0", "160x120", "-s:v:1", "320x240", "-f", "hls", "-hls_time", "1", "-hls_list_size", "0"]; + let out = ["-hls_segment_type", "fmp4", "-var_stream_map", "v:0,agroup:a v:1,agroup:a a:0,agroup:a,language:en,default:yes", "-master_pl_name", "m.m3u8"]; + let names = ["-hls_fmp4_init_filename", "init%v.mp4", "-hls_segment_filename", "v%v_%d.m4s", "v%v.m3u8"]; + b.make(&[&streams[..], &out, &names].concat()); + let (_stop, mut stopped) = watch::channel(false); + let found = stream::probe(&b.shared.client, &Source::new(&b.url("m.m3u8")).unwrap(), &mut stopped).await.unwrap(); + assert_eq!(found.videos.iter().map(|v| v.size.unwrap().1).collect::>(), [240, 120]); + assert_eq!((found.audios.len(), found.live), (1, false)); + assert!((found.duration.unwrap() - LENGTH).abs() < 0.2); + + let file = b.get("m.m3u8", Choice::default()).await.unwrap(); + check(&file, LENGTH, &["h264", "aac"]); + assert!(b.server.requests_for("/media/v0_0.m4s").is_empty(), "the best one only"); + let file = b.get("m.m3u8", Choice { max_height: Some(120), audio: Pick::None, ..Choice::default() }).await.unwrap(); + check(&file, LENGTH, &["h264"]); + let file = b.get("m.m3u8", Choice { video: Pick::None, ..Choice::default() }).await.unwrap(); + assert_eq!(file.extension().unwrap(), "m4a"); + check(&file, LENGTH, &["aac"]); + let gone = Choice { video: Pick::One("x".into()), ..Choice::default() }; + assert_eq!(kind_of(b.get("m.m3u8", gone).await), ErrorKind::Media); + b.clean(3); +} + +#[tokio::test(flavor = "multi_thread")] +async fn hls_with_keys_and_ranges() { + let b = Bench::new().await; + std::fs::write(b.media.join("k.bin"), b"0123456789abcdef").unwrap(); + b.write("k.info", "k.bin\nk.bin\n"); + b.make(&["-hls_key_info_file", "k.info", "-hls_flags", "periodic_rekey", "-f", "hls", "-hls_time", "1", "-hls_list_size", "0", "-hls_segment_filename", "e%d.ts", "e.m3u8"]); + assert!(b.read("e.m3u8").contains("METHOD=AES-128")); + check(&b.get("e.m3u8", Choice::default()).await.unwrap(), LENGTH, &["h264", "aac"]); + assert_eq!(b.server.requests_for("/media/k.bin").len(), 1, "a key is asked for once"); + + b.make(&["-hls_flags", "single_file", "-f", "hls", "-hls_time", "1", "-hls_list_size", "0", "r.m3u8"]); + assert!(b.read("r.m3u8").contains("#EXT-X-BYTERANGE")); + check(&b.get("r.m3u8", Choice::default()).await.unwrap(), LENGTH, &["h264", "aac"]); + + std::fs::write(b.media.join("k.bin"), b"another key here").unwrap(); + let e = b.get("e.m3u8", Choice::default()).await.unwrap_err(); + assert!(matches!(e, Error::BadReply(_) | Error::Conn { kind: ErrorKind::Media, .. }), "{e:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn hls_with_a_break() { + let b = Bench::new().await; + b.make(HLS); + let list = b.read("h.m3u8"); + let (head, pieces) = list.split_at(list.find("#EXTINF").unwrap()); + let pieces = pieces.replace("#EXT-X-ENDLIST\n", ""); + // The same again, with the clock back at its start. + b.write("twice.m3u8", &format!("{head}{pieces}#EXT-X-DISCONTINUITY\n{pieces}#EXT-X-ENDLIST\n")); + let file = b.get("twice.m3u8", Choice::default()).await.unwrap(); + let seen = look(&file); + assert!((seen.seconds - 2.0 * LENGTH).abs() < 0.3, "{}", seen.seconds); + assert_eq!(seen.codecs, ["h264", "aac"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn dash_whole() { + let b = Bench::new().await; + for (name, args) in [ + ("t.mpd", &["-use_template", "1", "-use_timeline", "1"][..]), + ("n.mpd", &["-use_template", "1", "-use_timeline", "0"]), + ("l.mpd", &["-use_template", "0", "-use_timeline", "0"]), + ("s.mpd", &["-single_file", "1"]), + ] { + let sets = ["-f", "dash", "-seg_duration", "1", "-adaptation_sets", "id=0,streams=v id=1,streams=a"]; + let prefix = name.split('.').next().unwrap(); + let (init, media) = (format!("{prefix}i$RepresentationID$.m4s"), format!("{prefix}c$RepresentationID$-$Number%05d$.m4s")); + b.make(&[&sets[..], args, &["-init_seg_name", &init, "-media_seg_name", &media, name]].concat()); + let file = b.get(name, Choice::default()).await.unwrap_or_else(|e| panic!("{name}: {e:?}\n{}", b.read(name))); + check(&file, LENGTH, &["h264", "aac"]); + } + // All in one file, taken in ranges. + b.write( + "one.mpd", + r#" + one.mp4"#, + ); + b.make(&["-an", "-movflags", "frag_keyframe+empty_moov+default_base_moof", "one.mp4"]); + check(&b.get("one.mpd", Choice::default()).await.unwrap(), LENGTH, &["h264"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn dash_that_grows() { + let b = Bench::new().await; + b.make(&["-an", "-f", "dash", "-seg_duration", "1", "-use_timeline", "0", "g.mpd"]); + let set = r#""#; + let list = |n: u32, kind: &str| { + let times: String = (0..n).map(|t| format!(r#""#)).collect(); + format!(r#"{set}{times}"#) + }; + b.write("grow.mpd", &list(3, "dynamic")); + let id = b.add(&b.url("grow.mpd"), ""); + let going = b.go(id, Choice::default()).await; + for n in 4..=6 { + until("asked for the next", || b.server.requests_for(&format!("/media/chunk-stream0-{:05}.m4s", n - 1)).len() == 1).await; + b.write("grow.mpd", &list(n, if n == 6 { "static" } else { "dynamic" })); + } + check(&going.end().await.unwrap(), LENGTH, &["h264"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn live_until_finished() { + let b = Bench::new().await; + b.make(HLS); + let whole = b.read("h.m3u8"); + let pieces: Vec<&str> = whole[whole.find("#EXTINF").unwrap()..].split_inclusive(".ts\n").take(6).collect(); + let window = |from: usize, to: usize| format!("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:{from}\n{}", pieces[from..to].concat()); + b.write("live.m3u8", &window(0, 4)); + let id = b.add(&b.url("live.m3u8"), ""); + let got = |i: usize| b.server.requests_for(&format!("/media/h{i}.ts")).len() == 1; + let going = b.go(id, Choice::default()).await; + until("at the end of the list", || got(3)).await; + assert!(!got(0), "it joins near the end"); + // Paused, while the stream goes on. + until("kept", || going.here() > 2_000).await; + sleep(ms(300)).await; + going.stop().await; + b.write("live.m3u8", &window(2, 5)); + let going = b.go(id, Choice::default()).await; + until("what came meanwhile", || got(4)).await; + b.write("live.m3u8", &window(3, 6)); + until("the next", || got(5)).await; + sleep(ms(300)).await; + going.monitor.finish(); + check(&going.end().await.unwrap(), 5.0, &["h264", "aac"]); + for i in 1..6 { + assert!(got(i), "{i} once"); + } + b.clean(1); + + // A limit ends it too, and so does the list. + b.write("live.m3u8", &window(0, 4)); + let file = b.get("live.m3u8", Choice { seconds: Some(2), ..Choice::default() }).await.unwrap(); + check(&file, 2.0, &["h264", "aac"]); + let id = b.add(&b.url("live.m3u8"), "over"); + let going = b.go(id, Choice::default()).await; + until("under way", || going.here() > 2_000).await; + b.write("live.m3u8", &(window(0, 6) + "#EXT-X-ENDLIST\n")); + check(&going.end().await.unwrap(), 5.0, &["h264", "aac"]); + + // Finished while it was paused: what there is. + b.write("live.m3u8", &window(0, 4)); + let id = b.add(&b.url("live.m3u8"), "paused"); + let going = b.go(id, Choice::default()).await; + until("recorded", || going.here() > 2_000 && going.monitor.snapshot().connections == 0).await; + going.stop().await; + let monitor = Arc::new(Monitor::new(16)); + monitor.finish(); + b.write("live.m3u8", "gone"); + check(&b.go_with(id, Choice::default(), monitor).await.end().await.unwrap(), 3.0, &["h264", "aac"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn goes_on_after_a_restart() { + let mut b = Bench::new().await; + b.make(HLS); + b.server.set_faults("/media/h*", Faults { latency_ms: Some(150), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), ""); + let going = b.go(id, Choice::default()).await; + until("begun", || going.here() > 2_000).await; + going.stop().await; + // Another program start. + b.shared = Bench::shared(b.dir.path()); + let parts = b.shared.store.parts(id).unwrap(); + assert!(parts[0].done > 0 && parts[0].end.is_none()); + b.server.clear_all_faults(); + b.server.clear_log(); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + check(&file, LENGTH, &["h264", "aac"]); + let again = (0..6).filter(|i| b.server.requests_for(&format!("/media/h{i}.ts")).len() == 1).count(); + assert!(again < 6, "nothing that was here is asked for again"); + b.clean(1); + // Killed after the end, before the list knew. + assert_eq!(b.go(id, Choice::default()).await.end().await.unwrap(), file); + + // Killed between the joining and the name. + let id = b.add(&b.url("h.m3u8"), "x.mp4"); + b.shared.store.save_parts(id, vec![Part { start: 0, end: None, done: 5000 }]).unwrap(); + std::fs::copy(&file, medlar_core::disk::partial_path(&b.dir.path().join("files"), "x.mp4")).unwrap(); + b.server.clear_log(); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + assert_eq!(file.file_name().unwrap(), "x.mp4"); + check(&file, LENGTH, &["h264", "aac"]); + assert!(b.server.log().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn another_list_is_not_mixed_in() { + let b = Bench::new().await; + b.make(HLS); + b.server.set_faults("/media/h*", Faults { latency_ms: Some(150), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), ""); + let going = b.go(id, Choice::default()).await; + until("begun", || going.here() > 2_000).await; + going.stop().await; + let list = b.read("h.m3u8"); + b.write("h.m3u8", &list.replacen("#EXTINF", "#EXTINF:1,\nh0.ts\n#EXTINF", 1)); + assert!(matches!(b.go(id, Choice::default()).await.end().await, Err(Error::Changed))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn pieces_are_tried_again() { + let b = Bench::new().await; + b.make(HLS); + b.server.set_faults("/media/h1.ts", Faults { status: Some(503), status_count: Some(2), ..Faults::default() }); + b.server.set_faults("/media/h2.ts", Faults { status: Some(500), status_count: Some(1), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), ""); + let going = b.go(id, Choice::default()).await; + check(&going.end().await.unwrap(), LENGTH, &["h264", "aac"]); + assert_eq!(b.server.requests_for("/media/h1.ts").len(), 3); + + // One that never comes: the others are kept. + b.server.set_faults("/media/h3.ts", Faults { cut_after: Some(1000), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), "two.mkv"); + let e = b.go(id, Choice::default()).await.end().await.unwrap_err(); + assert!(matches!(e, Error::Cut { .. }), "{e:?}"); + b.server.clear_all_faults(); + b.server.clear_log(); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + assert!(check(&file, LENGTH, &["h264", "aac"]).format.contains("matroska")); + assert!(b.server.requests_for("/media/h0.ts").is_empty()); + + for (status, wanted) in [(404, 404), (403, 403)] { + b.server.set_faults("/media/h3.ts", Faults::status(status)); + let e = b.get("h.m3u8", Choice::default()).await.unwrap_err(); + assert!(matches!(e, Error::Status { code, .. } if code == wanted), "{e:?}"); + } + let e = b.get("no.m3u8", Choice::default()).await.unwrap_err(); + assert!(matches!(e, Error::Status { code: 404, .. }), "{e:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn protected_and_false_ones() { + let b = Bench::new().await; + b.make(HLS); + let protected = "#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"skd://k\",KEYFORMAT=\"com.apple.streamingkeydelivery\"\n#EXTINF"; + let list = b.read("h.m3u8"); + b.write("fair.m3u8", &list.replacen("#EXTINF", protected, 1)); + assert_eq!(kind_of(b.get("fair.m3u8", Choice::default()).await), ErrorKind::Drm); + b.make(&["-an", "-encryption_scheme", "cenc-aes-ctr", "-encryption_key", "00112233445566778899aabbccddeeff", "-encryption_kid", "00112233445566778899aabbccddeeff", "-movflags", "frag_keyframe+empty_moov", "enc.mp4"]); + b.write("wide.mpd", r#""#); + assert_eq!(kind_of(b.get("wide.mpd", Choice::default()).await), ErrorKind::Drm); + // The list doesn't say so, but the piece does. + b.write("quiet.m3u8", "#EXTM3U\n#EXT-X-MAP:URI=\"enc.mp4\"\n#EXTINF:6,\nenc.mp4\n#EXT-X-ENDLIST\n"); + assert_eq!(kind_of(b.get("quiet.m3u8", Choice::default()).await), ErrorKind::Drm); + // Lists that pretend to be pieces don't get ffmpeg to open anything. + let secret = b.dir.path().join("secret.ts"); + std::fs::copy(b.media.join("h0.ts"), &secret).unwrap(); + let evil = [ + format!("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nfile://{}\n#EXT-X-ENDLIST\n", secret.display()), + format!("ffconcat version 1.0\nfile '{}'\n", secret.display()), + format!("#EXTM3U\n#EXTINF:1,\n{}\n#EXT-X-ENDLIST\n", b.url("h5.ts")), + ]; + for text in evil { + b.write("evil.ts", &text); + for list in ["#EXTM3U\n#EXTINF:1,\nevil.ts\n#EXT-X-ENDLIST\n", "#EXTM3U\n#EXTINF:1,\nevil.ts\n#EXT-X-DISCONTINUITY\n#EXTINF:1,\nevil.ts\n#EXT-X-ENDLIST\n"] { + b.write("evil.m3u8", list); + assert_eq!(kind_of(b.get("evil.m3u8", Choice::default()).await), ErrorKind::Media, "{text}"); + } + } + assert!(b.server.requests_for("/media/h5.ts").is_empty()); + // No ffmpeg: nothing is downloaded. + let id = b.add(&b.url("h.m3u8"), ""); + let (_stop, stopped) = watch::channel(false); + let request = Request { id, source: Source::new(&b.url("h.m3u8")).unwrap(), choice: Choice::default(), tools: &Tools::default(), options: &b.options }; + b.server.clear_log(); + assert_eq!(kind_of(stream::download(&b.shared, request, &Monitor::new(1), stopped).await), ErrorKind::Tool); + assert!(b.server.log().is_empty()); +} + +/// A server of one RTSP stream: a tone, 50 packets a second, in real time. +struct Rtsp { + port: u16, + heard: Arc>>, +} + +impl Rtsp { + /// Ends after `seconds`, if any are given. + fn start(login: Option<&'static str>, seconds: Option) -> Rtsp { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let heard = Arc::new(Mutex::new(vec![])); + let log = heard.clone(); + std::thread::spawn(move || { + for conn in listener.incoming() { + let (conn, log) = (conn.unwrap(), log.clone()); + std::thread::spawn(move || drop(Rtsp::serve(conn, login, seconds, &log))); + } + }); + Rtsp { port, heard } + } + + fn serve(conn: TcpStream, login: Option<&str>, seconds: Option, log: &Mutex>) -> std::io::Result<()> { + let mut out = conn.try_clone()?; + let mut lines = BufReader::new(conn).lines(); + loop { + let mut head: Vec = vec![]; + loop { + match lines.next() { + Some(Ok(line)) if line.is_empty() => break, + Some(Ok(line)) => head.push(line), + _ => return Ok(()), + } + } + let Some(request) = head.first() else { continue }; + log.lock().unwrap().push(request.clone()); + let of = |name: &str| head.iter().find_map(|l| l.strip_prefix(name)).map(str::to_string); + let seq = of("CSeq: ").unwrap_or_default(); + if login.is_some_and(|l| of("Authorization: Basic ").as_deref() != Some(l)) { + write!(out, "RTSP/1.0 401 Unauthorized\r\nCSeq: {seq}\r\nWWW-Authenticate: Basic realm=\"cam\"\r\n\r\n")?; + continue; + } + let sdp = "v=0\r\no=- 0 0 IN IP4 127.0.0.1\r\ns=x\r\nt=0 0\r\nm=audio 0 RTP/AVP 0\r\na=control:track1\r\n"; + let more = match request.split(' ').next().unwrap_or_default() { + "OPTIONS" => "Public: DESCRIBE, SETUP, PLAY, TEARDOWN\r\n\r\n".into(), + "DESCRIBE" => format!("Content-Type: application/sdp\r\nContent-Length: {}\r\n\r\n{sdp}", sdp.len()), + "SETUP" => "Transport: RTP/AVP/TCP;unicast;interleaved=0-1\r\nSession: 1\r\n\r\n".into(), + _ => "Session: 1\r\n\r\n".into(), + }; + write!(out, "RTSP/1.0 200 OK\r\nCSeq: {seq}\r\n{more}")?; + if request.starts_with("PLAY") { + let mut out = out.try_clone()?; + std::thread::spawn(move || { + let start = Instant::now(); + for n in 0u32.. { + if seconds.is_some_and(|s| f64::from(n) >= s * 50.0) { + return out.shutdown(std::net::Shutdown::Both); + } + let mut packet = vec![b'$', 0, 0, 172, 0x80, 0]; + packet.extend((n as u16).to_be_bytes()); + packet.extend((n * 160).to_be_bytes()); + packet.extend([0, 0, 0, 1]); + packet.extend([if n % 2 == 0 { 0x90 } else { 0x10 }; 160]); + out.write_all(&packet)?; + std::thread::sleep((ms(20) * (n + 1)).saturating_sub(start.elapsed())); + } + Ok(()) + }); + } + } + } + + fn url(&self) -> String { + format!("rtsp://127.0.0.1:{}/cam", self.port) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn rtsp_is_recorded() { + let b = Bench::new().await; + let server = Rtsp::start(None, None); + // Until it is told to end, with a pause. + let id = b.add(&server.url(), ""); + let going = b.go(id, Choice::default()).await; + until("recording", || going.here() > 10_000).await; + going.stop().await; + let before = b.shared.store.parts(id).unwrap()[0].done; + let going = b.go(id, Choice::default()).await; + until("recording again", || going.here() > before + 15_000).await; + going.monitor.finish(); + let file = going.end().await.unwrap(); + // Not one of the formats mp4 can hold. + assert_eq!(file.file_name().unwrap(), "cam.mkv"); + let seen = look(&file); + assert_eq!(seen.codecs, ["pcm_mulaw"]); + // 8000 bytes a second. + assert!(seen.seconds > 2.5 && seen.seconds < 20.0, "{}", seen.seconds); + + let timed = b.add(&server.url(), "timed"); + let file = b.go(timed, Choice { seconds: Some(2), ..Choice::default() }).await.end().await.unwrap(); + assert!((look(&file).seconds - 2.0).abs() < 0.3, "{}", look(&file).seconds); + let sized = b.add(&server.url(), "sized"); + let file = b.go(sized, Choice { bytes: Some(8_000), ..Choice::default() }).await.end().await.unwrap(); + let size = file.metadata().unwrap().len(); + assert!(size > 7_000 && size < 60_000, "{size}"); + // It ends by itself. + let short = Rtsp::start(None, Some(1.5)); + let id = b.add(&short.url(), "short"); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + assert!((look(&file).seconds - 1.5).abs() < 0.3, "{}", look(&file).seconds); + b.clean(4); + // Nobody there. + let gone = b.add(&format!("rtsp://127.0.0.1:{}/x", TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()), ""); + assert_eq!(kind_of(b.go(gone, Choice::default()).await.end().await), ErrorKind::Refused); +} + +#[tokio::test(flavor = "multi_thread")] +async fn rtsp_logins_are_not_seen() { + let mut b = Bench::new().await; + // us%er:p'w x + let server = Rtsp::start(Some("dXMlZXI6cCd3IHg="), None); + let secrets = Arc::new(Secrets::new(Bus::Off)); + let settings = Settings { proxy: "direct".into(), ..Settings::default() }; + let sites = Sites::new(ClientOptions::default(), &settings, secrets.clone(), Bus::Off).unwrap(); + let login = Login { user: "us%er".into(), password: "p'w x".into() }; + let secret = Secret { home: Some(server.url()), login: Some(login), ..Secret::default() }; + let _ = secrets.save("cam", "cam", &secret).await; + b.sites = Some(sites.clone()); + let id = b.add(&server.url(), ""); + assert_eq!(kind_of(b.go(id, Choice::default()).await.end().await), ErrorKind::Login); + b.shared.store.edit_task(id, |t| t.secret = Some("cam".into())).unwrap(); + let going = b.go(id, Choice::default()).await; + until("recording", || going.here() > 5_000).await; + let mine: Vec = children().into_iter().filter(|args| args.contains(&format!(":{}/", server.port)) || args.contains("pipe:0")).collect(); + assert!(!mine.is_empty()); + assert!(mine.iter().all(|args| !args.contains("er:") && !args.contains("p%27w") && !args.contains("p'w")), "{mine:?}"); + going.monitor.finish(); + assert_eq!(look(&going.end().await.unwrap()).codecs, ["pcm_mulaw"]); + + // Never around a proxy. + server.heard.lock().unwrap().clear(); + sites.set(&Settings { proxy: "socks5://127.0.0.1:9".into(), proxy_bypass: vec![], ..Settings::default() }); + let id = b.add(&server.url(), ""); + assert_eq!(kind_of(b.go(id, Choice::default()).await.end().await), ErrorKind::Proxy); + assert!(server.heard.lock().unwrap().is_empty()); +} + +/// The arguments of our child processes. +fn children() -> Vec { + let me = std::process::id(); + let mut found = vec![]; + for entry in std::fs::read_dir("/proc").unwrap().flatten() { + let stat = std::fs::read_to_string(entry.path().join("stat")).unwrap_or_default(); + let parent = stat.rsplit(')').next().and_then(|s| s.split_whitespace().nth(1)).and_then(|p| p.parse::().ok()); + if parent == Some(me) { + found.push(std::fs::read_to_string(entry.path().join("cmdline")).unwrap_or_default().replace('\0', " ")); + } + } + found +} + +/// MMS over HTTP: the header, then the packets of an ASF file. +fn mms_server(asf: Vec) -> u16 { + let long = |at: usize| u64::from_le_bytes(asf[at..at + 8].try_into().unwrap()) as usize; + let header = long(16) + 50; + let end = long(16) + long(long(16) + 16); + let packets: Vec> = asf[header..end].chunks(3200).map(<[u8]>::to_vec).collect(); + let header = asf[..header].to_vec(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let chunk = |kind: u8, n: u32, data: &[u8]| { + let len = (data.len() as u16 + 8).to_le_bytes(); + [&[b'$', kind][..], &len, &n.to_le_bytes(), &[0, 0x0c], &len, data].concat() + }; + std::thread::spawn(move || { + for conn in listener.incoming() { + let mut conn = conn.unwrap(); + let mut head = vec![]; + let mut byte = [0]; + while !head.ends_with(b"\r\n\r\n") && conn.read(&mut byte).unwrap_or(0) == 1 { + head.push(byte[0]); + } + let text = String::from_utf8_lossy(&head).into_owned(); + let _ = conn.write_all(b"HTTP/1.0 200 OK\r\nContent-Type: application/x-mms-framed\r\nPragma: client-id=1\r\n\r\n"); + let _ = conn.write_all(&chunk(b'H', 0, &header)); + if text.contains("xPlayStrm=1") { + for (i, p) in packets.iter().enumerate() { + let _ = conn.write_all(&chunk(b'D', i as u32, p)); + } + let _ = conn.write_all(&[b'$', b'E', 4, 0, 0, 0, 0, 0]); + } + } + }); + port +} + +#[tokio::test(flavor = "multi_thread")] +async fn mms_is_recorded() { + let b = Bench::new().await; + ffmpeg(&b.media, &["-f", "lavfi", "-i", "testsrc=size=160x120:rate=10:duration=6", "-f", "lavfi", "-i", "sine=440:duration=6", "-c:v", "wmv2", "-c:a", "wmav2", "-f", "asf", "a.wmv"]); + let port = mms_server(std::fs::read(b.media.join("a.wmv")).unwrap()); + let id = b.add(&format!("mms://127.0.0.1:{port}/a.wmv"), ""); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + let seen = look(&file); + assert!((seen.seconds - LENGTH).abs() < 0.3, "{}", seen.seconds); + assert_eq!(seen.codecs, ["wmv2", "wmav2"]); + assert!(seen.packets > 60); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_manager_knows_streams() { + use medlar_core::manager::{Bin, Command, Config, Manager}; + use medlar_core::settings::Limits; + let b = Bench::new().await; + b.make(HLS); + let limits = Limits { speed: 0, max_active: 4, max_connections: 32, parts_per_download: 4, connections_per_host: 16 }; + let dir = tempfile::tempdir().unwrap(); + let mut config = Config::new(Bench::shared(dir.path()), limits); + (config.options, config.bin, config.tick) = (b.options.clone(), Bin::at(dir.path().join("Trash")), ms(20)); + let manager = Manager::open(config).unwrap(); + let add = async |url: String| { + let task = Task { url, folder: dir.path().join("files"), ..Task::default() }; + manager.send(Command::Add(Box::new(task))).await.unwrap() + }; + let view = |id| manager.snapshot().get(id).unwrap().clone(); + let state = async |id, state| until(&format!("{state:?}"), || view(id).state() == state).await; + + let film = add(b.url("h.m3u8")).await; + state(film, State::Done).await; + assert_eq!(view(film).task.name, "h.mp4"); + check(&dir.path().join("files/h.mp4"), LENGTH, &["h264", "aac"]); + assert_eq!(view(film).size, Some(dir.path().join("files/h.mp4").metadata().unwrap().len())); + + // Live: paused, moved with what there is, and ended. + let list = b.read("h.m3u8").replace("#EXT-X-ENDLIST\n", ""); + b.write("live.m3u8", &list); + let live = add(b.url("live.m3u8")).await; + until("recorded", || view(live).downloaded > 2_000 && view(live).connections == 0).await; + manager.send(Command::Pause(live)).await.unwrap(); + state(live, State::Paused).await; + manager.send(Command::Rename { id: live, name: "mine.mp4".into() }).await.unwrap(); + manager.send(Command::Finish(live)).await.unwrap(); + state(live, State::Done).await; + check(&dir.path().join("files/mine.mp4"), 3.0, &["h264", "aac"]); + + let camera = Rtsp::start(None, None); + let cam = add(camera.url()).await; + until("recording", || view(cam).downloaded > 10_000).await; + manager.send(Command::Finish(cam)).await.unwrap(); + state(cam, State::Done).await; + assert_eq!(view(cam).task.name, "cam.mkv"); + + b.write("fair.m3u8", "#EXTM3U\n#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"skd://k\"\n#EXTINF:1,\nh0.ts\n"); + let fair = add(b.url("fair.m3u8")).await; + state(fair, State::Failed).await; + let error = view(fair).task.error.clone().unwrap(); + assert_eq!(error.kind, Some(ErrorKind::Drm)); + assert!(error.detail.starts_with("Copy protected"), "{}", error.detail); + manager.send(Command::Finish(fair)).await.unwrap(); + manager.close(); +} diff --git a/docs/RECOVERY.md b/docs/RECOVERY.md index d91df29..cfaa154 100644 --- a/docs/RECOVERY.md +++ b/docs/RECOVERY.md @@ -38,6 +38,9 @@ Title and text: `error.` and `error..why` in the catalogue; button: | `changed` | File changed on the server | blocked | no | Choose (`choose`) | | `no_resume` | Can't be continued | blocked | no | Choose (`choose`) | | `killed` | Interrupted | passing | no | Resume (`resume`) | +| `drm` | Copy protected | blocked | no | Edit link (`edit_link`) | +| `tool` | A program is missing | blocked | no | Try again (`try_again`) | +| `media` | Stream can't be saved | serious | no | Try again (`try_again`) | | `tls` | Secure connection failed | serious | no | Try again (`try_again`) | | `disk` | Disk error | serious | later 30–600 s | Change folder (`change_folder`) | | `list` | Download list not saved | serious | later 30–600 s | Try again (`try_again`) | From f9eec8f1617aae0bb36b459334bfcc38243d9aa3 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 13:55:19 -0600 Subject: [PATCH 03/70] S009: mirrors, Metalink and checksums Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 22 + Plans/02 Engine/S009-mirrors-checksums.md | 12 +- Plans/INDEX.md | 2 +- crates/core/Cargo.toml | 5 + crates/core/lang/en.json | 13 + crates/core/src/error.rs | 3 +- crates/core/src/http/download.rs | 260 +++++++++- crates/core/src/http/fetch.rs | 36 ++ crates/core/src/http/mod.rs | 12 +- crates/core/src/http/monitor.rs | 34 +- crates/core/src/http/parts.rs | 409 ++++++++++++++-- crates/core/src/http/probe.rs | 4 + crates/core/src/lib.rs | 3 + crates/core/src/manager/actor.rs | 105 +++- crates/core/src/manager/files.rs | 1 + crates/core/src/manager/mod.rs | 24 +- crates/core/src/metalink.rs | 452 ++++++++++++++++++ crates/core/src/mirror.rs | 133 ++++++ crates/core/src/model.rs | 13 +- crates/core/src/relink/mod.rs | 53 ++- crates/core/src/snapshot.rs | 24 +- crates/core/src/store/004.sql | 2 + crates/core/src/store/mod.rs | 2 +- crates/core/src/store/rows.rs | 13 +- crates/core/src/verify.rs | 553 ++++++++++++++++++++++ crates/core/tests/mirror.rs | 498 +++++++++++++++++++ docs/DECISIONS.md | 3 + docs/PROGRESS.md | 11 + docs/RECOVERY.md | 1 + 29 files changed, 2597 insertions(+), 106 deletions(-) create mode 100644 crates/core/src/metalink.rs create mode 100644 crates/core/src/mirror.rs create mode 100644 crates/core/src/store/004.sql create mode 100644 crates/core/src/verify.rs create mode 100644 crates/core/tests/mirror.rs diff --git a/Cargo.lock b/Cargo.lock index e62fe95..3cae3be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -583,6 +583,19 @@ dependencies = [ "digest", ] +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -853,6 +866,12 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "core-foundation" version = "0.9.4" @@ -2771,6 +2790,7 @@ dependencies = [ "aes", "arc-swap", "base64 0.23.1", + "blake3", "bytes", "cbc", "chrono", @@ -2784,6 +2804,7 @@ dependencies = [ "md-5", "medlar-testserver", "percent-encoding", + "quick-xml", "rcgen", "regex", "reqwest", @@ -2796,6 +2817,7 @@ dependencies = [ "rustls-platform-verifier", "serde", "serde_json", + "sha1", "sha2", "tempfile", "tokio", diff --git a/Plans/02 Engine/S009-mirrors-checksums.md b/Plans/02 Engine/S009-mirrors-checksums.md index b82e210..1eb44e2 100644 --- a/Plans/02 Engine/S009-mirrors-checksums.md +++ b/Plans/02 Engine/S009-mirrors-checksums.md @@ -10,12 +10,12 @@ FEATURES 1.8, 1.13. - crates/core/src/{segment,host,relink}* ## Steps -- [ ] Several sources per file: each checked with S008's comparison before its bytes are used; parts spread by measured speed; a bad mirror is dropped alone -- [ ] Metalink 3 and 4 files and the `Link`/`Digest` headers; piece hashes repair single pieces -- [ ] Checksums MD5, SHA-1, SHA-256, SHA-512, BLAKE3, hashed off the download threads; sources: metalink, sidecar files, headers, pasted text (type detected by length) -- [ ] Verify state and progress in the snapshot; mismatch offers repair (piece hashes), other mirror or restart -- [ ] XML parsing hardened: size and depth limits, no entities -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S009: …`, push +- [x] Several sources per file: each checked with S008's comparison before its bytes are used; parts spread by measured speed; a bad mirror is dropped alone +- [x] Metalink 3 and 4 files and the `Link`/`Digest` headers; piece hashes repair single pieces +- [x] Checksums MD5, SHA-1, SHA-256, SHA-512, BLAKE3, hashed off the download threads; sources: metalink, sidecar files, headers, pasted text (type detected by length) +- [x] Verify state and progress in the snapshot; mismatch offers repair (piece hashes), other mirror or restart +- [x] XML parsing hardened: size and depth limits, no entities +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S009: …`, push ## End criteria - `nice cargo test -j 2 -p medlar-core --test mirror` green: fast plus slow mirror, lying mirror, corrupt piece repaired diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 178245a..35f8867 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -17,7 +17,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S006](02%20Engine/S006-manager.md) Download manager, events and snapshots - [x] [S007](02%20Engine/S007-error-recovery.md) Error recovery - [x] [S008](02%20Engine/S008-continue-links.md) Continue from a new link -- [ ] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums +- [x] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums - [x] [S010](02%20Engine/S010-logins-proxies.md) Logins, cookies and proxies - [x] [S011](02%20Engine/S011-ftp-sftp.md) FTP, FTPS and SFTP - [ ] [S012](02%20Engine/S012-streams.md) HLS, DASH, RTSP and MMS diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index d3deb28..05379bf 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -9,6 +9,8 @@ description = "Medlar's engine, store and settings" aes = "0.9" arc-swap = "1.9.5" base64 = "0.23" +# In Rust alone, so that no C compiler is needed. +blake3 = { version = "1", default-features = false, features = ["pure", "std"] } bytes = "1.10" cbc = "0.2" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } @@ -21,6 +23,8 @@ log = { workspace = true, features = ["std"] } md-5 = "0.11.0" percent-encoding = "2.3.2" regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] } +# The one wayland-scanner has. +quick-xml = "0.41" roxmltree = "0.21" # Pinned: D-017. reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider", "socks"] } @@ -34,6 +38,7 @@ rustls = { version = "0.23.46", default-features = false, features = ["ring", "s rustls-platform-verifier = "0.7.1" serde.workspace = true serde_json.workspace = true +sha1 = "0.11" sha2 = "0.11.1" tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "process"] } tokio-rustls = { version = "0.26", default-features = false } diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 5a652cc..02528b4 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -319,6 +319,19 @@ "error.full": "{what}. {why}", "error.no_server": "The server", + "error.checksum": "File is damaged", + "error.checksum.why": "The complete file is not what its checksum says. It was kept under its unfinished name, or where it was.", + "verify.nothing": "No checksum", + "verify.open": "Not checked yet", + "verify.checking": "Checking", + "verify.good": "Matches its checksum", + "verify.bad": "Does not match its checksum", + "verify.repair": "Download the damaged pieces again", + "verify.other_mirror": "Start over from another mirror", + "verify.restart": "Start over", + "metalink.form": "This is not a metalink file, or it is broken.", + "metalink.unsafe": "This metalink file is larger or deeper than a sensible one, or defines things of its own. It was not read.", + "metalink.empty": "This metalink file has nothing that can be downloaded.", "log.retry": {"one": "Next try in {n} second", "other": "Next try in {n} seconds"}, "dialog.cancel": "Cancel", diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index 7017aee..79a0003 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -97,7 +97,7 @@ impl ErrorKind { Login => (Blocked, Retry::Never, Fix::SignIn), Forbidden | Expired | WrongContent | Link => (Blocked, Retry::Never, Fix::NewLink), NotFound | Rejected | BadLink => (Blocked, Retry::Never, Fix::EditLink), - Changed | NoResume => (Blocked, Retry::Never, Fix::Choose), + Changed | NoResume | Checksum => (Blocked, Retry::Never, Fix::Choose), Killed => (Passing, Retry::Never, Fix::Resume), Tls => (Serious, Retry::Never, Fix::TryAgain), Disk => (Serious, later(30, 600), Fix::ChangeFolder), @@ -201,6 +201,7 @@ impl Failure { E::Encoded(_) | E::BadReply(_) => ErrorKind::BadReply, // Stopped is no failure. E::Cut { .. } | E::Stopped => ErrorKind::Cut, + E::Checksum => ErrorKind::Checksum, E::Missing => ErrorKind::FileGone, E::Disk(e) => of_disk(e, place.folder), E::Store(_) => ErrorKind::List, diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index fe7a2f2..ed17d27 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -1,17 +1,22 @@ //! One file from link to disk. use super::fetch::compare; -use super::parts::Run; +use super::parts::{Ended, Run}; use super::*; use crate::adapt::{self, Timing}; use crate::disk::{PartialFile, blocking}; use crate::host::{self, Hosts}; use crate::limit::Group; +use crate::metalink; +use crate::mirror; use crate::model::{self, Part, Task, TaskId}; use crate::part::LivePart; +use crate::relink::{self, NewLink}; use crate::segment::Rules; use crate::store::Store; -use std::path::PathBuf; +use crate::verify::{Found, Wanted}; +use std::ops::Range; +use std::path::{Path, PathBuf}; use std::sync::Arc; /// What all downloads have in common. @@ -58,10 +63,87 @@ impl Default for Options { } } -/// Starts or continues the task and returns the finished file. Doesn't touch the task's state. +/// Times that wrong pieces come again before the download fails. +const REPAIRS: u32 = 3; +/// Waited for a metalink that the server tells of. +const ASIDE: Duration = Duration::from_secs(5); + +/// The file with all its bytes. +enum Whole { + /// Under its unfinished name. + Partial(PartialFile, u64), + Finished(PathBuf), +} + +impl Whole { + fn path(&self) -> &Path { + match self { + Whole::Partial(file, _) => file.path(), + Whole::Finished(path) => path, + } + } +} + +type Gave = Vec<(String, Vec>)>; + +/// Starts or continues the task and returns the finished file, compared with its checksum if it has one. Wrong pieces come again +/// if it has hashes of them. Doesn't touch the task's state. pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Options, monitor: &Monitor, mut stop: Stop) -> Result { - let (client, store) = (&shared.client, &shared.store); - let job = Job { store: store.clone(), id }; + let job = Job { store: shared.store.clone(), id }; + // Links that brought wrong bytes. + let (mut out, mut doubted) = (vec![], vec![]); + for round in 0.. { + let (whole, gave) = fetch_whole(shared, &job, &source, &out, options, monitor, &mut stop).await?; + let task = job.task().await?; + let wanted = Wanted { checksum: task.checksum.as_ref().and_then(|c| c.parse().ok()), pieces: task.pieces.clone() }; + let checked = monitor.checked(); + if !wanted.nothing() { + *checked.lock().unwrap() = Some(0.0); + } + let share = checked.clone(); + let found = wanted.compare(whole.path().to_path_buf(), move |x| *share.lock().unwrap() = Some(x), &stop).await; + *checked.lock().unwrap() = None; + let verified = match found? { + Found::Good(by) => Some(by), + Found::Nothing => None, + Found::Bad(ranges) if ranges.is_empty() || round == REPAIRS => return Err(Error::Checksum), + Found::Bad(ranges) => { + log::debug!("task {id}: {} wrong ranges come again", ranges.len()); + for (i, (url, gave)) in gave.into_iter().enumerate() { + let wrong = gave.iter().any(|g| ranges.iter().any(|r| r.start < g.end && g.start < r.end)); + // The base gets a second chance. + if wrong && (i > 0 || doubted.contains(&url)) { + out.push(url); + } else if wrong { + doubted.push(url); + } + } + job.forget(whole, ranges).await?; + continue; + } + }; + if task.verified != verified { + job.run(move |s| Ok(s.edit_task(id, move |t| t.verified = verified)?)).await?; + } + return match whole { + Whole::Partial(file, size) => job.finish(file, size).await, + Whole::Finished(path) => Ok(path), + }; + } + unreachable!("the last round returns") +} + +/// Until all bytes are here. +async fn fetch_whole( + shared: &Shared, + job: &Job, + source: &Source, + out: &[String], + options: &Options, + monitor: &Monitor, + stop: &mut Stop, +) -> Result<(Whole, Gave)> { + let (client, id) = (&shared.client, job.id); let (task, parts) = job.run(move |s| Ok((s.task(id)?, s.parts(id)?))).await?; let file = if parts.is_empty() { None @@ -72,12 +154,12 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt if !parts.is_empty() && parts.iter().all(finished) { let size = parts.iter().map(|p| p.done).sum(); match file { - Some(file) => return job.finish(file, size).await, - // Killed between the rename and the end. + Some(file) => return Ok((Whole::Partial(file, size), vec![])), + // Killed between the rename and the end, or done before. None => { let path = task.folder.join(&task.name); if path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == size) { - return Ok(path); + return Ok((Whole::Finished(path), vec![])); } } } @@ -87,15 +169,14 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt return Err(Error::Missing); } - let mut probe = probe(client, &source, &mut stop).await?; - if is_page(&task, &source, &probe) { - return Err(Error::Page); - } + let Opened { url, mut probe, compared } = open(client, &task, &parts, source, out, stop).await?; let body = probe.body.take(); - let link = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version.clone() }; + // Once on a mirror, its redirects are its own. + let here = if url == task.url { source.at(&probe.url) } else { source.mirror(&url)?.at(&probe.url) }; + let link = Link { client: client.clone(), source: here, ranges: probe.ranges, version: probe.version.clone() }; let (file, parts) = match file { - Some(file) => resume(&job, &task, file, parts, &link, &mut stop).await?, - None => start(&job, &task, probe).await?, + Some(file) => resume(job, &task, file, parts, &link, compared, stop).await?, + None => start(shared, job, &task, probe, &link, stop).await?, }; if let Some(size) = link.version.size { let reserving = file.clone(); @@ -107,10 +188,14 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt let known = job.run(move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default(); shared.hosts.set_host_cap(&host, link.source.max_connections().or(known.max_connections)); monitor.flow().put_limited(Group::Host(host.clone()), link.source.speed_limit().or(known.speed_limit)); - let start = host::tolerated(&known, model::now()).unwrap_or(adapt::START); - let mut run = Run::new(shared, link, file.clone(), parts, body, host.clone(), start, task.max_parts, options, monitor); - let result = run.go(&job, &mut stop).await; - let (live, learned) = run.end(); + let begin = host::tolerated(&known, model::now()).unwrap_or(adapt::START); + // Its name and more are known now. + let task = Arc::new(job.task().await?); + let mirrors = links(&task).into_iter().filter(|u| *u != url && !out.contains(u)).filter_map(|u| Some((u.clone(), source.mirror(&u).ok()?))); + let mirrors = if link.ranges { mirrors.collect() } else { vec![] }; + let mut run = Run::new(shared, task, (url, link), mirrors, file.clone(), parts, body, host.clone(), begin, options, monitor); + let result = run.go(job, stop).await; + let Ended { live, learned, gave } = run.end(); let saved = job.checkpoint(&live, &file).await; if let Some(n) = learned { job.run(move |s| Ok(host::remember(s, &host, n, model::now())?)).await?; @@ -119,7 +204,78 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt saved?; let size = live.iter().map(|p| p.get().done).sum(); let file = Arc::into_inner(file).expect("the parts have ended"); - job.finish(file, size).await + Ok((Whole::Partial(file, size), gave)) +} + +/// All links of the task, each once. +fn links(task: &Task) -> Vec { + let mut all = vec![task.url.clone()]; + for m in &task.mirrors { + if !all.contains(m) { + all.push(m.clone()); + } + } + all.truncate(metalink::MAX_URLS); + all +} + +struct Opened { + url: String, + probe: Probe, + /// What is here was compared with it. + compared: bool, +} + +/// The first link that works and has the file that is here. +async fn open(client: &Client, task: &Task, parts: &[Part], source: &Source, out: &[String], stop: &mut Stop) -> Result { + let mut failed = None; + for (i, url) in links(task).into_iter().enumerate() { + if out.contains(&url) { + continue; + } + let from = match if i == 0 { Ok(source.clone()) } else { source.mirror(&url) } { + Ok(from) => from, + Err(e) => { + failed.get_or_insert(e); + continue; + } + }; + match open_one(client, task, parts, from, i == 0, stop).await { + Ok((probe, compared)) => return Ok(Opened { url, probe, compared }), + Err(e @ (Error::Stopped | Error::Disk(_) | Error::Store(_) | Error::Missing)) => return Err(e), + Err(e) => { + log::debug!("link {i} of task {}: {e:?}", task.id); + failed.get_or_insert(e); + } + } + } + Err(failed.unwrap_or(Error::Checksum)) +} + +async fn open_one(client: &Client, task: &Task, parts: &[Part], source: Source, first: bool, stop: &mut Stop) -> Result<(Probe, bool)> { + let probe = probe(client, &source, stop).await?; + if is_page(task, &source, &probe) { + return Err(Error::Page); + } + let fits = |size| task.pieces.as_ref().is_none_or(|p| p.fit(size)); + if !probe.version.size.is_none_or(fits) { + return Err(Error::Changed); + } + if parts.is_empty() { + return Ok((probe, false)); + } + if first { + return if old(task).same_file(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) }; + } + let link = NewLink { url: source.url.to_string(), ..NewLink::default() }; + let checked = relink::check(client, task, parts, link, source, stop).await?; + let nothing = checked.reason == relink::Reason::Nothing && checked.ranges; + if mirror::usable(&checked) || nothing { Ok((probe, true)) } else { Err(Error::Changed) } +} + +/// The version the bytes here are of. +fn old(task: &Task) -> Validators { + Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() } } /// The server sent a web page, and the task is for something else. @@ -134,7 +290,8 @@ fn finished(p: &Part) -> bool { p.end == Some(p.start + p.done) } -async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc, Vec)> { +async fn start(shared: &Shared, job: &Job, task: &Task, probe: Probe, link: &Link, stop: &mut Stop) -> Result<(Arc, Vec)> { + let hints = hints(shared, task, &probe, link, stop).await?; let parts = vec![Part { start: 0, end: probe.version.size.filter(|_| probe.ranges), done: 0 }]; let wanted = safe_name(&task.name).unwrap_or(probe.name); let (id, saved, folder) = (job.id, parts.clone(), task.folder.clone()); @@ -148,6 +305,8 @@ async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc task.etag = probe.version.etag; task.last_modified = probe.version.last_modified; task.mime = probe.mime; + task.verified = None; + hints.put_in(task); })?; store.save_parts(id, saved)?; Ok(file) @@ -156,10 +315,42 @@ async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc Ok((Arc::new(file), parts)) } +/// What the server tells about the file, and the metalink it points to. Only what the task doesn't know yet counts. +async fn hints(shared: &Shared, task: &Task, probe: &Probe, link: &Link, stop: &mut Stop) -> Result { + let mut known = metalink::File { + checksum: probe.hints.checksum.clone(), + urls: probe.hints.mirrors.clone(), + ..metalink::File::default() + }; + let same = |f: &metalink::File| f.checksum.is_some() && f.checksum == known.checksum; + if let Some(url) = probe.hints.metalink.as_ref().filter(|_| task.pieces.is_none() && probe.ranges && known.checksum.is_some()) { + let source = link.source.mirror(url.as_str())?; + match tokio::time::timeout(ASIDE, metalink::read(&shared.client, &source, stop)).await { + Ok(Err(Error::Stopped)) => return Err(Error::Stopped), + Ok(Ok(files)) => { + if let Some(f) = files.into_iter().find(same) { + known.pieces = f.pieces; + known.urls.extend(f.urls); + } + } + // It would have been nice to have. + _ => {} + } + } + Ok(known) +} + /// Checks that the server still has the file the parts came from. -async fn resume(job: &Job, task: &Task, file: PartialFile, mut parts: Vec, link: &Link, stop: &mut Stop) -> Result<(Arc, Vec)> { - let old = Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() }; - if !old.same_file(&link.version) { +async fn resume( + job: &Job, + task: &Task, + file: PartialFile, + mut parts: Vec, + link: &Link, + compared: bool, + stop: &mut Stop, +) -> Result<(Arc, Vec)> { + if !compared && !old(task).same_file(&link.version) { return Err(Error::Changed); } let file = Arc::new(file); @@ -202,6 +393,27 @@ pub(super) struct Job { } impl Job { + async fn task(&self) -> Result { + let id = self.id; + self.run(move |s| Ok(s.task(id)?)).await + } + + /// Ranges of the file that have to come again. A finished file becomes an unfinished one. + async fn forget(&self, whole: Whole, ranges: Vec>) -> Result<()> { + let id = self.id; + self.run(move |store| { + let task = store.task(id)?; + let parts = mirror::without(&store.parts(id)?, &ranges); + if let Whole::Finished(path) = &whole { + let _names = disk::names(); + disk::rename_new(path, &disk::partial_path(&task.folder, &task.name)).map_err(disk::Error::Io)?; + } + store.save_parts(id, parts)?; + Ok(()) + }) + .await + } + pub(super) async fn run(&self, work: impl FnOnce(&Store) -> Result + Send + 'static) -> Result { let store = self.store.clone(); blocking(move || work(&store)).await diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index d31ece9..87f7e91 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -211,6 +211,42 @@ pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> same_body(&link.client, send_range(link, at, Some(at + len), stop).await?, known, stop).await } +/// `len` bytes at `at`. +pub(crate) async fn bytes_at(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result> { + let response = send_range(link, at, Some(at + len), stop).await?; + let data = all(&link.client, response, len, stop).await?; + if data.len() as u64 == len { Ok(data) } else { Err(Error::Cut { got: data.len() as u64, expected: Some(len) }) } +} + +/// A whole file of at most `max` bytes that is no web page. +pub(crate) async fn small(client: &Client, source: &Source, max: u64, stop: &mut Stop) -> Result> { + let response = source.get(client, None, None, stop).await?; + let headers = response.headers(); + if response.status() != StatusCode::OK { + return Err(status_error(&response)); + } + if page(name::mime(headers).as_deref()) { + return Err(Error::Page); + } + check_encoding(headers, response.url())?; + all(client, response, max, stop).await +} + +async fn all(client: &Client, mut response: Response, max: u64, stop: &mut Stop) -> Result> { + let mut data = vec![]; + loop { + let chunk = tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + chunk = client.wait(response.chunk()) => chunk?, + }; + let Some(chunk) = chunk else { return Ok(data) }; + if data.len() as u64 + chunk.len() as u64 > max { + return Err(Error::BadReply("more than there should be".into())); + } + data.extend_from_slice(&chunk); + } +} + /// Whether the body begins with `known`. pub(crate) async fn same_body(client: &Client, mut response: Response, known: &[u8], stop: &mut Stop) -> Result { let mut rest = known; diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 272180c..0983793 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -10,9 +10,9 @@ mod probe; pub use download::{Options, Shared, download}; pub(crate) use download::is_page; -pub(crate) use fetch::same_body; +pub(crate) use fetch::{bytes_at, same_body, small}; pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes}; -pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot}; +pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot}; pub use name::safe as safe_name; pub(crate) use piece::piece; pub use probe::{Probe, probe}; @@ -66,6 +66,8 @@ pub enum Error { Cut { got: u64, expected: Option }, /// Finished bytes are recorded, but their file is gone. Missing, + /// The whole file isn't what its checksum says. + Checksum, Disk(disk::Error), Store(store::Error), } @@ -249,6 +251,12 @@ impl Source { Source { url: url.clone(), headers, access: self.access.clone(), remote: self.remote.clone() } } + /// Another link to the same file. What was given for one site stays with it. + pub fn mirror(&self, url: &str) -> Result { + let url = Source::new(url)?.url; + Ok(Source { remote: Remote::of(&url).map(Arc::new), ..self.at(&url) }) + } + pub(crate) fn remote(&self) -> Option<&Remote> { self.remote.as_deref() } diff --git a/crates/core/src/http/monitor.rs b/crates/core/src/http/monitor.rs index 7e32173..d7ab27b 100644 --- a/crates/core/src/http/monitor.rs +++ b/crates/core/src/http/monitor.rs @@ -45,6 +45,27 @@ pub struct PartView { pub fails: u32, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServerState { + /// Not compared yet. + Waiting, + Checking, + Ready, + /// Another file, or it failed. + Out, +} + +/// A link that the download uses, or would like to. +#[derive(Debug, Clone, PartialEq)] +pub struct ServerView { + /// Name and port. Empty until it was reached. + pub host: String, + pub state: ServerState, + pub connections: u32, + /// Bytes per second of one connection. + pub speed: f64, +} + #[derive(Debug, Clone, Default, PartialEq)] pub struct Snapshot { pub size: Option, @@ -57,6 +78,10 @@ pub struct Snapshot { pub received: u64, /// Bytes per second. pub speed: f64, + /// The one the others are compared with first. + pub servers: Vec, + /// Share of the file that was compared with its checksum, while that goes on. + pub checked: Option, } /// One per download; outlives its runs. @@ -67,6 +92,7 @@ pub struct Monitor { state: Mutex<(Snapshot, Vec>)>, flow: Arc, finish: watch::Sender, + checked: Arc>>, } impl Monitor { @@ -76,7 +102,7 @@ impl Monitor { } pub fn with_flow(cap: u32, flow: Flow) -> Monitor { - Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow), finish: watch::Sender::new(false) } + Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow), finish: watch::Sender::new(false), checked: Arc::default() } } /// The limits that count for it. @@ -110,9 +136,15 @@ impl Monitor { let p = part.get(); (view.start, view.end, view.done) = (p.start, p.end, part.pos() - p.start); } + shot.checked = *self.checked.lock().unwrap(); shot } + /// Where the comparison with the checksum says how far it is. + pub(super) fn checked(&self) -> Arc>> { + self.checked.clone() + } + pub(crate) fn cap(&self) -> watch::Receiver { self.cap.subscribe() } diff --git a/crates/core/src/http/parts.rs b/crates/core/src/http/parts.rs index df5ccd2..3127b57 100644 --- a/crates/core/src/http/parts.rs +++ b/crates/core/src/http/parts.rs @@ -2,15 +2,17 @@ use super::download::Job; use super::fetch::fetch_within; -use super::monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot}; +use super::monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot}; use super::*; use crate::adapt::Adapt; use crate::disk::PartialFile; -use crate::host::{Hosts, Member, Permit}; -use crate::model::{ErrorKind, Part}; +use crate::host::{self, Hosts, Member, Permit}; +use crate::mirror::{self, NEEDED}; +use crate::model::{ErrorKind, Part, Task}; use crate::part::LivePart; use crate::segment::{self, Pick, View}; use std::hash::{BuildHasher, RandomState}; +use std::ops::Range; use std::sync::Arc; use std::time::Instant; use tokio::task::JoinSet; @@ -19,13 +21,22 @@ use tokio::time::{MissedTickBehavior, interval}; /// Speeds are averaged over about this many ticks. const SMOOTH: u32 = 8; +/// The server the others are compared with. +const BASE: usize = 0; + pub(super) struct Run<'a> { - link: Arc, + shared: &'a Shared, + task: Arc, + /// The base first, then the mirrors. + servers: Vec, + checks: JoinSet<(usize, Result>)>, + /// Why the last server that was given up failed. + gave_up: Option, + /// Servers whose bytes have to come again. Nothing runs meanwhile. + distrusted: Vec, file: Arc, body: Option, - host: String, hosts: Arc, - member: Member, /// Its speed had a limit, so it says nothing about the host. limited: bool, max_parts: Option, @@ -47,6 +58,49 @@ pub(super) struct Run<'a> { worked: u32, } +/// One link to the file. +struct Server { + /// As the task has it. + url: String, + source: Source, + state: ServerState, + ready: Option, + /// Bytes per second of one of its connections. + speed: Option, + /// No connection before this. + rest_until: Option, + /// In a row, without a byte. + fails: u32, + /// Connections it stands, as far as it said so. Counts only beside others. + cap: u32, + used: bool, + /// What came from it. + gave: Vec>, +} + +struct Ready { + link: Arc, + host: String, + member: Member, +} + +impl Server { + fn new(url: String, source: Source) -> Server { + Server { url, source, state: ServerState::Waiting, ready: None, speed: None, rest_until: None, fails: 0, cap: u32::MAX, used: false, gave: vec![] } + } + + fn open(&self, now: Instant) -> bool { + self.state == ServerState::Ready && self.rest_until.is_none_or(|until| now >= until) + } + + fn got(&mut self, range: Range) { + match self.gave.iter_mut().find(|r| r.end == range.start) { + Some(r) => r.end = range.end, + None => self.gave.push(range), + } + } +} + struct Slot { id: PartId, part: Arc, @@ -59,9 +113,14 @@ struct Slot { swaps: u32, /// Had a connection before. used: bool, + /// The server its last bytes came from. + last: Option, } struct Worker { + server: usize, + /// Where it began. + from: u64, stop: watch::Sender, permit: Permit, leaving: bool, @@ -87,6 +146,15 @@ impl Slot { } } +/// What is left of a run. +pub(super) struct Ended { + pub live: Vec>, + /// The number of connections to remember for the base's host. + pub learned: Option, + /// The links, the base's first, and what came from each. + pub gave: Vec<(String, Vec>)>, +} + /// What an error of one part means for the download. enum Weight { Fatal, @@ -113,24 +181,33 @@ fn weigh(e: &Error) -> Weight { impl<'a> Run<'a> { #[allow(clippy::too_many_arguments)] pub(super) fn new( - shared: &Shared, - link: Link, + shared: &'a Shared, + task: Arc, + base: (String, Link), + mirrors: Vec<(String, Source)>, file: Arc, parts: Vec, body: Option, host: String, start: u32, - max_parts: Option, options: &'a Options, monitor: &'a Monitor, ) -> Run<'a> { let cap = *monitor.cap().borrow(); + let max_parts = task.max_parts; + let (url, link) = base; + let mut base = Server::new(url, link.source.clone()); + base.ready = Some(Ready { member: shared.hosts.join(&host), link: Arc::new(link), host }); + base.state = ServerState::Ready; let mut run = Run { - link: Arc::new(link), + shared, + task, + servers: std::iter::once(base).chain(mirrors.into_iter().map(|(url, source)| Server::new(url, source))).collect(), + checks: JoinSet::new(), + gave_up: None, + distrusted: vec![], file, body, - member: shared.hosts.join(&host), - host, hosts: shared.hosts.clone(), limited: false, max_parts, @@ -167,12 +244,18 @@ impl<'a> Run<'a> { } let mut saving = JoinSet::new(); loop { - if self.failed.is_none() { + if !self.distrusted.is_empty() && self.workers.is_empty() && self.failed.is_none() { + self.take_back(); + checkpoint.reset_immediately(); + } + if self.failed.is_none() && self.distrusted.is_empty() { let flow = self.monitor.flow(); self.limited |= flow.limited(); let cap = *cap.borrow_and_update(); self.adapt.set_cap(cap.min(self.max_parts.unwrap_or(u32::MAX)).min(flow.connections())); - self.schedule(Instant::now()); + let now = Instant::now(); + self.look_at_mirrors(); + self.schedule(now); } self.publish(); if self.workers.is_empty() && (self.failed.is_some() || self.slots.iter().all(|s| s.part.finished())) { @@ -183,6 +266,10 @@ impl<'a> Run<'a> { Ok((id, result)) => self.ended(id, result, Instant::now()), Err(e) => std::panic::resume_unwind(e.into_panic()), }, + Some(checked) = self.checks.join_next() => match checked { + Ok((server, result)) => self.checked(server, result), + Err(e) => std::panic::resume_unwind(e.into_panic()), + }, _ = tick.tick() => self.measure(Instant::now()), _ = checkpoint.tick(), if saving.is_empty() => { let (job, live, file) = (job.clone(), self.live(), self.file.clone()); @@ -207,9 +294,187 @@ impl<'a> Run<'a> { self.failed.take().map_or(Ok(()), Err) } - /// The parts, and the number of connections to remember for the host. Lets go of the file. - pub(super) fn end(self) -> (Vec>, Option) { - (self.live(), self.adapt.learned().filter(|_| self.link.ranges && !self.limited)) + /// Lets go of the file. + pub(super) fn end(self) -> Ended { + let alone = self.servers.iter().filter(|s| s.used).count() == 1; + let learned = self.adapt.learned().filter(|_| self.base().ranges && !self.limited && alone); + let live = self.live(); + Ended { live, learned, gave: self.servers.into_iter().map(|s| (s.url, s.gave)).collect() } + } + + fn base(&self) -> &Arc { + &self.servers[BASE].ready.as_ref().expect("the base is always ready").link + } + + // Mirrors. + + /// Compares the next one, when enough is here for that. + fn look_at_mirrors(&mut self) { + let Some(i) = self.servers.iter().position(|s| s.state == ServerState::Waiting) else { return }; + if !self.checks.is_empty() || !self.can_check() { + return; + } + let parts: Vec = self.slots.iter().map(|s| s.part.get()).collect(); + self.servers[i].state = ServerState::Checking; + let (shared, task, base, source) = (self.shared.clone(), self.task.clone(), self.base().clone(), self.servers[i].source.clone()); + self.checks.spawn(async move { + let (_keep, stop) = watch::channel(false); + let check = async { + let Some(link) = mirror::check(shared.client, (*task).clone(), parts, (*base).clone(), source, stop).await? else { return Ok(None) }; + let host = host::key(&link.source.url); + let (store, asked) = (shared.store.clone(), host.clone()); + let known = crate::disk::blocking(move || store.host(&asked)).await?.unwrap_or_default(); + // The limit of a host counts for a whole download; that is the base's. + let limited = link.source.speed_limit().or(known.speed_limit).is_some(); + if limited && host != host::key(&base.source.url) { + return Ok(None); + } + shared.hosts.set_host_cap(&host, link.source.max_connections().or(known.max_connections)); + Ok(Some(link)) + }; + (i, check.await) + }); + } + + fn can_check(&self) -> bool { + self.base().ranges && self.slots.iter().map(|s| s.part.get().done).sum::() >= NEEDED + } + + fn checked(&mut self, i: usize, result: Result>) { + let s = &mut self.servers[i]; + match result { + Ok(Some(link)) => { + let host = host::key(&link.source.url); + s.ready = Some(Ready { member: self.hosts.join(&host), link: Arc::new(link), host }); + s.state = ServerState::Ready; + } + other => { + log::debug!("mirror {i} not used: {:?}", other.err()); + s.state = ServerState::Out; + self.any_left(); + } + } + } + + /// Whether another one than `i` can go on, now or after its comparison. + fn others_than(&self, i: usize) -> bool { + let can_check = self.can_check(); + self.servers.iter().enumerate().any(|(j, s)| { + j != i + && match s.state { + ServerState::Ready | ServerState::Checking => true, + ServerState::Waiting => can_check, + ServerState::Out => false, + } + }) + } + + /// Gives a server up. Its bytes come again if it is not trusted any more. + fn expel(&mut self, i: usize, e: Error, trusted: bool) { + log::debug!("server {i} given up: {e:?}"); + self.servers[i].state = ServerState::Out; + self.gave_up = Some(e); + for s in self.slots.iter_mut().filter(|s| s.worker.as_ref().is_some_and(|w| w.server == i)) { + s.send_away(); + } + if !trusted { + self.distrusted.push(i); + self.slots.iter_mut().for_each(Slot::send_away); + } + self.any_left(); + } + + fn any_left(&mut self) { + if !self.others_than(usize::MAX) + && let Some(e) = self.gave_up.take() + { + self.fail(e); + } + } + + /// Nothing runs: the parts lose what came from the distrusted ones. + fn take_back(&mut self) { + let bad: Vec<_> = self.distrusted.drain(..).flat_map(|i| std::mem::take(&mut self.servers[i].gave)).collect(); + let parts: Vec = self.slots.iter().map(|s| s.part.get()).collect(); + self.slots.clear(); + for p in mirror::without(&parts, &bad) { + let slot = self.slot(p); + self.events.push(PartEvent::Born { id: slot.id, start: p.start, end: p.end }); + self.slots.push(slot); + } + self.merge(); + } + + fn running_on(&self, i: usize) -> u32 { + self.slots.iter().filter_map(Slot::running).filter(|w| w.server == i).count() as u32 + } + + fn many(&self) -> bool { + self.servers.iter().filter(|s| s.state == ServerState::Ready).count() > 1 + } + + /// A place for one more connection at the server that brings the most; one that wasn't tried comes first. + fn place(&self, weight: f64, now: Instant) -> Option<(usize, Permit)> { + let many = self.many(); + let mut open: Vec = (0..self.servers.len()).filter(|i| self.servers[*i].open(now)).collect(); + // One that has just begun is taken for an average one. + let speed = |i: &usize| { + let s = &self.servers[*i]; + if s.used { s.speed.unwrap_or(self.usual) } else { f64::INFINITY } + }; + open.sort_by(|a, b| speed(b).total_cmp(&speed(a))); + open.into_iter().find_map(|i| { + let running = self.running_on(i); + if many && running >= self.servers[i].cap { + return None; + } + let wanted = if many { running + 1 } else { self.wanted() }; + Some((i, self.servers[i].ready.as_ref()?.member.open(wanted, weight, now)?)) + }) + } + + /// Others on the host get what isn't used. + fn tell_hosts(&self, wanted: u32, weight: f64) { + let many = self.many(); + for (i, s) in self.servers.iter().enumerate() { + let Some(r) = &s.ready else { continue }; + let wanted = match s.state { + ServerState::Ready if many => self.running_on(i) + 1, + ServerState::Ready => wanted, + _ => 0, + }; + r.member.wants(wanted, weight); + } + } + + /// Moves one connection to a server that is far faster, or that wasn't tried. + fn balance(&mut self, now: Instant) { + let idle = |s: &Slot| s.worker.as_ref().is_none_or(|w| !w.leaving); + if !self.many() || self.running() < 2 || self.running() < self.wanted() || !self.slots.iter().all(idle) { + return; + } + let untried = self.servers.iter().any(|s| s.open(now) && !s.used); + let best = (0..self.servers.len()).filter(|i| self.servers[*i].open(now) && self.running_on(*i) < self.servers[*i].cap); + let best = best.filter_map(|i| Some((i, self.servers[i].speed?))).max_by(|a, b| a.1.total_cmp(&b.1)); + let (usual, options) = (self.usual, self.options); + let speed = |w: &Worker| w.speed.unwrap_or(usual); + // Within limits the slow ones only wait for their turn. + let limited = self.monitor.flow().limited(); + let slowest = self.slots.iter_mut().filter(|s| s.running().is_some()).min_by(|a, b| { + let of = |s: &Slot| s.running().map_or(f64::INFINITY, speed); + of(a).total_cmp(&of(b)) + }); + let Some(s) = slowest else { return }; + let patience = options.patience * (1 << s.swaps.min(8)); + let Some(w) = s.running() else { return }; + let long = w.delivers.is_some_and(|since| now - since >= patience); + let far = best.is_some_and(|(i, best)| i != w.server && speed(w) < best / 4.0); + if untried { + s.send_away(); + } else if long && far && !limited { + s.swaps += 1; + s.send_away(); + } } fn live(&self) -> Vec> { @@ -218,7 +483,7 @@ impl<'a> Run<'a> { fn slot(&mut self, part: Part) -> Slot { self.next_id += 1; - Slot { id: self.next_id, part: LivePart::new(part), worker: None, rest_until: None, fails: 0, swaps: 0, used: false } + Slot { id: self.next_id, part: LivePart::new(part), worker: None, rest_until: None, fails: 0, swaps: 0, used: false, last: None } } fn fail(&mut self, e: Error) { @@ -235,17 +500,17 @@ impl<'a> Run<'a> { } fn wanted(&self) -> u32 { - if self.link.ranges { self.adapt.target() } else { 1 } + if self.base().ranges { self.adapt.target() } else { 1 } } fn schedule(&mut self, now: Instant) { - if !self.link.ranges { + if !self.base().ranges { // One part without resume: no cuts, no second connection. let i = self.slots.iter().position(|s| !s.part.finished()); if let Some(i) = i.filter(|i| self.slots[*i].worker.is_none()) - && let Some(permit) = self.member.open(1, self.monitor.flow().weight(), now) + && let Some(permit) = self.servers[BASE].ready.as_ref().and_then(|r| r.member.open(1, self.monitor.flow().weight(), now)) { - self.begin(i, permit, now); + self.begin(i, BASE, permit, now); } return; } @@ -262,6 +527,7 @@ impl<'a> Run<'a> { slowest.map(Slot::send_away); } self.drop_stalled(now); + self.balance(now); let weight = self.monitor.flow().weight(); // How many it could use. let mut use_of = self.wanted(); @@ -276,9 +542,9 @@ impl<'a> Run<'a> { self.drop_crawling(&views, now); break; }; - let Some(permit) = self.member.open(self.wanted(), weight, now) else { break }; + let Some((server, permit)) = self.place(weight, now) else { break }; match pick { - Pick::Take(i) => self.begin(i, permit, now), + Pick::Take(i) => self.begin(i, server, permit, now), Pick::Split { part, at } => { let end = views[part].end; // False when it got beyond `at` in the meantime. @@ -288,11 +554,11 @@ impl<'a> Run<'a> { let slot = self.slot(Part { start: at, end: Some(end), done: 0 }); self.events.push(PartEvent::Split { from: self.slots[part].id, id: slot.id, at, end }); self.slots.insert(part + 1, slot); - self.begin(part + 1, permit, now); + self.begin(part + 1, server, permit, now); } } } - self.member.wants(use_of, weight); + self.tell_hosts(use_of, weight); } /// A connection that brings nothing is replaced. One that never did only while others do: the server may be slow to answer. @@ -327,16 +593,21 @@ impl<'a> Run<'a> { } } - fn begin(&mut self, i: usize, permit: Permit, now: Instant) { + fn begin(&mut self, i: usize, server: usize, permit: Permit, now: Instant) { + let from = &mut self.servers[server]; + from.used = true; + let link = from.ready.as_ref().expect("only ready ones are used").link.clone(); let s = &mut self.slots[i]; if s.used { self.events.push(PartEvent::Stolen { id: s.id }); } let (stop, stopping) = watch::channel(false); let first = s.part.received(); - s.worker = Some(Worker { stop, permit, leaving: false, first, seen: first, quiet_since: now, delivers: None, speed: None }); + let p = s.part.get(); + s.worker = Some(Worker { server, from: p.start + p.done, stop, permit, leaving: false, first, seen: first, quiet_since: now, delivers: None, speed: None }); (s.used, s.rest_until) = (true, None); - let (id, link, part, file, body) = (s.id, self.link.clone(), s.part.clone(), self.file.clone(), self.body.take()); + let (id, part, file) = (s.id, s.part.clone(), self.file.clone()); + let body = if server == BASE { self.body.take() } else { None }; let flow = self.monitor.flow().clone(); self.workers.spawn(async move { (id, fetch_within(&link, &part, &file, body, &flow, stopping).await) }); } @@ -347,10 +618,17 @@ impl<'a> Run<'a> { let w = s.worker.take().expect("it just ended"); let got = s.part.received(); self.received += got - w.seen; + let before = s.last; + let (p, server) = (s.part.get(), &mut self.servers[w.server]); + if p.start + p.done > w.from { + server.got(w.from..p.start + p.done); + s.last = Some(w.server); + } if got > w.first { - s.fails = 0; + (s.fails, server.fails) = (0, 0); } else if result.is_err() && !w.leaving { s.fails += 1; + server.fails += 1; } match result { Ok(()) => { @@ -363,14 +641,25 @@ impl<'a> Run<'a> { self.merge(); } Err(Error::Stopped) if w.leaving => {} - Err(e) if self.failed.is_some() || !self.link.ranges => self.fail(e), - Err(e) => self.broken(i, e, now), + Err(e) if self.failed.is_some() || !self.base().ranges => self.fail(e), + // Its server was given up for the same. + Err(_) if self.servers[w.server].state == ServerState::Out => {} + Err(e) => self.broken(i, w.server, before, e, now), } } /// One part failed. The others go on. - fn broken(&mut self, i: usize, e: Error, now: Instant) { - let (others, running) = (self.delivering(), self.running()); + fn broken(&mut self, i: usize, server: usize, before: Option, e: Error, now: Instant) { + // It compared what another one brought. + let liar = before.filter(|b| matches!(e, Error::Changed) && server == BASE && *b != BASE).unwrap_or(server); + let local = matches!(e, Error::Disk(_) | Error::Store(_) | Error::Missing); + if !local && self.others_than(liar) { + return self.broken_beside_others(i, liar, e, now); + } + if liar != server { + return self.expel(liar, e, false); + } + let (others, running, host) = (self.delivering(), self.running(), self.host(server).to_string()); let retry_after = if let Error::Status { retry_after, .. } = &e { *retry_after } else { None }; let s = &mut self.slots[i]; let wait = backoff(self.options, s.fails).max(retry_after.unwrap_or_default()); @@ -379,7 +668,8 @@ impl<'a> Run<'a> { if matches!(weight, Weight::Refused { again: true }) && others == 0 && running > 0 { // Maybe too many at once, though none got anywhere: for now fewer, also if this run ends. let pause = retry_after.unwrap_or_default().min(self.options.timing.refused); - self.hosts.refused(&self.host, now + pause + self.options.timing.window * 3); + let until = now + pause + self.options.timing.window * 3; + self.hosts.refused(&host, until); } match weight { Weight::Fatal => return self.fail(e), @@ -391,18 +681,48 @@ impl<'a> Run<'a> { self.worked = running; self.adapt.refused(now, running, others > 0); if others > 0 { - self.hosts.refused(&self.host, now + self.options.timing.refused); + self.hosts.refused(&host, now + self.options.timing.refused); } } Weight::Broken => {} } if let Some(pause) = retry_after { - self.hosts.rest(&self.host, now + pause); + self.hosts.rest(&host, now + pause); } self.slots[i].rest_until = Some(now + wait); log::debug!("part {} failed, again in {wait:?}: {e:?}", self.slots[i].id); } + /// The same where another server can go on. + fn broken_beside_others(&mut self, i: usize, server: usize, e: Error, now: Instant) { + // The base's bytes are what the others were compared with. + let trusted = !matches!(e, Error::Changed) || server == BASE; + let weight = weigh(&e); + if matches!(weight, Weight::Fatal | Weight::Refused { again: false }) || self.servers[server].fails >= self.options.tries { + return self.expel(server, e, trusted); + } + let retry_after = if let Error::Status { retry_after, .. } = &e { retry_after.unwrap_or_default() } else { Duration::ZERO }; + let running = self.running_on(server); + if matches!(weight, Weight::Refused { .. }) { + self.hosts.refused(self.host(server), now + self.options.timing.refused); + self.servers[server].cap = running.max(1); + } + let wait = backoff(self.options, self.servers[server].fails).max(retry_after); + let s = &mut self.servers[server]; + // Those that still run show that it isn't down. + if running == 0 || !retry_after.is_zero() { + s.rest_until = Some(now + wait); + } + if !self.servers.iter().any(|s| s.open(now)) { + self.slots[i].rest_until = Some(now + wait); + } + log::debug!("part {} failed at server {server}, again in {wait:?}: {e:?}", self.slots[i].id); + } + + fn host(&self, server: usize) -> &str { + self.servers[server].ready.as_ref().map_or("", |r| &r.host) + } + /// Neighbours that are whole become one. fn merge(&mut self) { let whole = |s: &Slot| s.worker.is_none() && s.part.finished(); @@ -449,6 +769,12 @@ impl<'a> Run<'a> { speeds.push(speed); } } + for (i, server) in self.servers.iter_mut().enumerate() { + let own: Vec = self.slots.iter().filter_map(Slot::running).filter(|w| w.server == i).filter_map(|w| w.speed).collect(); + if !own.is_empty() { + server.speed = Some(own.iter().sum::() / own.len() as f64); + } + } self.speed = smooth(self.speed, (self.received - before) as f64 / secs); // The last one left is compared with what others brought before. if speeds.len() > 1 { @@ -476,8 +802,15 @@ impl<'a> Run<'a> { PartView { id: s.id, start: p.start, end: p.end, done: s.part.pos() - p.start, state, speed, fails: s.fails } }); let shot = Snapshot { - size: self.link.version.size, + size: self.base().version.size, parts: parts.collect(), + servers: (0..self.servers.len()) + .map(|i| { + let s = &self.servers[i]; + ServerView { host: self.host(i).into(), state: s.state, connections: self.running_on(i), speed: s.speed.unwrap_or(0.0) } + }) + .collect(), + checked: None, connections: self.running(), wanted: self.wanted(), received: self.received, diff --git a/crates/core/src/http/probe.rs b/crates/core/src/http/probe.rs index f77bf3f..31bc06d 100644 --- a/crates/core/src/http/probe.rs +++ b/crates/core/src/http/probe.rs @@ -1,6 +1,7 @@ //! What a link leads to. use super::*; +use crate::metalink::{self, Hints}; #[derive(Debug)] pub struct Probe { @@ -12,6 +13,8 @@ pub struct Probe { /// Safe to use as a file name. pub name: String, pub mime: Option, + /// Checksum and mirrors the headers tell of. + pub hints: Hints, /// The whole file, already on its way: the server sent it instead of a range. Use it, or drop it to hang up. pub body: Option, } @@ -44,6 +47,7 @@ pub async fn probe(client: &Client, source: &Source, stop: &mut Stop) -> Result< version: Validators::of(headers, size), name: name::pick(source, &url, headers), mime: name::mime(headers), + hints: metalink::hints(headers, &url), body: None, url, }; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 415ae11..0cd25cd 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,6 +14,8 @@ pub mod limit; pub mod listing; pub mod logging; pub mod manager; +pub mod metalink; +pub mod mirror; pub mod model; pub mod net_state; pub mod part; @@ -34,5 +36,6 @@ pub mod stream; pub mod strings; pub mod tls; mod transport; +pub mod verify; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 603a84b..6248354 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -21,7 +21,8 @@ use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals}; use crate::speed::{History, Meter}; use crate::store::{self, Store}; use crate::stream::{self, Tools}; -use crate::{adopt, disk, host, redact, site, strings, tr}; +use crate::verify::Checksum; +use crate::{adopt, disk, host, metalink, redact, site, strings, tr, verify}; use arc_swap::ArcSwap; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::path::{Path, PathBuf}; @@ -72,6 +73,8 @@ struct Run { known: bool, /// What was on disk before it began. had: u64, + /// It was done before: only compares it again. + again: bool, } /// What a waiting download waits for. @@ -111,6 +114,7 @@ struct Entry { resumable: Option, /// Its next run ends a stream at once. finish: bool, + checked: f32, meter: Meter, history: Arc, /// Bytes of the second that isn't over. @@ -139,6 +143,7 @@ impl Entry { wanted: 0, resumable: None, finish: false, + checked: 0.0, meter: Meter::default(), history: Arc::default(), second: 0, @@ -191,7 +196,7 @@ impl Entry { connections: self.connections, wanted: self.wanted, resumable: self.resumable, - checked: 0.0, + checked: if self.task.state == State::Checking { self.checked } else { 0.0 }, retry_at: if let Some(Hold::Until(_, at)) = self.hold { Some(at) } else { None }, fails: self.fails, server: self.host.clone(), @@ -381,6 +386,8 @@ impl Actor { Msg::Command(command, answer) => self.command(command, answer), Msg::Check(id, link, answer) => self.check(id, link, answer), Msg::CheckPartial(path, link, answer) => self.check_partial(path, link, answer), + Msg::FindChecksum(id, answer) => self.find_checksum(id, answer), + Msg::ReadMetalink(link, answer) => self.read_metalink(link, answer), Msg::Limits(limits) => self.set_limits(limits), Msg::OnChange(call) => self.on_change.push(call), Msg::Ended(id, result) => self.ended(id, result), @@ -511,7 +518,7 @@ impl Actor { fn must_wait(&self, id: TaskId, command: &Command) -> bool { use Command::*; let e = &self.entries[&id]; - let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | Restore(_) | Continue { .. }); + let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | OtherMirror(_) | Restore(_) | Continue { .. }); !e.todo.is_empty() || match e.work { None => false, @@ -607,6 +614,20 @@ impl Actor { None => result = Err(Error::Name), }, Command::Edit { edit, .. } => result = self.change(id, edit), + Command::Verify(_) if state == Done => return self.verify(id, answer), + Command::Verify(_) => {} + Command::OtherMirror(_) => { + let Some(next) = self.entries[&id].task.mirrors.first().cloned() else { return self.answer(answer, Ok(id)) }; + // The link of now becomes the last one. + result = self.change(id, |t| { + let old = std::mem::replace(&mut t.url, next); + t.mirrors.remove(0); + t.mirrors.push(old); + }); + if result.is_ok() { + return self.apply(id, Command::Redownload(id), answer); + } + } Command::AwaitLink(_) => result = self.await_link(id), Command::Continue { checked, .. } => return self.go_on(id, *checked, answer), Command::Remove { .. } | Command::KeepBoth(_) => {} @@ -623,6 +644,8 @@ impl Actor { task.state = State::Queued; } task.name = safe_name(&task.name).unwrap_or_default(); + task.checksum = task.checksum.map(verify::plain); + task.verified = None; (task.error, task.downloaded, task.finished_at, task.removed_at) = (None, 0, None, None); if task.position == 0.0 { task.position = self.last_position + 1.0; @@ -669,6 +692,30 @@ impl Actor { }); } + fn find_checksum(&self, id: TaskId, answer: oneshot::Sender>>) { + let Some(e) = self.entries.get(&id).filter(|e| !e.removed()) else { + let _ = answer.send(Err(store::Error::NotFound.into())); + return; + }; + let (task, shared, sites) = (e.task.clone(), self.config.shared.clone(), self.config.sites.clone()); + self.look(answer, e.host.clone(), async move { + let (_keep, mut stop) = watch::channel(false); + let source = site::source(sites.as_ref(), &task, &stop).await?; + verify::sidecar(&shared.client, &source, &mut stop).await + }); + } + + fn read_metalink(&self, link: NewLink, answer: oneshot::Sender>>) { + let (shared, sites) = (self.config.shared.clone(), self.config.sites.clone()); + self.look(answer, host_of(&link.url), async move { + let (_keep, mut stop) = watch::channel(false); + let mut task = Task::default(); + link.put_in(&mut task); + let source = site::source(sites.as_ref(), &task, &stop).await?; + metalink::read(&shared.client, &source, &mut stop).await + }); + } + fn check_partial(&self, path: PathBuf, link: NewLink, answer: oneshot::Sender>) { let (shared, sites) = (self.config.shared.clone(), self.config.sites.clone()); self.look(answer, host_of(&link.url), async move { @@ -770,7 +817,7 @@ impl Actor { return Ok(()); } self.entry(id).forced = 0; - if state == State::Running { + if matches!(state, State::Running | State::Checking) { self.stop_run(id); } self.set_state(id, State::Paused, None) @@ -808,7 +855,7 @@ impl Actor { t.queue = new.queue; t.position = new.position; t.priority = new.priority; - t.checksum = new.checksum; + t.checksum = new.checksum.map(verify::plain); t.max_parts = new.max_parts; t.tries = new.tries; t.speed_limit = new.speed_limit; @@ -900,7 +947,7 @@ impl Actor { /// Takes a running one's place away. fn suspend(&mut self, id: TaskId) { - if self.entries[&id].task.state == State::Running { + if matches!(self.entries[&id].task.state, State::Running | State::Checking) { self.stop_run(id); self.move_to(id, State::Queued, None); } @@ -973,6 +1020,23 @@ impl Actor { log::error!("task {id} not started: {e}"); return; } + self.launch(id, false); + } + + /// Compares a finished file with its checksum once more. + fn verify(&mut self, id: TaskId, answer: Option) { + let task = &self.entries[&id].task; + let wanted = task.checksum.is_some() || task.pieces.is_some(); + // Without them it would be downloaded. + let known = self.store.parts(id).is_ok_and(|p| !p.is_empty()); + let result = if wanted && known { self.set_state(id, State::Checking, None) } else { Ok(()) }; + if wanted && known && result.is_ok() { + self.launch(id, true); + } + self.answer(answer, result.map(|()| id)); + } + + fn launch(&mut self, id: TaskId, again: bool) { let task = self.entries[&id].task.clone(); if let Err(e) = Source::new(&task.url) { return self.failed(id, &Why::Http(e)); @@ -982,7 +1046,7 @@ impl Actor { flow.put(Group::Queue(task.queue)); flow.set(task.speed_limit); let monitor = Arc::new(Monitor::with_flow(unlimited(self.config.limits.parts_per_download), flow)); - let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded }; + let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded, again }; if std::mem::take(&mut self.entry(id).finish) { monitor.finish(); } @@ -1012,6 +1076,7 @@ impl Actor { e.log(&tr!("log.connect", server = e.host)); e.counters.runs += 1; e.meter = Meter::default(); + e.checked = 0.0; e.work = Some(Work::Run(run)); } @@ -1034,7 +1099,7 @@ impl Actor { fn ended(&mut self, id: TaskId, result: std::result::Result) { self.measure(id, Duration::ZERO); - let had = if let Some(Work::Run(run)) = &self.entries[&id].work { run.had } else { 0 }; + let (had, again) = if let Some(Work::Run(run)) = &self.entries[&id].work { (run.had, run.again) } else { (0, false) }; self.runs.remove(&id); let reloaded = self.reload(id, true); let e = self.entry(id); @@ -1047,9 +1112,13 @@ impl Actor { self.entry(id).fails = 0; } match result { + Ok(_) if again && self.entries[&id].task.state == State::Checking => { + self.move_to(id, State::Done, None); + self.entry(id).took(None); + } Ok(_) => self.finished(id), Err(Why::Http(http::Error::Stopped)) => self.suspend(id), - Err(why) if self.entries[&id].task.state == State::Running => self.failed(id, &why), + Err(why) if matches!(self.entries[&id].task.state, State::Running | State::Checking) => self.failed(id, &why), // It was being stopped anyway. Err(why) => { let text = self.failure(id, &why).text; @@ -1241,7 +1310,7 @@ impl Actor { /// Lets the computer sleep when no download is being stopped any more. fn saved(&mut self) { - if self.runs.iter().all(|id| self.entries[id].task.state == State::Running) { + if self.runs.iter().all(|id| matches!(self.entries[id].task.state, State::Running | State::Checking)) { self.going = None; } } @@ -1362,6 +1431,7 @@ impl Actor { fn measure(&mut self, id: TaskId, dt: Duration) { let Some(Work::Run(run)) = self.entries.get_mut(&id).and_then(|e| e.work.as_mut()) else { return }; let shot = run.monitor.snapshot(); + let again = run.again; let bytes = shot.received.saturating_sub(run.received); run.received = shot.received.max(run.received); let first = !run.known && !shot.parts.is_empty(); @@ -1374,6 +1444,21 @@ impl Actor { self.second += bytes; self.totals.counters.received += bytes; self.totals.counters.active += active; + match (shot.checked, self.entries[&id].task.state) { + (Some(share), state) => { + if state == State::Running { + self.move_to(id, State::Checking, None); + } + let e = self.entries.get_mut(&id).expect("seen above"); + if e.checked != share { + e.checked = share; + self.dirty.insert(id); + } + } + // Wrong pieces come again. + (None, State::Checking) if !again && shot.parts.iter().any(|p| p.state != PartState::Done) => self.move_to(id, State::Running, None), + _ => {} + } let e = self.entries.get_mut(&id).expect("seen above"); e.second += bytes; e.counters.received += bytes; diff --git a/crates/core/src/manager/files.rs b/crates/core/src/manager/files.rs index b86c9d1..d5852de 100644 --- a/crates/core/src/manager/files.rs +++ b/crates/core/src/manager/files.rs @@ -183,6 +183,7 @@ pub fn discard(store: &Store, id: TaskId) -> Result<()> { store.save_parts(id, vec![])?; store.edit_task(id, |t| { (t.size, t.etag, t.last_modified, t.mime, t.finished_at, t.downloaded) = (None, None, None, None, None, 0); + t.verified = None; })?; Ok(()) } diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index 88b8ea4..d2477a6 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -21,7 +21,9 @@ use crate::recover::sleep::Sleep; use crate::relink::{Checked, NewLink}; use crate::settings::Limits; use crate::site::Sites; +use crate::metalink; use crate::snapshot::Snapshot; +use crate::verify::Checksum; use crate::{store, tr}; use arc_swap::ArcSwap; use std::fmt; @@ -114,6 +116,10 @@ pub enum Command { Move { id: TaskId, folder: PathBuf }, /// Renames the file too. A taken name gets a number. Rename { id: TaskId, name: String }, + /// Compares a finished file with its checksum, or its pieces. Nothing without them. + Verify(TaskId), + /// From the start, as a new file, from the next mirror. The link it has becomes the last mirror. + OtherMirror(TaskId), /// Changes what the user decides: link, mirrors, queue, position, priority, limits, headers, notes and the like. /// Changes of other fields are dropped. Edit { id: TaskId, edit: Box }, @@ -133,7 +139,7 @@ impl Command { use Command::*; match self { Add(_) | Adopt { .. } => None, - Start(id) | Pause(id) | Resume(id) | Stop(id) | Finish(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id), + Start(id) | Pause(id) | Resume(id) | Stop(id) | Finish(id) | Restore(id) | Redownload(id) | Verify(id) | OtherMirror(id) | KeepBoth(id) | AwaitLink(id) => Some(*id), Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id), } } @@ -204,6 +210,8 @@ type Answer = oneshot::Sender>; enum Msg { Command(Command, Option), Check(TaskId, NewLink, oneshot::Sender>), + FindChecksum(TaskId, oneshot::Sender>>), + ReadMetalink(NewLink, oneshot::Sender>>), CheckPartial(PathBuf, NewLink, oneshot::Sender>), Limits(Limits), OnChange(Box), @@ -253,6 +261,20 @@ impl Manager { Reply(reply) } + /// Looks for a checksum beside the file on its server; nothing changes. `Command::Edit` takes it. + pub fn find_checksum(&self, id: TaskId) -> Reply> { + let (answer, reply) = oneshot::channel(); + let _ = self.to.send(Msg::FindChecksum(id, answer)); + Reply(reply) + } + + /// The files in a metalink; `metalink::File::task` makes downloads of them. + pub fn read_metalink(&self, link: NewLink) -> Reply> { + let (answer, reply) = oneshot::channel(); + let _ = self.to.send(Msg::ReadMetalink(link, answer)); + Reply(reply) + } + /// The same for an unfinished file of another program. pub fn check_partial(&self, path: PathBuf, link: NewLink) -> Reply { let (answer, reply) = oneshot::channel(); diff --git a/crates/core/src/metalink.rs b/crates/core/src/metalink.rs new file mode 100644 index 0000000..e449255 --- /dev/null +++ b/crates/core/src/metalink.rs @@ -0,0 +1,452 @@ +//! Metalink: lists of sources and checksums, as files (versions 3 and 4) and as headers of a reply (RFC 6249). +//! +//! They come from anywhere: sizes, depth and counts have limits, and a document type or an entity of its own ends the reading. + +use crate::http::{self, Client, Error, Source, Stop, safe_name}; +use crate::model::Task; +use crate::tr; +use crate::verify::{Algo, Checksum, Pieces}; +use quick_xml::XmlVersion; +use quick_xml::events::{BytesStart, Event}; +use quick_xml::reader::Reader; +use reqwest::header::HeaderMap; +use std::fmt; +use std::sync::Arc; +use url::Url; + +/// Of a whole metalink file. +pub const MAX_SIZE: u64 = 16 << 20; +const MAX_DEPTH: usize = 16; +const MAX_FILES: usize = 10_000; +/// Sources kept of one file. +pub const MAX_URLS: usize = 64; +/// Of one text or attribute. +const MAX_TEXT: usize = 8192; + +/// One file of a metalink, with at least one source. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct File { + /// Safe to use as a file name. Empty when there is none. + pub name: String, + pub size: Option, + /// The strongest it has. + pub checksum: Option, + pub pieces: Option>, + /// The best first. + pub urls: Vec, +} + +impl File { + /// A download of it. + pub fn task(&self) -> Task { + let mut task = Task { url: self.urls.first().cloned().unwrap_or_default(), name: self.name.clone(), ..Task::default() }; + self.put_in(&mut task); + task + } + + /// Adds its sources, and the checksums the task doesn't have. + pub(crate) fn put_in(&self, task: &mut Task) { + for url in &self.urls { + if *url != task.url && !task.mirrors.contains(url) && task.mirrors.len() < MAX_URLS { + task.mirrors.push(url.clone()); + } + } + if task.checksum.is_none() { + task.checksum = self.checksum.as_ref().map(Checksum::to_string); + } + if task.pieces.is_none() { + task.pieces = self.pieces.clone(); + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bad { + /// Not a metalink, or a broken one. + Form, + /// Beyond the limits, or with a document type. + Unsafe, + /// Nothing in it can be downloaded. + Empty, +} + +impl fmt::Display for Bad { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&match self { + Bad::Form => tr!("metalink.form"), + Bad::Unsafe => tr!("metalink.unsafe"), + Bad::Empty => tr!("metalink.empty"), + }) + } +} + +impl std::error::Error for Bad {} + +/// Whether a link or a file leads to a metalink. +pub fn is(name: &str, mime: Option<&str>) -> bool { + let name = name.to_ascii_lowercase(); + name.ends_with(".meta4") || name.ends_with(".metalink") || matches!(mime, Some("application/metalink4+xml" | "application/metalink+xml")) +} + +/// Fetches a metalink and reads it. +pub async fn read(client: &Client, source: &Source, stop: &mut Stop) -> http::Result> { + let data = http::small(client, source, MAX_SIZE, stop).await?; + parse(&data).map_err(|e| Error::BadReply(e.to_string())) +} + +#[derive(Default)] +struct Building { + file: File, + /// Order and link; the lowest first. + urls: Vec<(i64, String)>, + checksums: Vec, + /// Kind, length, hashes. + pieces: Option<(Option, u64, Vec)>, + best: Option, + /// None: the pieces can't be used. + piece_index: Option, +} + +impl Building { + fn end(mut self) -> Option { + self.urls.sort_by_key(|(order, _)| *order); + for (_, url) in self.urls { + if !self.file.urls.contains(&url) && self.file.urls.len() < MAX_URLS { + self.file.urls.push(url); + } + } + self.file.checksum = self.checksums.into_iter().max_by_key(|c| c.algo); + let size = self.file.size; + self.file.pieces = self.best.filter(|p| size.is_none_or(|s| p.fit(s))).map(Arc::new); + (!self.file.urls.is_empty()).then_some(self.file) + } + + fn end_pieces(&mut self) { + let Some((Some(algo), size, hashes)) = self.pieces.take() else { return }; + let Some(pieces) = Pieces::new(algo, size, hashes) else { return }; + if self.best.as_ref().is_none_or(|b| b.algo < pieces.algo) { + self.best = Some(pieces); + } + } +} + +pub fn parse(data: &[u8]) -> Result, Bad> { + if data.len() as u64 > MAX_SIZE { + return Err(Bad::Unsafe); + } + let mut reader = Reader::from_reader(data); + reader.config_mut().expand_empty_elements = true; + // Names of the open elements, and what stands in the innermost one. + let mut path: Vec = vec![]; + let mut text = String::new(); + let mut attributes: Vec<(String, String)> = vec![]; + let mut files = vec![]; + let mut file: Option = None; + loop { + match reader.read_event().map_err(|_| Bad::Form)? { + Event::Start(e) => { + let name = std::str::from_utf8(e.local_name().as_ref()).map_err(|_| Bad::Form)?.to_string(); + if path.is_empty() && name != "metalink" { + return Err(Bad::Form); + } + path.push(name); + if path.len() > MAX_DEPTH { + return Err(Bad::Unsafe); + } + text.clear(); + attributes = attributes_of(&e)?; + let get = |k: &str| attributes.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()); + match (path.last().map(String::as_str), &mut file) { + (Some("file"), None) => { + if files.len() >= MAX_FILES { + return Err(Bad::Unsafe); + } + let name = get("name").and_then(safe_name).unwrap_or_default(); + file = Some(Building { file: File { name, ..File::default() }, ..Building::default() }); + } + (Some("pieces"), Some(f)) => { + let len = get("length").and_then(|l| l.parse().ok()).unwrap_or(0); + f.pieces = Some((get("type").and_then(Algo::from_name), len, vec![])); + f.piece_index = Some(0); + } + _ => {} + } + } + Event::End(_) => { + let Some(name) = path.pop() else { return Err(Bad::Form) }; + if let Some(f) = &mut file { + let get = |k: &str| attributes.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()); + let inside = path.last().map(String::as_str); + let value = text.trim(); + match (name.as_str(), inside) { + ("file", _) => files.extend(file.take().and_then(Building::end)), + ("size", Some("file")) => f.file.size = value.parse().ok(), + ("hash", Some("pieces")) => { + let Some((Some(algo), _, hashes)) = &mut f.pieces else { continue }; + let hash = format!("{}:{value}", algo.name()).parse::(); + // Version 3 numbers them. + let place = get("piece").map_or(f.piece_index, |p| p.parse().ok()); + match hash { + Ok(hash) if place.is_some() && place == f.piece_index && hashes.len() < algo.len() * crate::verify::MAX_PIECES => { + hashes.extend(hash.hash); + f.piece_index = place.map(|p| p + 1); + } + // One missing makes all useless. + _ => f.pieces = None, + } + } + ("hash", Some("file" | "verification")) => { + let algo = get("type").and_then(Algo::from_name); + f.checksums.extend(algo.and_then(|a| format!("{}:{value}", a.name()).parse().ok())); + } + ("pieces", _) => f.end_pieces(), + ("url", Some("file" | "resources")) => { + let number = |k| get(k).and_then(|n| n.parse::().ok()); + // Version 3: more is better. Version 4: less is. + let order = number("preference").map(|p| 1_000_000 - p.clamp(0, 1_000_000)).or(number("priority")); + if f.urls.len() < MAX_URLS * 4 && let Some(url) = usable(value) { + f.urls.push((order.unwrap_or(1_000_001), url)); + } + } + _ => {} + } + } + text.clear(); + attributes.clear(); + } + Event::Text(t) => add(&mut text, &t.decode().map_err(|_| Bad::Form)?)?, + Event::CData(t) => add(&mut text, &t.decode().map_err(|_| Bad::Form)?)?, + Event::GeneralRef(r) => { + let known = match (r.resolve_char_ref(), &*r) { + (Ok(Some(c)), _) => c, + (_, b"amp") => '&', + (_, b"lt") => '<', + (_, b"gt") => '>', + (_, b"quot") => '"', + (_, b"apos") => '\'', + _ => return Err(Bad::Unsafe), + }; + add(&mut text, known.encode_utf8(&mut [0; 4]))?; + } + Event::DocType(_) => return Err(Bad::Unsafe), + Event::Eof if path.is_empty() && files.is_empty() => return Err(Bad::Empty), + Event::Eof if path.is_empty() => return Ok(files), + Event::Eof => return Err(Bad::Form), + Event::Empty(_) | Event::Comment(_) | Event::Decl(_) | Event::PI(_) => {} + } + } +} + +fn add(text: &mut String, more: &str) -> Result<(), Bad> { + if text.len() + more.len() > MAX_TEXT { + // Descriptions may be long; nothing read here is. + text.clear(); + return Ok(()); + } + text.push_str(more); + Ok(()) +} + +fn attributes_of(e: &BytesStart) -> Result, Bad> { + let mut out = vec![]; + for a in e.attributes().take(32) { + let a = a.map_err(|_| Bad::Form)?; + // Knows the five entities of XML and no others. + let value = a.normalized_value(XmlVersion::Implicit1_0).map_err(|_| Bad::Unsafe)?; + let name = std::str::from_utf8(a.key.local_name().into_inner()).map_err(|_| Bad::Form)?.to_string(); + if value.len() <= MAX_TEXT { + out.push((name, value.into_owned())); + } + } + Ok(out) +} + +/// A link that can be downloaded and holds no login. +fn usable(url: &str) -> Option { + let url = Source::new(url).ok()?.url; + (url.username().is_empty() && url.password().is_none()).then(|| url.into()) +} + +/// What the headers of a reply say about the file. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Hints { + pub checksum: Option, + /// The best first. Only with a checksum, as RFC 6249 wants it. + pub mirrors: Vec, + /// A metalink file about it. + pub metalink: Option, +} + +/// `Digest` (RFC 3230), `Repr-Digest` (RFC 9530) and `Link` (RFC 6249). `at` is where the reply came from. +pub fn hints(headers: &HeaderMap, at: &Url) -> Hints { + let values = |name: &str| -> Vec<&str> { headers.get_all(name).iter().take(64).filter_map(|v| v.to_str().ok()).collect() }; + let mut hints = Hints::default(); + let digests = ["digest", "repr-digest"].into_iter().flat_map(values).flat_map(|v| v.split(',')); + hints.checksum = digests + .filter_map(|d| { + let (algo, value) = d.trim().split_once('=')?; + Checksum::from_base64(Algo::from_name(algo.trim())?, value.trim_matches(':')) + }) + .max_by_key(|c| c.algo); + let mut mirrors: Vec<(i64, String)> = vec![]; + for value in values("link") { + for (target, parameters) in links(value) { + let get = |k: &str| parameters.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.as_str()); + let Some(url) = at.join(target).ok().and_then(|u| usable(u.as_str())) else { continue }; + let is = |rel: &str| get("rel").is_some_and(|r| r.split_ascii_whitespace().any(|r| r.eq_ignore_ascii_case(rel))); + if is("duplicate") && mirrors.len() < MAX_URLS && url != at.as_str() && mirrors.iter().all(|(_, m)| *m != url) { + mirrors.push((get("pri").and_then(|p| p.parse().ok()).unwrap_or(1_000_000), url)); + } else if is("describedby") && get("type") == Some("application/metalink4+xml") { + hints.metalink = hints.metalink.or(Url::parse(&url).ok()); + } + } + } + if hints.checksum.is_some() { + mirrors.sort_by_key(|(order, _)| *order); + hints.mirrors = mirrors.into_iter().map(|(_, url)| url).collect(); + } + hints +} + +/// `; name=value; name="value", …` +fn links(value: &str) -> Vec<(&str, Vec<(&str, String)>)> { + let mut out = vec![]; + let mut rest = value; + while let Some((_, after)) = rest.split_once('<') { + let Some((target, mut tail)) = after.split_once('>') else { break }; + let mut parameters = vec![]; + loop { + tail = tail.trim_start(); + let Some(next) = tail.strip_prefix(';') else { break }; + let end = next.find(['=', ';', ',']).unwrap_or(next.len()); + let name = next[..end].trim(); + tail = &next[end..]; + let Some(value) = tail.strip_prefix('=') else { + parameters.push((name, String::new())); + continue; + }; + let value = value.trim_start(); + if let Some(quoted) = value.strip_prefix('"') { + let Some((inner, after)) = quoted.split_once('"') else { return out }; + parameters.push((name, inner.to_string())); + tail = after; + } else { + let end = value.find([';', ',']).unwrap_or(value.len()); + parameters.push((name, value[..end].trim().to_string())); + tail = &value[end..]; + } + } + out.push((target.trim(), parameters)); + rest = tail; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use reqwest::header::{HeaderName, HeaderValue}; + + const SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + const MD5: &str = "d41d8cd98f00b204e9800998ecf8427e"; + + fn v4(inner: &str) -> String { + format!("\n{inner}") + } + + #[test] + fn version_4() { + let text = v4(&format!( + "x & y + 500{MD5} {SHA}\n + 00 + {MD5}{MD5} + https://two/f?a=1&b=2 + ftp://three/fmagnet:?xt=1http://user:pw@four/fhttp://one/f + http://t/f.torrent + sftp://h/b" + )); + let files = parse(text.as_bytes()).unwrap(); + assert_eq!(files.len(), 2); + let f = &files[0]; + assert!(!f.name.contains('/') && !f.name.starts_with('.'), "{}", f.name); + assert_eq!(f.urls, ["http://one/f", "https://two/f?a=1&b=2", "ftp://three/f"]); + assert_eq!((f.size, f.checksum.as_ref().unwrap().to_string()), (Some(500), format!("sha256:{SHA}"))); + assert_eq!(f.pieces.as_ref().unwrap().count(), 2); + let task = f.task(); + assert_eq!((task.url.as_str(), task.mirrors.len(), task.pieces.is_some()), ("http://one/f", 2, true)); + assert_eq!((files[1].name.as_str(), files[1].checksum.as_ref()), ("b", None)); + } + + #[test] + fn version_3() { + let text = format!( + "9 + {MD5}da39a3ee5e6b4b0d3255bfef95601890afd80709 + {MD5}{MD5}{MD5} + + http://b/http://t/ + http://a/" + ); + let f = parse(text.as_bytes()).unwrap().remove(0); + assert_eq!(f.urls[..2], ["http://a/", "http://b/"]); + assert_eq!(f.checksum.unwrap().algo, Algo::Sha1); + assert_eq!(f.pieces.unwrap().count(), 3); + let gap = parse(text.replace("piece=\"1\"", "piece=\"5\"").as_bytes()).unwrap().remove(0); + assert_eq!(gap.pieces, None); + let short = parse(text.replace("9", "900").as_bytes()).unwrap().remove(0); + assert_eq!(short.pieces, None, "they don't fit the size"); + } + + #[test] + fn hostile_files() { + let url = "http://a/"; + let file = format!("{url}"); + for (text, why) in [ + (format!("]>{}", v4(&file)), Bad::Unsafe), + (format!("{file}"), Bad::Unsafe), + (v4("http://a/&lol;"), Bad::Unsafe), + (v4("http://a/"), Bad::Unsafe), + (v4(&("".repeat(100) + &"".repeat(100))), Bad::Unsafe), + (v4(&"http://a/".repeat(MAX_FILES + 1)), Bad::Unsafe), + (" ".repeat(MAX_SIZE as usize + 1), Bad::Unsafe), + (format!("{file}"), Bad::Form), + (format!("{file}"), Bad::Form), + (format!("{file}".into(), Bad::Form), + (v4("javascript:1file:///etc/passwd"), Bad::Empty), + (String::new(), Bad::Empty), + ] { + assert_eq!(parse(text.as_bytes()), Err(why), "{}", &text[..text.len().min(200)]); + } + assert_eq!(parse(b"\xff\xfe<\0m\0"), Err(Bad::Form)); + let many = v4(&format!("{}", (0..5000).map(|i| format!("http://h{i}/")).collect::())); + assert_eq!(parse(many.as_bytes()).unwrap()[0].urls.len(), MAX_URLS); + let long = v4(&format!("{url}{}", "x".repeat(100_000))); + assert_eq!(parse(long.as_bytes()).unwrap().len(), 1); + } + + #[test] + fn headers() { + let at = Url::parse("https://h/d/f.iso").unwrap(); + let of = |all: &[(&str, &str)]| { + let all = all.iter().map(|(k, v)| (HeaderName::try_from(*k).unwrap(), HeaderValue::try_from(*v).unwrap())); + hints(&HeaderMap::from_iter(all), &at) + }; + let sha = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="; + let digest = format!("MD5=1B2M2Y8AsgTpgAmY7PhCfg==,SHA-256={sha}"); + let link = "; rel=duplicate; pri=2; geo=\"a,b;c\", ; rel=\"duplicate other\"; pri=1, \ + ; rel=describedby; type=\"application/metalink4+xml\", ; rel=duplicate, ; rel=duplicate"; + let h = of(&[("digest", &digest), ("link", link)]); + assert_eq!(h.checksum.unwrap().to_string(), format!("sha256:{SHA}")); + assert_eq!(h.mirrors, ["https://h/m1", "http://m/2,x"]); + assert_eq!(h.metalink.unwrap().as_str(), "https://h/d/f.meta4"); + assert_eq!(of(&[("link", link)]).mirrors, [""; 0], "nothing to check them with"); + let repr = of(&[("repr-digest", &format!("sha-256=:{sha}:"))]); + assert_eq!(repr.checksum.unwrap().algo, Algo::Sha256); + for bad in ["<", ";", "; rel=\"dup", ",,,", ";;;=;", "é"] { + let _ = links(bad); + } + assert_eq!(of(&[("digest", "SHA-256=x"), ("digest", "nonsense")]).checksum, None); + } +} diff --git a/crates/core/src/mirror.rs b/crates/core/src/mirror.rs new file mode 100644 index 0000000..b2522cd --- /dev/null +++ b/crates/core/src/mirror.rs @@ -0,0 +1,133 @@ +//! Other links to the same file, used beside the first one. +//! +//! Nothing comes from a mirror before it was compared with what is here, and with the base at places that aren't here yet. + +use crate::http::{Client, Link, Result, Source, Stop, bytes_at, same_bytes}; +use crate::model::{Part, Task}; +use crate::relink::{self, NewLink, Reason, Verdict}; +use std::hash::{BuildHasher, RandomState}; +use std::ops::Range; + +/// So many finished bytes are needed for a comparison. +pub const NEEDED: u64 = 16 * 1024; +/// Compared in one place that isn't here yet. +const SPOT: u64 = 4096; + +/// The mirror, ready for use. None if it isn't the same file, or can't be told. +pub(crate) async fn check(client: Client, task: Task, parts: Vec, base: Link, source: Source, mut stop: Stop) -> Result> { + let link = NewLink { url: source.url.to_string(), ..NewLink::default() }; + let (checked, opened) = relink::open_link(&client, &task, &parts, link, source, &mut stop).await?; + let Some(mirror) = usable(&checked).then_some(opened).flatten() else { + log::debug!("mirror refused: {:?}", checked.reason); + return Ok(None); + }; + if mirror.version.size != base.version.size { + return Ok(None); + } + if checked.reason == Reason::Samples { + for spot in spots(&parts, base.version.size.unwrap_or(0)) { + let known = bytes_at(&base, spot.start, spot.end - spot.start, &mut stop).await?; + if !same_bytes(&mirror, &known, spot.start, &mut stop).await? { + log::debug!("mirror refused: other bytes at {}", spot.start); + return Ok(None); + } + } + } + Ok(Some(mirror)) +} + +/// The comparison says it can be continued from. +pub(crate) fn usable(checked: &relink::Checked) -> bool { + checked.ranges && matches!(checked.verdict(), Verdict::Same | Verdict::ProbablySame) +} + +/// The end of the file and a place by chance, unless they are here. +fn spots(parts: &[Part], size: u64) -> Vec> { + let chance = RandomState::new().hash_one(size) % size.max(1); + let here = relink::runs(parts); + [size.saturating_sub(SPOT)..size, chance..size.min(chance + SPOT)] + .into_iter() + .filter(|s| !s.is_empty() && !here.iter().any(|r| r.start <= s.start && s.end <= r.end)) + .collect() +} + +/// The parts without `bad`, whose bytes have to come again. +pub(crate) fn without(parts: &[Part], bad: &[Range]) -> Vec { + let mut out = vec![]; + for p in parts { + let end = p.end.unwrap_or(p.start + p.done); + let mut at = p.start; + let mut cuts: Vec<_> = bad.iter().filter(|b| b.start < p.start + p.done && b.end > p.start).collect(); + cuts.sort_by_key(|b| b.start); + for b in cuts { + let (from, to) = (b.start.max(at), b.end.min(p.start + p.done)); + if from >= to { + continue; + } + if from > at { + out.push(Part { start: at, end: Some(from), done: from - at }); + } + // The rest of an unfinished part goes with it. + let last = to == p.start + p.done; + out.push(Part { start: from, end: Some(if last { end } else { to }), done: 0 }); + at = if last { end } else { to }; + } + if at < end || (p.start == end && at == end) { + out.push(Part { start: at, end: p.end, done: (p.start + p.done).saturating_sub(at) }); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn part(start: u64, end: u64, done: u64) -> Part { + Part { start, end: Some(end), done } + } + + #[test] + #[allow(clippy::single_range_in_vec_init)] + fn bad_ranges_come_again() { + let parts = [part(0, 100, 100), part(100, 200, 50), part(200, 300, 0)]; + assert_eq!(without(&parts, &[]), parts); + assert_eq!(without(&parts, &[0..100]), [part(0, 100, 0), parts[1], parts[2]]); + assert_eq!(without(&parts, &[10..20, 90..120]), [ + part(0, 10, 10), part(10, 20, 0), part(20, 90, 70), part(90, 100, 0), part(100, 120, 0), part(120, 200, 30), parts[2] + ]); + assert_eq!(without(&parts, &[140..260]), [parts[0], part(100, 140, 40), part(140, 200, 0), parts[2]]); + assert_eq!(without(&parts, &[150..200]), parts, "nothing of it is here"); + assert_eq!(without(&[part(0, 0, 0)], &[0..10]), [part(0, 0, 0)]); + } + + /// Every byte stays in exactly one part, and none of the bad ones counts as done. + #[test] + fn no_gap_after_a_cut() { + for _ in 0..500 { + let (mut parts, mut at) = (vec![], 0); + for _ in 0..fastrand::u64(1..6) { + let len = fastrand::u64(1..50); + parts.push(part(at, at + len, fastrand::u64(0..=len))); + at += len; + } + let bad: Vec<_> = (0..fastrand::u64(0..4)).map(|_| fastrand::u64(0..at)).map(|s| s..s + fastrand::u64(1..40)).collect(); + let new = without(&parts, &bad); + assert_eq!((new[0].start, new.last().unwrap().end), (0, Some(at)), "{parts:?} {bad:?}"); + assert!(new.windows(2).all(|w| w[0].end == Some(w[1].start)), "{parts:?} {bad:?} {new:?}"); + let done = |parts: &[Part], i: u64| parts.iter().any(|p| p.start <= i && i < p.start + p.done); + for i in 0..at { + assert_eq!(done(&new, i), done(&parts, i) && !bad.iter().any(|b| b.contains(&i)), "{i}: {parts:?} {bad:?} {new:?}"); + } + } + } + + #[test] + fn spots_are_not_here_yet() { + for _ in 0..100 { + let s = spots(&[part(0, 100_000, 50_000)], 100_000); + assert!(s.contains(&(95_904..100_000)) && s.iter().all(|s| s.end <= 100_000 && s.end > 50_000)); + } + assert_eq!(spots(&[part(0, 9, 9)], 9), []); + } +} diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 15c0a3e..c125580 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -2,8 +2,10 @@ //! //! Secrets (cookies, logins, tokens) never appear here. `secret` fields hold the name of a keyring item. +use crate::verify::Pieces; use serde::{Deserialize, Serialize}; use std::path::PathBuf; +use std::sync::Arc; pub type TaskId = i64; pub type QueueId = i64; @@ -65,7 +67,8 @@ impl State { // Queued again: the app was killed, or the task gave up its place. Running => &[Queued, Waiting, Paused, Checking, Finishing, Failed], Paused => &[Queued, Waiting, Failed], - Checking => &[Queued, Paused, Finishing, Failed], + // Running: some pieces come again. Done: it was done before. + Checking => &[Queued, Running, Paused, Finishing, Done, Failed], Finishing => &[Queued, Done, Failed], // Queued: download again. Checking: check the file again. Done => &[Queued, Checking, Gone], @@ -136,6 +139,8 @@ named_enum!( /// Sound and picture that can't be made a file of. Media = "media", Crashed = "crashed", + /// The file doesn't match its checksum. + Checksum = "checksum", } ); @@ -172,6 +177,10 @@ pub struct Task { pub last_modified: Option, /// `sha256:…`. pub checksum: Option, + /// Hashes of its pieces, to repair single ones. + pub pieces: Option>, + /// What the finished file was found to match: `checksum` as it was then, or `pieces`. + pub verified: Option, pub max_parts: Option, /// Failures in a row before it fails, 0 for never. None for the setting. pub tries: Option, @@ -214,6 +223,8 @@ impl Default for Task { etag: None, last_modified: None, checksum: None, + pieces: None, + verified: None, max_parts: None, tries: None, speed_limit: None, diff --git a/crates/core/src/relink/mod.rs b/crates/core/src/relink/mod.rs index 2d178fc..9474d28 100644 --- a/crates/core/src/relink/mod.rs +++ b/crates/core/src/relink/mod.rs @@ -149,45 +149,68 @@ impl Checked { /// Compares the task's finished bytes with the new link's. Reads the file only; the task may even be running. pub async fn check(client: &Client, task: &Task, parts: &[Part], link: NewLink, source: Source, stop: &mut Stop) -> Result { + Ok(open_link(client, task, parts, link, source, stop).await?.0) +} + +/// The same, and the server to go on from. None when the verdict was clear without it. +pub(crate) async fn open_link( + client: &Client, + task: &Task, + parts: &[Part], + link: NewLink, + source: Source, + stop: &mut Stop, +) -> Result<(Checked, Option)> { let path = disk::partial_path(&task.folder, &task.name); let whole = runs(parts); let file = if whole.is_empty() { None } else { Some(open(&path).await?) }; let (mut checked, opened) = probed(client, task, link, source, total(&whole), stop).await?; - let Some((server, body)) = opened else { return Ok(checked) }; - let Some(file) = file else { - checked.reason = Reason::Nothing; - return Ok(checked); - }; + let Some((server, body)) = opened else { return Ok((checked, None)) }; + if let Some(file) = file { + judge(&mut checked, &server, body, task, &file, &whole, stop).await?; + } + Ok((checked, Some(server))) +} + +async fn judge( + checked: &mut Checked, + server: &Link, + body: Option, + task: &Task, + file: &Arc, + whole: &[Range], + stop: &mut Stop, +) -> Result<()> { let old = Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() }; // Both at the same server, as far as is known. let same_server = url::Url::parse(&task.url).is_ok_and(|u| u.origin() == server.source.url.origin()); let opinion = versions(&old, &server.version, same_server); if opinion == Opinion::Other { checked.reason = Reason::OtherVersion; - return Ok(checked); + return Ok(()); } // More is here than it has. if let (Some(size), Some(last)) = (server.version.size, whole.last()) && last.end > size { checked.reason = Reason::Size { old: last.end, new: size }; - return Ok(checked); + return Ok(()); } if !server.ranges { let head = whole.first().filter(|r| r.start == 0).map(|r| r.end.min(ALL)).unwrap_or(0); - let known = read(&file, 0..head).await?; + let known = read(file, 0..head).await?; let same = match body { - Some(body) => same_body(client, body, &known, stop).await?, + Some(body) => same_body(&server.client, body, &known, stop).await?, None => true, }; checked.compared = head; checked.reason = if same { Reason::NoRanges } else { Reason::Bytes }; - return Ok(checked); + return Ok(()); } drop(body); - for sample in samples(&whole) { - let known = read(&file, sample.clone()).await?; - checked.reason = match same_bytes(&server, &known, sample.start, stop).await { + for sample in samples(whole) { + let known = read(file, sample.clone()).await?; + checked.reason = match same_bytes(server, &known, sample.start, stop).await { Ok(true) => { checked.compared += known.len() as u64; continue; @@ -201,14 +224,14 @@ pub async fn check(client: &Client, task: &Task, parts: &[Part], link: NewLink, } Err(e) => return Err(e), }; - return Ok(checked); + return Ok(()); } checked.reason = match opinion { Opinion::Same => Reason::Version, _ if checked.compared < SAMPLE => Reason::TooLittle, _ => Reason::Samples, }; - Ok(checked) + Ok(()) } /// What the link leads to. Nothing to compare comes along when the verdict is clear already. diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs index cd109e3..2320848 100644 --- a/crates/core/src/snapshot.rs +++ b/crates/core/src/snapshot.rs @@ -1,8 +1,9 @@ //! The download list as everyone but the manager sees it. Never changes; a newer one shares all that stayed the same. use crate::http::PartView; -use crate::model::{State, Task, TaskId, Time}; +use crate::model::{ErrorKind, State, Task, TaskId, Time}; use crate::speed::History; +use crate::verify::{self, Offer}; use std::collections::VecDeque; use std::sync::Arc; use std::time::Duration; @@ -48,6 +49,27 @@ impl TaskView { self.task.state } + /// How the file stands to its checksum. + pub fn verify(&self) -> verify::State { + let t = &self.task; + match t.state { + State::Checking => verify::State::Checking, + _ if t.error.as_ref().is_some_and(|e| e.kind == Some(ErrorKind::Checksum)) => verify::State::Bad, + _ if t.verified.is_some() && (t.checksum.is_none() || t.verified == t.checksum) => verify::State::Good, + _ if t.checksum.is_some() || t.pieces.is_some() => verify::State::Open, + _ => verify::State::Nothing, + } + } + + /// What can be done about a file that doesn't match, the cheapest first. + pub fn offers(&self) -> Vec { + if self.verify() != verify::State::Bad { + return vec![]; + } + let all = [(Offer::Repair, self.task.pieces.is_some()), (Offer::OtherMirror, !self.task.mirrors.is_empty()), (Offer::Restart, true)]; + all.into_iter().filter_map(|(o, can)| can.then_some(o)).collect() + } + /// Share of the file that is here, 0 to 1. None when the size is unknown. pub fn progress(&self) -> Option { match (self.task.state, self.size?) { diff --git a/crates/core/src/store/004.sql b/crates/core/src/store/004.sql new file mode 100644 index 0000000..e960a35 --- /dev/null +++ b/crates/core/src/store/004.sql @@ -0,0 +1,2 @@ +ALTER TABLE tasks ADD COLUMN pieces TEXT; +ALTER TABLE tasks ADD COLUMN verified TEXT; diff --git a/crates/core/src/store/mod.rs b/crates/core/src/store/mod.rs index 4d6b8e2..6fec2e8 100644 --- a/crates/core/src/store/mod.rs +++ b/crates/core/src/store/mod.rs @@ -16,7 +16,7 @@ use std::thread::JoinHandle; use std::time::Duration; /// Never edit one that shipped; add the next number. -const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql")]; +const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql")]; #[derive(Debug)] pub enum Error { diff --git a/crates/core/src/store/rows.rs b/crates/core/src/store/rows.rs index 6fa69c1..8bf8a09 100644 --- a/crates/core/src/store/rows.rs +++ b/crates/core/src/store/rows.rs @@ -7,6 +7,7 @@ use std::collections::HashSet; use std::ffi::OsString; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::path::{Path, PathBuf}; +use std::sync::Arc; /// File names needn't be UTF-8. fn path_bytes(path: &Path) -> &[u8] { @@ -29,6 +30,7 @@ fn from_json(text: String) -> Result { fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result { let folder = path_bytes(&t.folder); let (mirrors, headers) = (json(&t.mirrors), json(&t.headers)); + let pieces = t.pieces.as_ref().map(|p| p.to_string()); let columns: &[(&str, &dyn ToSql)] = named_params! { ":url": t.url, ":mirrors": mirrors, ":source_page": t.source_page, ":name": t.name, ":folder": folder, ":queue": t.queue, ":position": t.position, ":priority": t.priority.name(), ":size": t.size, @@ -36,7 +38,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result { ":checksum": t.checksum, ":max_parts": t.max_parts, ":speed_limit": t.speed_limit, ":headers": headers, ":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at, ":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes, ":tries": t.tries, - ":replaces": t.replaces, + ":replaces": t.replaces, ":pieces": pieces, ":verified": t.verified, }; Ok(c.execute(sql, columns)?) } @@ -46,10 +48,10 @@ pub fn insert_task(c: &Connection, t: &Task) -> Result { c, "INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime, etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at, - finished_at, removed_at, notes, tries, replaces) + finished_at, removed_at, notes, tries, replaces, pieces, verified) VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime, :etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at, - :finished_at, :removed_at, :notes, :tries, :replaces)", + :finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified)", t, )?; let id = c.last_insert_rowid(); @@ -68,7 +70,7 @@ pub fn update_task(c: &Connection, t: &Task) -> Result { etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts, speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after, start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes, - tries = :tries, replaces = :replaces + tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified WHERE id = {}", t.id ); @@ -120,6 +122,9 @@ fn task(r: &Row) -> Result { etag: r.get("etag")?, last_modified: r.get("last_modified")?, checksum: r.get("checksum")?, + // One that can't be read is one that can't repair anything. + pieces: r.get::<_, Option>("pieces")?.and_then(|p| p.parse().ok()).map(Arc::new), + verified: r.get("verified")?, max_parts: r.get("max_parts")?, tries: r.get("tries")?, speed_limit: r.get("speed_limit")?, diff --git a/crates/core/src/verify.rs b/crates/core/src/verify.rs new file mode 100644 index 0000000..ffd95fa --- /dev/null +++ b/crates/core/src/verify.rs @@ -0,0 +1,553 @@ +//! Checksums: what is known of them, and comparing files with them. + +use crate::disk::blocking; +use crate::http::{self, Client, Error, Source, Stop}; +use crate::tr; +use base64::Engine; +use base64::prelude::BASE64_STANDARD; +use blake3::Hasher as Blake3; +use md5::Md5; +use sha1::Sha1; +use sha2::{Digest, Sha256, Sha512}; +use std::fmt; +use std::fs::File; +use std::io; +use std::ops::Range; +use std::os::unix::fs::FileExt; +use std::path::PathBuf; +use std::str::FromStr; +use std::sync::Arc; + +/// More pieces than this are not kept. +pub const MAX_PIECES: usize = 1 << 16; +/// Read at once. +const CHUNK: usize = 1 << 20; +/// A list of checksums is never larger. +const MAX_LIST: u64 = 1 << 20; + +/// Weakest first. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Algo { + Md5, + Sha1, + Sha256, + Blake3, + Sha512, +} + +impl Algo { + pub const ALL: [Algo; 5] = [Algo::Md5, Algo::Sha1, Algo::Sha256, Algo::Blake3, Algo::Sha512]; + + pub fn name(self) -> &'static str { + match self { + Algo::Md5 => "md5", + Algo::Sha1 => "sha1", + Algo::Sha256 => "sha256", + Algo::Blake3 => "blake3", + Algo::Sha512 => "sha512", + } + } + + /// As it is shown. + pub fn label(self) -> &'static str { + match self { + Algo::Md5 => "MD5", + Algo::Sha1 => "SHA-1", + Algo::Sha256 => "SHA-256", + Algo::Blake3 => "BLAKE3", + Algo::Sha512 => "SHA-512", + } + } + + /// `sha-256`, `SHA256`, `b3` … + pub fn from_name(name: &str) -> Option { + let plain: String = name.chars().filter(|c| !matches!(c, '-' | '_')).collect::().to_ascii_lowercase(); + match plain.as_str() { + "sha" => Some(Algo::Sha1), + "b3" | "b3sum" => Some(Algo::Blake3), + _ => Algo::ALL.into_iter().find(|a| a.name() == plain), + } + } + + /// Bytes of a hash. + #[allow(clippy::len_without_is_empty)] + pub fn len(self) -> usize { + match self { + Algo::Md5 => 16, + Algo::Sha1 => 20, + Algo::Sha256 | Algo::Blake3 => 32, + Algo::Sha512 => 64, + } + } + + /// SHA-256, where it could be BLAKE3 too. + fn of_len(len: usize) -> Option { + Algo::ALL.into_iter().find(|a| a.len() == len) + } + + /// The usual ending of a file that holds one. + fn ending(self) -> &'static str { + if self == Algo::Blake3 { "b3" } else { self.name() } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Checksum { + pub algo: Algo, + pub hash: Vec, +} + +impl Checksum { + pub fn new(algo: Algo, hash: Vec) -> Option { + (hash.len() == algo.len()).then_some(Checksum { algo, hash }) + } + + fn from_hex(algo: Option, text: &str) -> Option { + let hash = unhex(text)?; + Checksum::new(algo.or(Algo::of_len(hash.len()))?, hash) + } + + pub(crate) fn from_base64(algo: Algo, text: &str) -> Option { + Checksum::new(algo, BASE64_STANDARD.decode(text.trim()).ok()?) + } +} + +/// `sha256:…` +impl fmt::Display for Checksum { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}:{}", self.algo.name(), hex(&self.hash)) + } +} + +/// What someone pastes: the hash alone (its length tells the kind), with the kind before it (`sha256:…`, `SHA-256 = …`, +/// `sha256-` and base64), or a line of a list. Of several lines the first that has one. +impl FromStr for Checksum { + type Err = (); + + fn from_str(text: &str) -> Result { + text.lines().find_map(|l| line(l, None)).map(|l| l.0).ok_or(()) + } +} + +/// The checksum of `name` in a list. One that names no file counts if it is the only one. +pub fn find(list: &str, name: &str, kind: Option) -> Option { + let lines: Vec<_> = list.lines().take(10_000).filter_map(|l| line(l, kind)).collect(); + let of = |n: &str| n.rsplit(['/', '\\']).next() == Some(name); + // The strongest, if there are several. + let named = lines.iter().filter(|(_, n)| n.as_deref().is_some_and(of)).map(|(c, _)| c).max_by_key(|c| c.algo); + match lines.as_slice() { + [(only, None)] => Some(only.clone()), + _ => named.cloned(), + } +} + +/// A hash, and the file it is said to be of. +fn line(line: &str, kind: Option) -> Option<(Checksum, Option)> { + let line = line.trim().trim_start_matches('\u{feff}'); + if line.is_empty() || line.len() > 8192 || line.starts_with(['#', ';']) { + return None; + } + // `SHA256 (file) = hash` + if let Some((left, hash)) = line.rsplit_once(" = ") + && let Some((algo, name)) = left.split_once(" (") + && let Some(name) = name.strip_suffix(')') + { + return Some((Checksum::from_hex(Some(Algo::from_name(algo)?), hash.trim())?, Some(name.into()))); + } + // `hash file` and `hash *file` + let (first, rest) = line.split_once(char::is_whitespace).unwrap_or((line, "")); + if let Some(c) = Checksum::from_hex(kind, first) { + let name = rest.trim_start().trim_start_matches('*'); + return Some((c, Some(name.to_string()).filter(|n| !n.is_empty()))); + } + // `kind: hash`, `kind = hash`, `kind hash`, `kind-base64` + let at = line.find([':', '=', ' ', '\t'])?; + let (algo, hash) = (Algo::from_name(line[..at].trim()), line[at..].trim_matches(|c: char| c.is_whitespace() || matches!(c, ':' | '='))); + if let Some(algo) = algo { + return Some((Checksum::from_hex(Some(algo), hash)?, None)); + } + let (algo, hash) = line.split_once('-')?; + Some((Checksum::from_base64(Algo::from_name(algo)?, hash)?, None)) +} + +/// As it is stored: `sha256:…`. What can't be understood stays as it is, and is never compared. +pub(crate) fn plain(text: String) -> String { + text.parse::().map_or(text, |c| c.to_string()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(text: &str) -> Option> { + let digits = text.as_bytes(); + if digits.is_empty() || digits.len() % 2 == 1 || !digits.iter().all(u8::is_ascii_hexdigit) { + return None; + } + digits.chunks(2).map(|d| u8::from_str_radix(std::str::from_utf8(d).ok()?, 16).ok()).collect() +} + +/// Hashes of the pieces of a file, each `size` long but the last. +#[derive(Clone, PartialEq, Eq)] +pub struct Pieces { + pub algo: Algo, + pub size: u64, + hashes: Vec, +} + +impl Pieces { + pub fn new(algo: Algo, size: u64, hashes: Vec) -> Option { + let fine = size > 0 && !hashes.is_empty() && hashes.len().is_multiple_of(algo.len()) && hashes.len() / algo.len() <= MAX_PIECES; + fine.then_some(Pieces { algo, size, hashes }) + } + + pub fn count(&self) -> u64 { + (self.hashes.len() / self.algo.len()) as u64 + } + + /// Whether a file of `len` bytes has so many. + pub fn fit(&self, len: u64) -> bool { + len.div_ceil(self.size) == self.count() + } + + fn hash(&self, i: u64) -> &[u8] { + let n = self.algo.len(); + &self.hashes[i as usize * n..][..n] + } +} + +impl fmt::Debug for Pieces { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Pieces({} {} of {})", self.count(), self.algo.name(), self.size) + } +} + +/// `sha256:262144:` and all hashes in base64. +impl fmt::Display for Pieces { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}:{}:{}", self.algo.name(), self.size, BASE64_STANDARD.encode(&self.hashes)) + } +} + +impl FromStr for Pieces { + type Err = (); + + fn from_str(text: &str) -> Result { + let mut parts = text.splitn(3, ':'); + let mut next = || parts.next().ok_or(()); + let (algo, size, hashes) = (next()?, next()?, next()?); + let hashes = BASE64_STANDARD.decode(hashes).map_err(drop)?; + Pieces::new(Algo::from_name(algo).ok_or(())?, size.parse().map_err(drop)?, hashes).ok_or(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Found { + /// The same; by what, as `Task::verified` has it. + Good(String), + /// Nothing to compare with. + Nothing, + /// With the ranges that are wrong, as far as that is known. + Bad(Vec>), +} + +/// What a file should be. +#[derive(Debug, Clone, Default)] +pub struct Wanted { + pub checksum: Option, + pub pieces: Option>, +} + +impl Wanted { + pub fn nothing(&self) -> bool { + self.checksum.is_none() && self.pieces.is_none() + } + + /// Reads the whole file, off the threads that download. `progress` gets the share that is done. + pub async fn compare(&self, path: PathBuf, progress: impl Fn(f32) + Send + 'static, stop: &Stop) -> http::Result { + if self.nothing() { + return Ok(Found::Nothing); + } + let (wanted, stop) = (self.clone(), stop.clone()); + let found = blocking(move || wanted.read(&path, progress, || *stop.borrow()).map_err(|e| (e, path))); + match found.await { + Ok(Some(found)) => Ok(found), + Ok(None) => Err(Error::Stopped), + Err((e, _)) if e.kind() == io::ErrorKind::NotFound => Err(Error::Missing), + Err((e, _)) => Err(crate::disk::Error::Io(e).into()), + } + } + + /// None when it was stopped. + fn read(&self, path: &PathBuf, progress: impl Fn(f32), stopped: impl Fn() -> bool) -> io::Result> { + let file = File::open(path)?; + let len = file.metadata()?.len(); + let pieces = self.pieces.as_ref().filter(|p| p.fit(len)); + if self.checksum.is_none() && pieces.is_none() { + return Ok(Some(if self.pieces.is_some() { Found::Bad(vec![]) } else { Found::Nothing })); + } + let mut whole = self.checksum.as_ref().map(|c| Hash::new(c.algo)); + let mut piece = pieces.map(|p| Hash::new(p.algo)); + let mut bad: Vec> = vec![]; + let mut buf = vec![0; CHUNK]; + let mut at = 0; + while at < len { + if stopped() { + return Ok(None); + } + // A piece ends where a read ends. + let piece_end = pieces.map_or(len, |p| ((at / p.size + 1).saturating_mul(p.size)).min(len)); + let n = (piece_end - at).min(CHUNK as u64) as usize; + file.read_exact_at(&mut buf[..n], at)?; + let end = at + n as u64; + if let Some(whole) = &mut whole { + whole.update(&buf[..n]); + } + if let (Some(p), Some(hash)) = (pieces, &mut piece) { + hash.update(&buf[..n]); + if end == piece_end { + let i = at / p.size; + if std::mem::replace(hash, Hash::new(p.algo)).end() != p.hash(i) { + let start = i * p.size; + match bad.last_mut() { + Some(last) if last.end == start => last.end = end, + _ => bad.push(start..end), + } + } + } + } + at = end; + progress(at as f32 / len as f32); + } + Ok(Some(match (&self.checksum, whole.map(Hash::end)) { + // The whole file's word counts more than that of its pieces. + (Some(c), Some(hash)) if hash == c.hash => Found::Good(c.to_string()), + (None, _) if bad.is_empty() => Found::Good("pieces".into()), + _ => Found::Bad(bad), + })) + } +} + +enum Hash { + Md5(Md5), + Sha1(Sha1), + Sha256(Sha256), + Sha512(Sha512), + Blake3(Box), +} + +impl Hash { + fn new(algo: Algo) -> Hash { + match algo { + Algo::Md5 => Hash::Md5(Md5::new()), + Algo::Sha1 => Hash::Sha1(Sha1::new()), + Algo::Sha256 => Hash::Sha256(Sha256::new()), + Algo::Sha512 => Hash::Sha512(Sha512::new()), + Algo::Blake3 => Hash::Blake3(Box::new(Blake3::new())), + } + } + + fn update(&mut self, data: &[u8]) { + match self { + Hash::Md5(h) => h.update(data), + Hash::Sha1(h) => h.update(data), + Hash::Sha256(h) => h.update(data), + Hash::Sha512(h) => h.update(data), + Hash::Blake3(h) => drop(h.update(data)), + } + } + + fn end(self) -> Vec { + match self { + Hash::Md5(h) => h.finalize().to_vec(), + Hash::Sha1(h) => h.finalize().to_vec(), + Hash::Sha256(h) => h.finalize().to_vec(), + Hash::Sha512(h) => h.finalize().to_vec(), + Hash::Blake3(h) => h.finalize().as_bytes().to_vec(), + } + } +} + +/// Looks for a checksum beside the file on its server: `name.sha256` and the like, then `SHA256SUMS` in its folder. +pub async fn sidecar(client: &Client, source: &Source, stop: &mut Stop) -> http::Result> { + let Some(name) = source.url.path_segments().and_then(|mut s| s.next_back()).filter(|n| !n.is_empty()) else { return Ok(None) }; + let plain = percent_encoding::percent_decode_str(name).decode_utf8_lossy().into_owned(); + let order = [Algo::Sha256, Algo::Sha512, Algo::Blake3, Algo::Sha1, Algo::Md5]; + let beside = order.map(|a| (format!("{name}.{}", a.ending()), a)); + let lists = [Algo::Sha256, Algo::Sha512].map(|a| (format!("{}SUMS", a.name().to_uppercase()), a)); + for (file, algo) in beside.into_iter().chain(lists) { + let mut url = source.url.clone(); + url.set_query(None); + let Ok(url) = url.join(&format!("./{file}")) else { continue }; + let list = match http::small(client, &source.at(&url), MAX_LIST, stop).await { + Ok(list) => list, + Err(Error::Status { .. } | Error::Page | Error::BadReply(_)) => continue, + Err(e) => return Err(e), + }; + if let Some(found) = find(&String::from_utf8_lossy(&list), &plain, Some(algo)) { + return Ok(Some(found)); + } + } + Ok(None) +} + +/// How a finished file stands to its checksum. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + /// There is nothing to compare it with. + Nothing, + /// Not compared yet. + Open, + /// `TaskView::checked` tells how far. + Checking, + Good, + Bad, +} + +impl State { + /// For the user. + pub fn label(self) -> String { + match self { + State::Nothing => tr!("verify.nothing"), + State::Open => tr!("verify.open"), + State::Checking => tr!("verify.checking"), + State::Good => tr!("verify.good"), + State::Bad => tr!("verify.bad"), + } + } +} + +/// What can be done about a file that doesn't match. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Offer { + /// Only the wrong pieces come again: `Command::Resume`. + Repair, + /// From the start, from the next mirror: `Command::OtherMirror`. + OtherMirror, + /// From the start: `Command::Redownload`. + Restart, +} + +impl Offer { + pub fn label(self) -> String { + match self { + Offer::Repair => tr!("verify.repair"), + Offer::OtherMirror => tr!("verify.other_mirror"), + Offer::Restart => tr!("verify.restart"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const EMPTY: [(Algo, &str); 4] = [ + (Algo::Md5, "d41d8cd98f00b204e9800998ecf8427e"), + (Algo::Sha1, "da39a3ee5e6b4b0d3255bfef95601890afd80709"), + (Algo::Sha256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), + ( + Algo::Sha512, + "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", + ), + ]; + + #[test] + fn length_tells_the_kind() { + for (algo, text) in EMPTY { + let c: Checksum = text.to_uppercase().parse().unwrap(); + assert_eq!((c.algo, c.to_string()), (algo, format!("{}:{text}", algo.name()))); + assert_eq!(c.to_string().parse(), Ok(c.clone())); + assert_eq!(Hash::new(algo).end(), c.hash); + } + let b3 = "blake3:af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"; + assert_eq!(b3.parse::().unwrap().hash, Hash::new(Algo::Blake3).end()); + assert_eq!(b3.parse::().unwrap().to_string(), b3); + } + + #[test] + fn pasted_text() { + let (_, sha) = EMPTY[2]; + let want: Checksum = sha.parse().unwrap(); + let sri = format!("sha256-{}", BASE64_STANDARD.encode(&want.hash)); + for text in [ + format!(" {sha} \n"), + format!("SHA-256: {sha}"), + format!("sha256={sha}"), + format!("SHA256 = {sha}"), + format!("sha256\t{sha}"), + format!("SHA256 (a b.iso) = {sha}"), + format!("{sha} *a b.iso"), + format!("# list\n\n{sha} a.iso\n"), + sri, + ] { + assert_eq!(text.parse(), Ok(want.clone()), "{text}"); + } + for text in ["", "hello", "sha256:", "abc", "md5:e3b0", &format!("md5: {sha}"), "sha256-####", "https://a/b", "é: ü"] { + assert_eq!(text.parse::(), Err(()), "{text}"); + } + } + + #[test] + fn lists() { + let [a, b] = [1u8, 2].map(|n| hex(&[n; 32])); + let list = format!("{a} ./dir/a.iso\n{b} *b.iso\nMD5 (a.iso) = {}\n", hex(&[3; 16])); + assert_eq!(find(&list, "a.iso", None).unwrap().hash, [1; 32]); + assert_eq!(find(&list, "b.iso", Some(Algo::Blake3)).unwrap().algo, Algo::Blake3); + assert_eq!(find(&list, "c.iso", None), None); + assert_eq!(find(&a, "c.iso", None).unwrap().hash, [1; 32], "alone, it is for any file"); + assert_eq!(find(&format!("{a} x.iso"), "c.iso", None), None); + assert_eq!(find(&format!("{a}\n{b}"), "c.iso", None), None); + } + + #[test] + fn pieces_and_whole() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("f"); + let data: Vec = (0..2_500_000u32).map(|i| (i % 251) as u8).collect(); + let sum = |algo, data: &[u8]| { + let mut h = Hash::new(algo); + h.update(data); + h.end() + }; + let pieces = |size: usize| { + let hashes = data.chunks(size).flat_map(|c| sum(Algo::Sha1, c)).collect(); + Some(Arc::new(Pieces::new(Algo::Sha1, size as u64, hashes).unwrap())) + }; + let checksum = Checksum::new(Algo::Blake3, sum(Algo::Blake3, &data)); + let read = |checksum: &Option, pieces| { + let w = Wanted { checksum: checksum.clone(), pieces }; + w.read(&path, |_| {}, || false).unwrap().unwrap() + }; + std::fs::write(&path, &data).unwrap(); + for size in [1000, 300_000, 1 << 20, 2_500_000, 9_000_000] { + assert_eq!(read(&None, pieces(size)), Found::Good("pieces".into())); + assert!(matches!(read(&checksum, pieces(size)), Found::Good(_))); + assert_eq!(pieces(size).unwrap().to_string().parse(), Ok((*pieces(size).unwrap()).clone())); + } + assert_eq!(read(&None, None), Found::Nothing); + let mut wrong = data.clone(); + for at in [0, 299_999, 300_000, 2_499_999] { + wrong[at] ^= 1; + } + std::fs::write(&path, &wrong).unwrap(); + assert_eq!(read(&checksum, pieces(300_000)), Found::Bad(vec![0..600_000, 2_400_000..2_500_000])); + assert_eq!(read(&None, pieces(1000)), Found::Bad(vec![0..1000, 299_000..301_000, 2_499_000..2_500_000])); + assert_eq!(read(&checksum, None), Found::Bad(vec![])); + // Pieces of another file. + std::fs::write(&path, &data[..9]).unwrap(); + assert_eq!(read(&None, pieces(1000)), Found::Bad(vec![])); + let stopped = Wanted { checksum, pieces: None }.read(&path, |_| {}, || true).unwrap(); + assert_eq!(stopped, None); + } + + #[test] + fn pieces_from_the_store() { + for bad in ["", "sha1", "sha1:5", "sha1:0:AAAA", "sha1:5:AAAA", "nope:5:AAAA", "sha1:x:"] { + assert!(bad.parse::().is_err(), "{bad}"); + } + assert!(Pieces::new(Algo::Md5, 1, vec![0; 16 * (MAX_PIECES + 1)]).is_none()); + let p = Pieces::new(Algo::Md5, 10, vec![0; 48]).unwrap(); + assert!(p.fit(21) && p.fit(30) && !p.fit(20) && !p.fit(31)); + } +} diff --git a/crates/core/tests/mirror.rs b/crates/core/tests/mirror.rs new file mode 100644 index 0000000..d4b69f1 --- /dev/null +++ b/crates/core/tests/mirror.rs @@ -0,0 +1,498 @@ +//! Several sources for one file, metalinks, and comparing with checksums. + +use medlar_core::adapt::Timing; +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::*; +use medlar_core::manager::{Bin, Command, Config, Manager}; +use medlar_core::metalink; +use medlar_core::model::{ErrorKind, State, Task, TaskId}; +use medlar_core::relink::NewLink; +use medlar_core::segment::Rules; +use medlar_core::settings::Limits; +use medlar_core::snapshot::TaskView; +use medlar_core::store::Store; +use medlar_core::verify::{self, Algo, Checksum, Offer, Pieces}; +use medlar_testserver::{Faults, META_LEN, META_SEED, TestServer, expected}; +use sha2::{Digest, Sha256}; +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::sync::watch; +use tokio::time::sleep; + +const LEN: usize = 4 << 20; +const PIECE: usize = 256 * 1024; + +/// Speeds are measured: one test at a time. +static ALONE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +fn options() -> Options { + Options { + rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) }, + timing: Timing { settle: ms(200), window: ms(400), hold: ms(2000), refused: ms(60_000) }, + tick: ms(25), + stall: ms(1000), + patience: ms(300), + tries: 2, + backoff: ms(20), + max_wait: ms(2000), + checkpoint: ms(20), + } +} + +/// Without tags and dates, so that only the bytes tell. +fn path(seed: u64) -> String { + format!("/data/{seed}/{LEN}/a.bin?etag=0&lm=0") +} + +fn sha256(seed: u64) -> String { + format!("sha256:{}", Sha256::digest(expected(seed, 0, LEN)).iter().map(|b| format!("{b:02x}")).collect::()) +} + +fn pieces(seed: u64) -> Option> { + let hashes = expected(seed, 0, LEN).chunks(PIECE).flat_map(|c| Sha256::digest(c).to_vec()).collect(); + Pieces::new(Algo::Sha256, PIECE as u64, hashes).map(Arc::new) +} + +fn whole(path: &Path, seed: u64) { + assert!(std::fs::read(path).unwrap() == expected(seed, 0, LEN)); +} + +/// One server for the first link, one for the mirrors. +struct Bench { + one: TestServer, + two: TestServer, + dir: tempfile::TempDir, + shared: Shared, + monitor: Arc, +} + +fn shared(dir: &Path) -> Shared { + let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap()); + let client = client(&ClientOptions { idle_timeout: ms(1500), ..ClientOptions::default() }).unwrap(); + Shared { client, store, hosts: Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() }) } +} + +impl Bench { + async fn new(cap: u32) -> Bench { + let dir = tempfile::tempdir().unwrap(); + let shared = shared(dir.path()); + Bench { one: TestServer::start().await, two: TestServer::start().await, dir, shared, monitor: Arc::new(Monitor::new(cap)) } + } + + fn add(&self, task: Task) -> TaskId { + self.shared.store.add_task(Task { folder: self.dir.path().join("files"), ..task }).unwrap() + } + + /// The right file on both. + fn both(&self) -> Task { + Task { url: self.one.url(&path(1)), mirrors: vec![self.two.url(&path(1))], ..Task::default() } + } + + async fn run(&self, id: TaskId) -> Result { + let (_keep, stop) = watch::channel(false); + let source = Source::new(&self.shared.store.task(id).unwrap().url).unwrap(); + let options = options(); + let run = download(&self.shared, id, source, &options, &self.monitor, stop); + tokio::time::timeout(Duration::from_secs(60), run).await.unwrap_or_else(|_| panic!("hangs: {:?}", self.monitor.snapshot())) + } +} + +/// Body bytes of the file that a server gave. +fn sent(server: &TestServer) -> u64 { + server.requests_for("/data/1/4194304/a.bin").iter().map(|r| r.sent).sum() +} + +fn slow(per_connection: u64) -> Faults { + Faults { throttle_conn: Some(per_connection), ..Faults::default() } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_fast_mirror_brings_more_than_a_slow_one() { + let _alone = ALONE.lock().await; + for fast_first in [false, true] { + let b = Bench::new(6).await; + let (fast, sluggish) = if fast_first { (&b.one, &b.two) } else { (&b.two, &b.one) }; + fast.set_faults("*", slow(1_000_000)); + sluggish.set_faults("*", slow(60_000)); + whole(&b.run(b.add(b.both())).await.unwrap(), 1); + println!("fast {} slow {}", sent(fast), sent(sluggish)); + assert!(sent(fast) > 3 * sent(sluggish), "fast {} slow {}", sent(fast), sent(sluggish)); + assert!(sent(sluggish) > 0); + let shot = b.monitor.snapshot(); + // The fast one alone may be done before the slow one was compared. + assert!(fast_first || shot.servers.iter().all(|s| s.state == ServerState::Ready && !s.host.is_empty()), "{:?}", shot.servers); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_mirror_with_another_file_gives_nothing() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + b.one.set_faults("*", slow(800_000)); + let page = b.two.url("/site/"); + let short = b.two.url("/data/1/4194303/a.bin"); + let mirrors = vec![b.two.url(&path(2)), short, page, b.two.url("/status/404"), "gopher://x/".into(), b.two.url(&(path(1) + "&ignore_range=1"))]; + let id = b.add(Task { mirrors, ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + let shot = b.monitor.snapshot(); + assert_eq!(shot.servers.iter().filter(|s| s.state == ServerState::Ready).count(), 1, "{:?}", shot.servers); + assert!(sent(&b.two) <= LEN as u64, "only looked at"); + let used = b.two.requests_for(&format!("/data/2/{LEN}/a.bin")); + assert!(!used.is_empty() && used.iter().map(|r| r.sent).sum::() < 200_000); +} + +/// It has the same start and end, so it passes; its bytes show when another one goes on behind them. +#[tokio::test(flavor = "multi_thread")] +async fn a_caught_liar_loses_all_it_gave() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + b.one.set_faults("*", slow(300_000)); + b.two.set_faults("*", Faults { change_after: Some(64 * 1024), cut_after: Some(200 * 1024), ..Faults::default() }); + whole(&b.run(b.add(b.both())).await.unwrap(), 1); + assert!(sent(&b.two) > 100_000, "it was used: {}", sent(&b.two)); + assert_eq!(b.monitor.snapshot().servers[1].state, ServerState::Out); +} + +#[tokio::test(flavor = "multi_thread")] +async fn wrong_pieces_of_a_lying_mirror_come_again() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + b.one.set_faults("*", slow(300_000)); + b.two.set_faults("*", Faults { change_after: Some(64 * 1024), ..slow(2_000_000) }); + let id = b.add(Task { checksum: Some(sha256(1)), pieces: pieces(1), ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + assert!(sent(&b.two) > 100_000, "it was used: {}", sent(&b.two)); + assert_eq!(b.shared.store.task(id).unwrap().verified, Some(sha256(1))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn bad_mirrors_are_dropped_alone() { + let _alone = ALONE.lock().await; + // Dead at once, dead later, refusing, cutting. + let faults = [ + Faults { expire_requests: Some(9), ..Faults::default() }, + Faults { expire_requests: Some(9), expire_status: Some(503), ..Faults::default() }, + Faults { cut_after: Some(8000), ..Faults::default() }, + ]; + for f in faults { + for mirror in [true, false] { + let b = Bench::new(4).await; + let (bad, good) = if mirror { (&b.two, &b.one) } else { (&b.one, &b.two) }; + good.set_faults("*", slow(500_000)); + bad.set_faults("*", Faults { throttle_conn: Some(500_000), ..f.clone() }); + let id = b.add(b.both()); + match b.run(id).await { + Ok(file) => whole(&file, 1), + // The first one died before the mirror was compared. The next run begins with the mirror. + Err(_) if !mirror => whole(&b.run(id).await.unwrap(), 1), + Err(e) => panic!("{f:?}: {e:?}"), + } + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_dead_first_link_is_replaced_also_later() { + let _alone = ALONE.lock().await; + let b = Bench::new(2).await; + b.one.set_faults("*", Faults::status(404)); + let id = b.add(b.both()); + whole(&b.run(id).await.unwrap(), 1); + // Half of it came from the first link. + b.one.set_faults("*", slow(1_000_000)); + b.two.set_faults("*", Faults::status(404)); + let id = b.add(b.both()); + let (stop, stopping) = watch::channel(false); + let source = Source::new(&b.one.url(&path(1))).unwrap(); + let options = options(); + let run = download(&b.shared, id, source, &options, &b.monitor, stopping); + let (result, ()) = tokio::join!(run, async { + sleep(ms(700)).await; + stop.send_replace(true); + }); + assert!(matches!(result, Err(Error::Stopped))); + b.one.set_faults("*", Faults::status(410)); + b.two.clear_all_faults(); + b.two.clear_log(); + whole(&b.run(id).await.unwrap(), 1); + assert!(sent(&b.two) < LEN as u64, "it went on: {}", sent(&b.two)); + // Another file is never continued from; the error is the first link's. + let id = b.add(Task { mirrors: vec![b.two.url(&path(2))], ..b.both() }); + b.shared.store.edit_task(id, |t| t.size = Some(LEN as u64)).unwrap(); + b.one.clear_all_faults(); + b.one.set_faults("*", Faults { expire_requests: Some(2), ..slow(200_000) }); + assert!(b.run(id).await.is_err()); + assert!(matches!(b.run(id).await, Err(Error::Status { code: 403, .. }))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_corrupt_piece_is_repaired() { + let _alone = ALONE.lock().await; + let b = Bench::new(1).await; + // The only source: wrong until it isn't. + b.one.set_faults("*", Faults { change_after: Some(3 << 20), ..Faults::default() }); + let task = Task { url: b.one.url(&path(1)), pieces: pieces(1), checksum: Some(sha256(1)), ..Task::default() }; + let id = b.add(task.clone()); + // One wrong megabyte is four pieces, asked for again in one: the first time it is whole, so the server has nothing to lie about. + whole(&b.run(id).await.unwrap(), 1); + let again = sent(&b.one) - LEN as u64; + assert!((1 << 20..(1 << 20) + 100_000).contains(&again), "{again}"); + assert_eq!(b.shared.store.task(id).unwrap().verified, Some(sha256(1))); + + // It never gets better, until a mirror takes over. + b.one.set_faults("*", Faults { change_after: Some(1000), ..Faults::default() }); + let id = b.add(task.clone()); + assert!(matches!(b.run(id).await, Err(Error::Checksum))); + b.one.clear_log(); + assert!(matches!(b.run(id).await, Err(Error::Checksum)), "still"); + assert!(b.shared.store.task(id).unwrap().verified.is_none()); + b.shared.store.edit_task(id, |t| t.mirrors = vec!["http://127.0.0.1:9/x".into()]).unwrap(); + let mirror = b.two.url(&path(1)); + b.shared.store.edit_task(id, move |t| t.mirrors.push(mirror)).unwrap(); + whole(&b.run(id).await.unwrap(), 1); + + // Without hashes of pieces there is nothing to repair. + let id = b.add(Task { pieces: None, ..task }); + assert!(matches!(b.run(id).await, Err(Error::Checksum))); + let task = b.shared.store.task(id).unwrap(); + assert!(task.folder.join(format!("{}.medlar", task.name)).exists(), "kept, and not under its name"); + assert!(!task.folder.join(&task.name).exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn pieces_of_another_size_refuse_the_file() { + let _alone = ALONE.lock().await; + let b = Bench::new(1).await; + let id = b.add(Task { url: b.one.url("/data/1/1m/a.bin"), pieces: pieces(1), ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + assert_eq!(b.shared.store.task(id).unwrap().verified.as_deref(), Some("pieces")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn every_kind_of_checksum() { + let _alone = ALONE.lock().await; + let b = Bench::new(4).await; + for algo in Algo::ALL { + let checksum = match algo { + Algo::Blake3 => Checksum::new(algo, blake3::hash(&expected(1, 0, LEN)).as_bytes().to_vec()), + _ => { + let source = Source::new(&b.one.url(&format!("/sum/{}/1/{LEN}", algo.name()))).unwrap(); + let body = reqwest_text(&b, source).await; + verify::find(&body, "data-1.bin", None) + } + }; + let checksum = checksum.unwrap(); + assert_eq!(checksum.algo, algo); + let id = b.add(Task { checksum: Some(checksum.to_string()), ..b.both() }); + whole(&b.run(id).await.unwrap(), 1); + assert_eq!(b.shared.store.task(id).unwrap().verified, Some(checksum.to_string())); + let id = b.add(Task { url: b.one.url(&path(2)), mirrors: vec![], checksum: Some(checksum.to_string()), ..Task::default() }); + assert!(matches!(b.run(id).await, Err(Error::Checksum)), "{algo:?}"); + } +} + +async fn reqwest_text(b: &Bench, source: Source) -> String { + let id = b.add(Task { url: source.url.to_string(), name: "sum".into(), ..Task::default() }); + std::fs::read_to_string(b.run(id).await.unwrap()).unwrap() +} + +// The manager. + +struct Managed { + server: TestServer, + dir: tempfile::TempDir, + manager: Manager, +} + +impl Managed { + async fn new() -> Managed { + let dir = tempfile::tempdir().unwrap(); + let limits = Limits { speed: 0, max_active: 8, max_connections: 32, parts_per_download: 4, connections_per_host: 16 }; + let mut config = Config::new(shared(dir.path()), limits); + config.options = options(); + (config.bin, config.tick) = (Bin::at(dir.path().join("Trash")), ms(2)); + Managed { server: TestServer::start().await, manager: Manager::open(config).unwrap(), dir } + } + + async fn add(&self, task: Task) -> TaskId { + self.run(Command::Add(Box::new(Task { folder: self.dir.path().join("files"), ..task }))).await + } + + async fn run(&self, command: Command) -> TaskId { + self.manager.send(command).await.unwrap() + } + + async fn until(&self, id: TaskId, what: &str, is: impl Fn(&TaskView) -> bool) -> Arc { + let end = Instant::now() + Duration::from_secs(40); + loop { + let view = self.manager.snapshot().get(id).unwrap().clone(); + if is(&view) { + return view; + } + assert!(Instant::now() < end, "never {what}: {:?} {:?} {:#?}", view.state(), view.task.error, view.log); + sleep(ms(1)).await; + } + } + + async fn done(&self, id: TaskId) -> Arc { + self.until(id, "done", |v| v.state() == State::Done).await + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn states_of_the_check() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + let good = m.add(Task { url: m.server.url(&path(1)), checksum: Some(sha256(1)["sha256:".len()..].to_uppercase()), ..Task::default() }).await; + let view = m.done(good).await; + assert_eq!((view.verify(), view.task.checksum.as_deref()), (verify::State::Good, Some(&*sha256(1)))); + assert!(view.offers().is_empty()); + let none = m.add(Task { url: m.server.url(&path(1)), ..Task::default() }).await; + assert_eq!(m.done(none).await.verify(), verify::State::Nothing); + + // One that doesn't match, and its ways out. + let bad = m.add(Task { url: m.server.url(&path(2)), mirrors: vec![m.server.url(&path(1))], checksum: Some(sha256(1)), ..Task::default() }).await; + let view = m.until(bad, "failed", |v| v.state() == State::Failed).await; + assert_eq!(view.task.error.as_ref().unwrap().kind, Some(ErrorKind::Checksum)); + assert_eq!((view.verify(), view.offers()), (verify::State::Bad, vec![Offer::OtherMirror, Offer::Restart])); + m.run(Command::OtherMirror(bad)).await; + let view = m.done(bad).await; + whole(&view.task.folder.join(&view.task.name), 1); + assert_eq!((view.verify(), view.task.mirrors.clone()), (verify::State::Good, vec![m.server.url(&path(2))])); + + // A pasted one counts when the file was compared with it. + m.run(Command::Edit { id: none, edit: Box::new(|t| t.checksum = Some(format!("SHA-256: {}", &sha256(1)[7..]))) }).await; + let view = m.until(none, "open", |v| v.verify() == verify::State::Open).await; + let (finished, counted) = (view.task.finished_at, view.counters.finished); + m.run(Command::Verify(none)).await; + let view = m.until(none, "good", |v| v.verify() == verify::State::Good).await; + assert_eq!((view.state(), view.task.finished_at, view.counters.finished), (State::Done, finished, counted)); + + // It rots on the disk. + let file = view.task.folder.join(&view.task.name); + let mut data = std::fs::read(&file).unwrap(); + data[3_000_000] ^= 1; + std::fs::write(&file, &data).unwrap(); + m.run(Command::Verify(none)).await; + let view = m.until(none, "bad", |v| v.verify() == verify::State::Bad).await; + assert_eq!((view.state(), view.offers()), (State::Failed, vec![Offer::Restart])); + assert!(file.exists()); + + // With pieces it is repaired at once. + let id = m.add(Task { url: m.server.url(&path(1)), pieces: pieces(1), ..Task::default() }).await; + let view = m.done(id).await; + let file = view.task.folder.join(&view.task.name); + let mut data = std::fs::read(&file).unwrap(); + data[3_000_000] ^= 1; + std::fs::write(&file, &data).unwrap(); + m.server.clear_log(); + m.run(Command::Verify(id)).await; + m.until(id, "good", |v| v.state() == State::Done && v.verify() == verify::State::Good).await; + whole(&file, 1); + assert!(sent(&m.server) < 2 * PIECE as u64, "{}", sent(&m.server)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn checking_can_be_seen_and_paused() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + // Long enough to be seen: MD5 in a debug build, 300 MB. + let len = 300u64 << 20; + let task = Task { url: m.server.url(&format!("/data/1/{len}/big.bin")), checksum: Some("00".repeat(16)), ..Task::default() }; + let id = m.add(task).await; + let end = Instant::now() + Duration::from_secs(40); + let mut seen = vec![]; + while seen.len() < 2 { + let view = m.manager.snapshot().get(id).unwrap().clone(); + if view.verify() == verify::State::Checking && view.checked > 0.0 && seen.last() != Some(&view.checked) { + seen.push(view.checked); + } + assert!(Instant::now() < end && view.state() != State::Failed, "{:?} {seen:?}", view.state()); + sleep(ms(1)).await; + } + assert!(seen.is_sorted() && seen[1] <= 1.0); + m.run(Command::Pause(id)).await; + let view = m.until(id, "paused", |v| v.state() == State::Paused && v.connections == 0).await; + assert_eq!(view.checked, 0.0); + sleep(ms(100)).await; + assert_eq!(m.until(id, "still paused", |_| true).await.state(), State::Paused); + m.server.clear_log(); + m.run(Command::Resume(id)).await; + let view = m.until(id, "failed", |v| v.state() == State::Failed).await; + assert_eq!(view.verify(), verify::State::Bad); + assert!(m.server.log().is_empty(), "it was whole"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn metalinks_and_headers() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + for (file, algo) in [("/meta/v4.meta4", "sha256"), ("/meta/v3.metalink", "sha1")] { + assert!(metalink::is(file, None)); + let link = NewLink { url: m.server.url(file), ..NewLink::default() }; + let files = m.manager.read_metalink(link).await.unwrap(); + let task = files[0].task(); + assert_eq!((task.name.as_str(), task.mirrors.len()), ("meta.bin", 1)); + let id = m.add(task).await; + let view = m.done(id).await; + assert_eq!(view.verify(), verify::State::Good); + assert!(view.task.checksum.as_ref().unwrap().starts_with(algo)); + assert!(std::fs::read(view.task.folder.join(&view.task.name)).unwrap() == expected(META_SEED, 0, META_LEN as usize)); + } + let id = m.add(Task { url: m.server.url("/meta/header.bin"), ..Task::default() }).await; + let view = m.done(id).await; + assert_eq!((view.verify(), view.task.mirrors.len()), (verify::State::Good, 1)); + // Not one. + let link = NewLink { url: m.server.url("/data/1/1000"), ..NewLink::default() }; + assert!(m.manager.read_metalink(link).await.is_err()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn sidecars() { + let _alone = ALONE.lock().await; + let m = Managed::new().await; + let id = m.add(Task { url: m.server.url("/meta/header.bin"), ..Task::default() }).await; + m.done(id).await; + assert_eq!(m.manager.find_checksum(id).await.unwrap(), None); + // Beside the file, and in a list. + let files = vec![ + ("/d/a%20b.iso.sha512", format!("{} a b.iso\n", "ab".repeat(64))), + ("/d/SHA256SUMS", format!("{} other.iso\n{} *listed.iso\n", "11".repeat(32), "22".repeat(32))), + ]; + let base = serve(files); + for (name, want) in [("a%20b.iso?x=1", Some(Checksum::new(Algo::Sha512, vec![0xab; 64]).unwrap())), ("listed.iso", "22".repeat(32).parse().ok()), ("c", None)] { + let id = m.add(Task { url: format!("{base}/d/{name}"), state: State::Paused, ..Task::default() }).await; + assert_eq!(m.manager.find_checksum(id).await.unwrap(), want, "{name}"); + } +} + +/// Answers 404 to all else. +fn serve(files: Vec<(&'static str, String)>) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + for mut stream in listener.incoming().flatten() { + let mut line = String::new(); + let mut lines = BufReader::new(stream.try_clone().unwrap()); + lines.read_line(&mut line).unwrap(); + let path = line.split(' ').nth(1).unwrap_or("").to_string(); + while line.trim() != "" { + line.clear(); + lines.read_line(&mut line).unwrap(); + } + let (status, body) = match files.iter().find(|f| f.0 == path) { + Some((_, body)) => ("200 OK", body.as_str()), + None => ("404 Not Found", ""), + }; + let _ = write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + } + }); + base +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 8f03492..29935ad 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -52,3 +52,6 @@ - D-050 — 2026-11-25 — One listing type for all (`listing::Entry`), with the link made of the raw bytes of the name; entries whose names could leave their folder are dropped. SFTP is russh with ring (no aws-lc-rs) and russh-sftp: a connection per part, 2 to 64 reads of 32 KiB under way, more only when they come too late. - D-051 — 2026-11-25 — Keys of SSH servers are in Medlar's own file (`Paths::known_hosts`), never in `~/.ssh`. An unknown or changed key stops the download before any login is sent; a key of another kind than the known one counts as changed. Only `host_keys.accept` adds one, and it replaces the server's old ones. With a key file, the login's password is its passphrase and is not sent to the server if it unlocked the key. - D-052 — 2026-11-25 — From here on the plans run on the branch `claude/orchestrate-0ad55c` (a new worktree); the rest of D-014 holds: sessions push only the branch, the orchestrator fast-forwards `main` after each validated category. — New orchestrator session. — all +- D-053 — 2026-11-25 — A mirror is used only after S008's comparison with what is here (verdict same or probably same, at least 16 KiB here) and, where no version proves it, after two more places that the base and the mirror must both have. Whoever is caught with other bytes is dropped and all it gave comes again; between the base and a mirror the mirror is the liar. If the first link fails, the next one that passes becomes the base. Each connection goes to the server that brings the most per connection, an untried one first; a connection four times slower than another server's moves there. — A wrong byte costs more than a slow start — 02, 06 +- D-054 — 2026-11-25 — Files are compared under their unfinished name, before they get their own, in the state `checking` (no place in the queue); `Checking` may go back to `Running` (pieces) and, for a file that was done before, to `Done`, which is no new finish. `Task::verified` holds what the file matched, so a new checksum counts as open by itself. The whole file's hash counts more than its pieces'. — A bad file never appears finished — 03, 05 +- D-055 — 2026-11-25 — Headers give mirrors only with a `Digest` or `Repr-Digest` (RFC 6249); they and a linked metalink fill only what the task doesn't have. Sidecars are looked for only when asked. Metalinks are read by quick-xml within limits; a document type or an unknown entity refuses the file. — No extra requests, nothing to expand — 02, 06 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b95e9ab..c198adc 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -159,5 +159,16 @@ Verified: `nice cargo test -j 2 -p medlar --test settings` green (26), all medla Not done: notifications and power have no settings yet, so these pages are hidden until later plans add rows; no folder chooser (a plain field); the SFTP key of a site (S011) has no field; a site's old login is deleted from the keyring only when the settings screen closes; the toast's Undo puts all settings back, not only that change. Real keyring, real desktop scheme change and a real GPU not tried. Seen: boxes 2 to 7 were ticked together after the tests, against rule 3. +## S009 — Mirrors, Metalink and checksums (2026-11-25) +Done: `core::{verify, metalink, mirror}`; several servers per download in `http/{download,parts,monitor}`, `Checking` in the manager, migration 004 (`Task::pieces`, `verified`). Choices: D-053 to D-055. Outside the plan's files: those, `probe`, `fetch` (`small`, `bytes_at`), `relink::open_link`, `snapshot`, `error`, strings; crates `blake3`, `quick-xml` 0.41 and `sha1` (the last two were in the tree). +- Verify states for the UI: `view.verify()` → `verify::State::{Nothing, Open, Checking, Good, Bad}`, each with `label()`; while `Checking` (also the task's state) `view.checked` is the share. `Bad` comes with `ErrorKind::Checksum`; `view.offers()` → `Offer::{Repair, OtherMirror, Restart}` with `label()`: `Command::{Resume, OtherMirror, Redownload}`. A finished file: `Command::Verify(id)` (after a pasted checksum: `Command::Edit`, then this). +- Checksum field: any pasted text, `text.parse::()` tells the kind (64 digits are SHA-256; BLAKE3 needs `blake3:`). `manager.find_checksum(id)` looks for sidecars, only when asked. Task's `checksum` is `sha256:…`. +- Metalink: `metalink::is(name, mime)`, `manager.read_metalink(link)` or `metalink::parse(&bytes)`, then `file.task()` (set the folder). Nothing in the app calls it yet (S016, S030). +- `http::Snapshot.servers` has each link's host, state, connections, speed (for the details panel). +- Wrong pieces come again by themselves, up to three times, without the mirror that gave them. +Not done: the Fix for `Checksum` in the list is the general `Choose` menu, not `offers()`; which mirror gave what is not kept over a restart; a mirror whose host has a speed limit is not used beside another host (the limit is of one host per download); no mirrors for files under 16 KiB, of unknown size or without ranges; a first link that dies before a mirror was compared fails the run, and the next one starts with the mirror. S019 applies host limits already (checked, not redone). +Verified: `nice cargo test -j 2 -p medlar-core --test mirror` green (13, three times; 36 to 49 s), all of core and clippy green with the S012 and S016 work of that moment. Covered: fast and slow mirror, other file, short file, page, caught liar, corrupt pieces, dead first and later links, all five kinds, paste, sidecars, headers, both metalinks, hostile XML, rot on disk, pause while checking. +Seen: boxes 2 to 5 were ticked together after the tests. A copy of the tree built into the shared target makes cargo take its artifacts for fresh ones of the real tree: never do that. + ## Later - diff --git a/docs/RECOVERY.md b/docs/RECOVERY.md index cfaa154..2385b6f 100644 --- a/docs/RECOVERY.md +++ b/docs/RECOVERY.md @@ -36,6 +36,7 @@ Title and text: `error.` and `error..why` in the catalogue; button: | `rejected` | Request rejected | blocked | no | Edit link (`edit_link`) | | `bad_link` | Link can't be used | blocked | no | Edit link (`edit_link`) | | `changed` | File changed on the server | blocked | no | Choose (`choose`) | +| `checksum` | File is damaged | blocked | no | Choose (`choose`) | | `no_resume` | Can't be continued | blocked | no | Choose (`choose`) | | `killed` | Interrupted | passing | no | Resume (`resume`) | | `drm` | Copy protected | blocked | no | Edit link (`edit_link`) | From 897c9efbe96019b98c82075861b72b31286f700c Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 13:57:12 -0600 Subject: [PATCH 04/70] S012: the choice of a stream is kept, plan done Co-Authored-By: Claude Opus 5.5 --- Plans/02 Engine/S012-streams.md | 14 +++++++------- Plans/INDEX.md | 2 +- crates/core/src/manager/actor.rs | 3 ++- crates/core/src/model.rs | 3 +++ crates/core/src/store/005.sql | 1 + crates/core/src/store/mod.rs | 2 +- crates/core/src/store/rows.rs | 10 ++++++---- crates/core/tests/stream.rs | 8 ++++++++ docs/DECISIONS.md | 3 +++ docs/PROGRESS.md | 10 ++++++++++ 10 files changed, 42 insertions(+), 14 deletions(-) create mode 100644 crates/core/src/store/005.sql diff --git a/Plans/02 Engine/S012-streams.md b/Plans/02 Engine/S012-streams.md index 9a97ffe..382ba70 100644 --- a/Plans/02 Engine/S012-streams.md +++ b/Plans/02 Engine/S012-streams.md @@ -11,13 +11,13 @@ FEATURES 1.10, 1.11, ffmpeg runner used by media plans. - docs/DECISIONS.md D-011 ## Steps -- [ ] ffmpeg finder and runner: argument lists only, progress parsing, cancel, log tail, missing-tool error kind -- [ ] HLS: master and media lists, variants, audio groups, AES-128 clear-key as the list itself offers; live lists record until stopped -- [ ] DASH: static and simple dynamic manifests, representation choice -- [ ] Fragments in parallel with retry, resume after restart, joined without re-encoding -- [ ] RTSP and MMS recorded through ffmpeg with stop and size or time limit -- [ ] DRM (Widevine, FairPlay, PlayReady signals) is recognised and refused with a plain message -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S012: …`, push +- [x] ffmpeg finder and runner: argument lists only, progress parsing, cancel, log tail, missing-tool error kind +- [x] HLS: master and media lists, variants, audio groups, AES-128 clear-key as the list itself offers; live lists record until stopped +- [x] DASH: static and simple dynamic manifests, representation choice +- [x] Fragments in parallel with retry, resume after restart, joined without re-encoding +- [x] RTSP and MMS recorded through ffmpeg with stop and size or time limit +- [x] DRM (Widevine, FairPlay, PlayReady signals) is recognised and refused with a plain message +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S012: …`, push ## End criteria - `nice cargo test -j 2 -p medlar-core --test stream` green on fixtures made by ffmpeg diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 35f8867..08a322c 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -20,7 +20,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [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 +- [x] [S012](02%20Engine/S012-streams.md) HLS, DASH, RTSP and MMS ## 03 Interface diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 6248354..6c0f41b 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -858,6 +858,7 @@ impl Actor { t.checksum = new.checksum.map(verify::plain); t.max_parts = new.max_parts; t.tries = new.tries; + t.stream = new.stream; t.speed_limit = new.speed_limit; t.headers = new.headers; t.proxy = new.proxy; @@ -1056,7 +1057,7 @@ impl Actor { let work = tokio::spawn(async move { let source = site::source(sites.as_ref(), &task, &stopped).await?; if stream::kind_of(&task).is_some() { - let request = stream::Request { id, source, choice: Default::default(), tools: &Tools::find(), options: &options }; + let request = stream::Request { id, source, choice: task.stream.clone().unwrap_or_default(), tools: &Tools::find(), options: &options }; return stream::download(&shared, request, &monitor, stopped).await; } download(&shared, id, source, &options, &monitor, stopped).await diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index c125580..f24e465 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -192,6 +192,8 @@ pub struct Task { /// Keyring item with the cookies and login. pub secret: Option, pub after: Option, + /// What was chosen of a stream. None is the best of it, for as long as it goes on. + pub stream: Option, /// The unfinished one this starts over. Removed when this is done. pub replaces: Option, pub start_at: Optionno\nnothing here\nsftp://me@e.org/f"; + let batch = Batch::of(text, true); + assert_eq!(batch.links, ["https://a.org/x", "HTTP://b.org/y", "ftp://c.org/z", "https://d.org/ü?q=1", "sftp://me@e.org/f"]); + assert_eq!((batch.total, batch.left_out, batch.patterns, batch.cut()), (5, 1, false, false)); + assert_eq!(Batch::of("éhttps://a/b x://y", true).links, ["https://a/b"]); + } + + #[test] + fn patterns_count_in_every_way() { + assert_eq!(all("http://h/[008-011].jpg"), ["http://h/008.jpg", "http://h/009.jpg", "http://h/010.jpg", "http://h/011.jpg"]); + assert_eq!(all("http://h/[9-11]"), ["http://h/9", "http://h/10", "http://h/11"]); + assert_eq!(all("http://h/[20-0:10]"), ["http://h/20", "http://h/10", "http://h/0"]); + assert_eq!(all("http://h/[a-c]{x,,yy}").len(), 9); + assert_eq!(all("http://h/{x,yy}/[1-2]"), ["http://h/x/1", "http://h/x/2", "http://h/yy/1", "http://h/yy/2"]); + assert_eq!(all("http://h/[2024-02-28..2024-03-01].gif"), ["http://h/2024-02-28.gif", "http://h/2024-02-29.gif", "http://h/2024-03-01.gif"]); + assert_eq!(all("http://h/[20260101..20251230]"), ["http://h/20260101", "http://h/20251231", "http://h/20251230"]); + assert_eq!(all("http://h/[01.02.2026..02.02.2026]"), ["http://h/01.02.2026", "http://h/02.02.2026"]); + } + + #[test] + fn what_is_no_pattern_stays() { + for link in ["http://[::1]:80/a", "http://h/[720p-x264]", "http://h/{a}", "http://h/[]", "http://h/[1-", "http://h/[1-2:0]", "http://h/[a-9]", "http://h/[2026-13-01..2026-13-02]"] { + let batch = Batch::of(link, true); + assert_eq!((batch.links, batch.patterns), (vec![link.to_string()], false)); + } + let literal = Batch::of("http://h/[1-3]", false); + assert_eq!((literal.links, literal.patterns), (vec!["http://h/[1-3]".to_string()], true)); + } + + #[test] + fn too_many_are_cut_and_counted() { + let batch = Batch::of("http://h/[1-999999999999]/[1-999999999999]/[1-999999999999]", true); + assert_eq!((batch.links.len(), batch.total, batch.cut()), (MOST, u64::MAX, true)); + let two = Batch::of(&format!("http://h/[1-{MOST}]\nhttp://h/x"), true); + assert_eq!((two.links.len(), two.total, two.cut()), (MOST, MOST as u64 + 1, true)); + let twice = Batch::of("http://h/{a,a,b}\nhttp://h/a", true); + assert_eq!((twice.links.len(), twice.total, twice.cut()), (2, 2, false)); + // As many links as fit, each looked at once. + let started = std::time::Instant::now(); + Batch::of(&"http://h/[1-999999999999]\n".repeat(1000), true); + assert!(started.elapsed().as_secs() < 5); + } +} diff --git a/crates/core/src/disk.rs b/crates/core/src/disk.rs index 8f7449c..3771b2e 100644 --- a/crates/core/src/disk.rs +++ b/crates/core/src/disk.rs @@ -197,6 +197,13 @@ impl PartialFile { } } +/// Bytes left for a folder that may not be there yet. None when its drive doesn't say. May wait for a slow drive. +pub fn free(folder: &Path) -> Option { + let there = folder.ancestors().find(|f| f.is_dir())?; + let stat = rustix::fs::statvfs(there).ok()?; + Some(stat.f_bavail.saturating_mul(stat.f_frsize)) +} + pub fn partial_path(folder: &Path, name: &str) -> PathBuf { folder.join(format!("{name}{ENDING}")) } diff --git a/crates/core/src/duplicate.rs b/crates/core/src/duplicate.rs new file mode 100644 index 0000000..16cd5de --- /dev/null +++ b/crates/core/src/duplicate.rs @@ -0,0 +1,95 @@ +//! What is in the list already. + +use crate::model::{Task, TaskId}; +use std::path::Path; +use url::Url; + +/// Why it is the same. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum By { + /// Another file may have this name in the same folder. + Name, + Link, + /// The file itself. + Checksum, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Duplicate { + pub id: TaskId, + pub by: By, +} + +/// What is about to be added. +#[derive(Debug, Clone, Copy, Default)] +pub struct New<'a> { + pub url: &'a str, + /// Empty when not known. + pub name: &'a str, + pub folder: Option<&'a Path>, + pub checksum: Option<&'a str>, +} + +/// All downloads, to be asked for many links. +pub struct Known<'a> { + tasks: Vec<(&'a Task, Option)>, + links: std::collections::HashMap, +} + +impl<'a> Known<'a> { + pub fn new(tasks: impl IntoIterator) -> Known<'a> { + let tasks: Vec<_> = tasks.into_iter().filter(|t| t.removed_at.is_none()).map(|t| (t, plain(&t.url))).collect(); + // The latest counts. + let links = tasks.iter().filter_map(|(t, link)| Some((link.clone()?, t.id))).collect(); + Known { tasks, links } + } + + /// What says most, then the latest. + pub fn find(&self, new: &New) -> Option { + let by_checksum = |sum: &str| self.tasks.iter().rev().find(|(t, _)| t.checksum.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(sum))); + if let Some((t, _)) = new.checksum.and_then(by_checksum) { + return Some(Duplicate { id: t.id, by: By::Checksum }); + } + if let Some(id) = plain(new.url).and_then(|link| self.links.get(&link)) { + return Some(Duplicate { id: *id, by: By::Link }); + } + let folder = new.folder.filter(|_| !new.name.is_empty())?; + let (t, _) = self.tasks.iter().rev().find(|(t, _)| t.name == new.name && t.folder == folder)?; + Some(Duplicate { id: t.id, by: By::Name }) + } +} + +/// Two ways to write a link are the same one: case of the host, usual port, what is behind `#`. A login doesn't count. +fn plain(link: &str) -> Option { + let mut url = Url::parse(link).ok()?; + url.set_fragment(None); + // Fails only without a host. + let _ = url.set_username(""); + let _ = url.set_password(None); + Some(url.into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn task(id: TaskId, url: &str, name: &str) -> Task { + Task { id, url: url.into(), name: name.into(), folder: "/d".into(), ..Task::default() } + } + + #[test] + fn links_names_and_checksums() { + let sum = format!("sha256:{}", "a".repeat(64)); + let mut tasks = vec![task(1, "https://H.org:443/a.zip#x", "a.zip"), task(2, "https://h.org/b", "b.zip"), task(3, "https://h.org/a.zip", "c.zip")]; + tasks[1].checksum = Some(sum.clone()); + tasks[2].removed_at = Some(1); + let known = Known::new(&tasks); + let find = |new: New| known.find(&new).map(|d| (d.id, d.by)); + let folder = Some(Path::new("/d")); + assert_eq!(find(New { url: "https://me:x@h.org/a.zip", ..New::default() }), Some((1, By::Link))); + assert_eq!(find(New { url: "https://h.org/a.zip", checksum: Some(&sum), ..New::default() }), Some((2, By::Checksum))); + assert_eq!(find(New { url: "https://x.org/q", name: "b.zip", folder, ..New::default() }), Some((2, By::Name))); + assert_eq!(find(New { url: "https://x.org/q", name: "b.zip", folder: Some(Path::new("/e")), ..New::default() }), None); + assert_eq!(find(New { url: "https://h.org/a.zip?v=2", name: "c.zip", folder, ..New::default() }), None); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 0cd25cd..2f9152c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -3,8 +3,10 @@ pub mod adapt; pub mod adopt; pub mod auth; +pub mod batch; pub mod cookie; pub mod disk; +pub mod duplicate; pub mod error; pub mod events; mod ftp; @@ -20,6 +22,7 @@ pub mod model; pub mod net_state; pub mod part; pub mod paths; +pub mod portal; pub mod proxy; pub mod recover; pub mod redact; diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 6c0f41b..ddedfa7 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -5,7 +5,7 @@ use super::bin::Binned; use super::pick::{Candidate, pick}; -use super::{Answer, Command, Config, Error, Files, Msg, Result, files}; +use super::{Answer, Command, Config, Error, Files, Msg, Probed, Result, files}; use crate::adopt::Found; use crate::error::{Failure, Place, Retry}; use crate::events::Event; @@ -16,6 +16,7 @@ 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::secret::{self, Secret}; use crate::settings::Limits; use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals}; use crate::speed::{History, Meter}; @@ -207,6 +208,12 @@ impl Entry { } } +/// None when the time has come. +fn wait_for(at: Time) -> Option { + let left = u64::try_from(at - now()).ok().filter(|left| *left > 0)?; + Some(Hold::Until(Instant::now().checked_add(Duration::from_millis(left))?, at)) +} + fn host_of(url: &str) -> Arc { url::Url::parse(url).map(|u| host::key(&u)).unwrap_or_default().into() } @@ -300,9 +307,11 @@ impl Actor { closing: false, }; actor.set_limits(actor.config.limits); + let mut unused = vec![]; for mut task in actor.store.tasks()? { if task.removed_at.is_some() { actor.store.delete_task(task.id)?; + unused.extend(task.secret); continue; } let awaits = task.state == State::Waiting && task.error.as_ref().is_some_and(|e| e.kind == Some(ErrorKind::Link)); @@ -327,6 +336,11 @@ impl Actor { } if awaits { entry.hold = Some(Hold::Link); + } else if entry.task.state == State::Waiting { + // It was away for too long: it starts with the next look. + entry.hold = entry.task.start_at.map(|at| wait_for(at).unwrap_or(Hold::Until(Instant::now(), at))); + } + if entry.hold.is_some() { actor.held.insert(id); } actor.entries.insert(id, entry); @@ -336,6 +350,7 @@ impl Actor { let (net, login) = (actor.to.clone(), actor.to.clone()); actor.runtime().spawn(net_state::watch(bus.clone(), move |n| drop(net.send(Msg::Network(n))))); actor.runtime().spawn(sleep::watch(bus, move |s| drop(login.send(Msg::Sleep(s))))); + unused.into_iter().for_each(|secret| actor.drop_secret(Some(secret))); actor.publish(); Ok(actor) } @@ -388,6 +403,7 @@ impl Actor { 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::Probe(task, secret, answer) => self.probe(*task, secret, answer), Msg::Limits(limits) => self.set_limits(limits), Msg::OnChange(call) => self.on_change.push(call), Msg::Ended(id, result) => self.ended(id, result), @@ -654,7 +670,13 @@ impl Actor { task.id = self.store.add_task(task.clone())?; let (id, mut entry) = (task.id, Entry::new(task)); entry.log(&tr!("log.added", url = entry.task.url)); + let start = entry.task.start_at.and_then(wait_for); self.entries.insert(id, entry); + if let Some(hold) = start.filter(|_| self.entries[&id].task.state != State::Paused) { + self.move_to(id, State::Waiting, None); + self.entry(id).hold = Some(hold); + self.held.insert(id); + } self.dirty.insert(id); self.happened.push(Event::Added(id)); self.choose = true; @@ -728,6 +750,20 @@ impl Actor { }); } + fn probe(&self, task: Task, secret: Option, answer: oneshot::Sender>) { + let (client, sites) = (self.config.shared.client.clone(), self.config.sites.clone()); + self.look(answer, host_of(&task.url), async move { + let (_keep, mut stop) = watch::channel(false); + let source = match (&sites, secret) { + (Some(sites), Some(secret)) => sites.source_with(&task, secret)?, + _ => site::source(sites.as_ref(), &task, &stop).await?, + }; + let probe = http::probe(&client, &source, &mut stop).await?; + let page = http::is_page(&task, &source, &probe); + Ok(Probed { name: probe.name, size: probe.version.size, mime: probe.mime, ranges: probe.ranges, page }) + }); + } + 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(()); @@ -848,6 +884,7 @@ impl Actor { fn change(&mut self, id: TaskId, edit: impl FnOnce(&mut Task)) -> Result<()> { let mut new = (*self.entries[&id].task).clone(); edit(&mut new); + let old = self.entries[&id].task.secret.clone(); let saved = self.store.edit_task(id, move |t| { t.url = new.url; t.mirrors = new.mirrors; @@ -874,6 +911,7 @@ impl Actor { let (size, downloaded) = (e.size, e.downloaded); e.task = Arc::new(saved); e.took(None); + let dropped = old.filter(|old| e.task.secret.as_ref() != Some(old)); if e.task.state == State::Running { (e.size, e.downloaded) = (size, downloaded); } @@ -882,6 +920,7 @@ impl Actor { run.monitor.flow().put(Group::Queue(e.task.queue)); run.monitor.flow().set(e.task.speed_limit); } + self.drop_secret(dropped); self.choose = true; Ok(()) } @@ -1374,8 +1413,11 @@ impl Actor { let (task, parts) = (self.store.task(id)?, if parts { Some(self.store.parts(id)?) } else { None }); let e = self.entry(id); let (state, error) = (e.task.state, e.task.error.clone()); + let old = e.task.secret.clone(); e.task = Arc::new(Task { state, error, ..task }); e.took(parts); + let dropped = old.filter(|old| e.task.secret.as_ref() != Some(old)); + self.drop_secret(dropped); Ok(()) } @@ -1390,11 +1432,22 @@ impl Actor { } self.removed.remove(&id); self.held.remove(&id); - self.entries.remove(&id); + let gone = self.entries.remove(&id); + self.drop_secret(gone.and_then(|e| e.task.secret.clone())); self.happened.push(Event::Forgotten(id)); } } + /// A task doesn't have this keyring item any more: it goes when no other task has it. + fn drop_secret(&self, name: Option) { + let (Some(name), Some(sites)) = (name.filter(|n| secret::is_task(n)), &self.config.sites) else { return }; + if self.entries.values().any(|e| e.task.secret.as_ref() == Some(&name)) { + return; + } + let secrets = sites.secrets.clone(); + self.runtime().spawn(async move { secrets.remove(&name).await }); + } + // Numbers. fn sample(&mut self, now: Instant) { diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index d2477a6..051de6e 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -19,6 +19,7 @@ use crate::net_state::Network; use crate::recover::Recovery; use crate::recover::sleep::Sleep; use crate::relink::{Checked, NewLink}; +use crate::secret::Secret; use crate::settings::Limits; use crate::site::Sites; use crate::metalink; @@ -174,6 +175,19 @@ impl Future for Reply { } } +/// What a link leads to. +#[derive(Debug, Clone, PartialEq)] +pub struct Probed { + /// The name it gets when none is given. + pub name: String, + pub size: Option, + pub mime: Option, + /// It can be continued and comes in parts. + pub ranges: bool, + /// A web page instead of the file. + pub page: bool, +} + pub struct Config { pub shared: Shared, /// Logins, proxies and rules per site. None: plain requests only (tests). @@ -213,6 +227,7 @@ enum Msg { FindChecksum(TaskId, oneshot::Sender>>), ReadMetalink(NewLink, oneshot::Sender>>), CheckPartial(PathBuf, NewLink, oneshot::Sender>), + Probe(Box, Option, oneshot::Sender>), Limits(Limits), OnChange(Box), /// A download ended. @@ -282,6 +297,13 @@ impl Manager { Reply(reply) } + /// What a link leads to; nothing is added. `secret` is used without being kept. Dropping the reply ends it. + pub fn probe(&self, task: Task, secret: Option) -> Reply { + let (answer, reply) = oneshot::channel(); + let _ = self.to.send(Msg::Probe(Box::new(task), secret, answer)); + Reply(reply) + } + /// Takes effect at once, also on running downloads. 0 is no limit. Connections that may stay go on as they are. pub fn set_limits(&self, limits: Limits) { let _ = self.to.send(Msg::Limits(limits)); diff --git a/crates/core/src/portal.rs b/crates/core/src/portal.rs new file mode 100644 index 0000000..652dab9 --- /dev/null +++ b/crates/core/src/portal.rs @@ -0,0 +1,33 @@ +//! The desktop's own file chooser. + +use crate::net_state::Bus; +use futures_lite::StreamExt; +use std::collections::HashMap; +use std::path::PathBuf; +use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; + +const NAME: &str = "org.freedesktop.portal.Desktop"; +const PATH: &str = "/org/freedesktop/portal/desktop"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Pick { + File, + Folder, +} + +/// Lets the user choose. `Ok(None)` when nothing was chosen, an error when the desktop has no chooser. +pub async fn choose(bus: &Bus, pick: Pick, title: &str) -> zbus::Result> { + let Some(bus) = bus.connect().await? else { return Err(zbus::Error::Unsupported) }; + let me = bus.unique_name().map(|n| n.trim_start_matches(':').replace('.', "_")).unwrap_or_default(); + let token = format!("medlar{}", std::process::id()); + // Listens first: the answer may come before the call returns. + let request = zbus::Proxy::new(&bus, NAME, format!("{PATH}/request/{me}/{token}"), "org.freedesktop.portal.Request").await?; + let mut answers = request.receive_signal("Response").await?; + let options = HashMap::from([("handle_token", Value::from(token)), ("directory", Value::from(pick == Pick::Folder))]); + let chooser = zbus::Proxy::new(&bus, NAME, PATH, "org.freedesktop.portal.FileChooser").await?; + let _: OwnedObjectPath = chooser.call("OpenFile", &("", title, options)).await?; + let Some(answer) = answers.next().await else { return Ok(None) }; + let (_, results): (u32, HashMap) = answer.body().deserialize()?; + let uris = results.get("uris").and_then(|v| Vec::::try_from(v.try_clone().ok()?).ok()).unwrap_or_default(); + Ok(uris.first().and_then(|uri| url::Url::parse(uri).ok()?.to_file_path().ok())) +} diff --git a/crates/core/src/secret.rs b/crates/core/src/secret.rs index 34db20c..d099c06 100644 --- a/crates/core/src/secret.rs +++ b/crates/core/src/secret.rs @@ -48,6 +48,19 @@ impl Kept { } } +/// Start of the names of tasks' items. One that no task has any more is deleted. +const TASK: &str = "task:"; + +/// A new name for a task's item. +pub fn task_name() -> String { + let random = std::hash::BuildHasher::hash_one(&std::hash::RandomState::new(), 0); + format!("{TASK}{:x}-{random:016x}", crate::model::now()) +} + +pub(crate) fn is_task(name: &str) -> bool { + name.starts_with(TASK) +} + /// All secrets, by the name that sites and tasks have in their `secret` field. pub struct Secrets { bus: Bus, diff --git a/crates/core/src/site.rs b/crates/core/src/site.rs index bf56b26..d256958 100644 --- a/crates/core/src/site.rs +++ b/crates/core/src/site.rs @@ -191,11 +191,16 @@ impl Sites { /// Where the task's requests start, with all that goes along. pub async fn source(self: &Arc, task: &Task) -> Result { - let source = Source::new(&task.url)?.with_headers(&task.headers); - let mut secret = match &task.secret { + let secret = match &task.secret { Some(name) => self.secrets.load(name).await.unwrap_or_default(), None => Secret::default(), }; + self.source_with(task, secret) + } + + /// With a secret that is in no keyring yet. + pub(crate) fn source_with(self: &Arc, task: &Task, mut secret: Secret) -> Result { + let source = Source::new(&task.url)?.with_headers(&task.headers); // The task may have a new link since. let home = secret.home.as_deref().and_then(|h| Url::parse(h).ok()); if !home.is_some_and(|home| same_site(&home, &source.url)) { diff --git a/crates/core/tests/auth.rs b/crates/core/tests/auth.rs index cf7ddf8..a148790 100644 --- a/crates/core/tests/auth.rs +++ b/crates/core/tests/auth.rs @@ -3,10 +3,10 @@ use medlar_core::auth::Login; use medlar_core::host::{Caps, Hosts}; use medlar_core::http::{ClientOptions, Error, Monitor, Options, Shared, client, download}; -use medlar_core::manager::{Command, Config, Manager}; +use medlar_core::manager::{Command, Config, Files, Manager}; use medlar_core::model::{ErrorKind, State, Task}; use medlar_core::net_state::Bus; -use medlar_core::secret::{Kept, Secret, Secrets}; +use medlar_core::secret::{self, Kept, Secret, Secrets}; use medlar_core::settings::{Limits, Settings}; use medlar_core::site::{Site, Sites}; use medlar_core::store::{self, Store}; @@ -756,3 +756,75 @@ async fn the_manager_uses_the_sites() { assert_eq!((task.state, most.max(1)), (State::Done, 1)); assert!(std::fs::read(task.folder.join(&task.name)).unwrap() == expected(7, 0, 8 << 20)); } + +#[tokio::test] +async fn keyring_items_go_with_their_last_task() { + let b = Bench::new().await; + let open = || { + let shared = Shared { client: client(&ClientOptions::default()).unwrap(), store: b.store.clone(), hosts: Hosts::new(Caps::default()) }; + let mut config = Config::new(shared, Limits::default()); + config.sites = Some(b.sites.clone()); + config.undo = Duration::ZERO; + Manager::open(config).unwrap() + }; + let manager = open(); + let secrets = &b.sites.secrets; + let kept = async |name: &str, there: bool| { + for _ in 0..200 { + if secrets.load(name).await.is_some() == there { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("{name}: {}", !there); + }; + let (one, two, three) = (secret::task_name(), secret::task_name(), secret::task_name()); + assert!(one != two && two != three); + for name in [&one, &two, &three, &"site:h".to_string()] { + secrets.save(name, "h", &with_login(PASSWORD)).await; + } + let add = |name: &str| { + let task = Task { secret: Some(name.into()), state: State::Paused, ..b.task("/data/7/300000/f.bin") }; + manager.send(Command::Add(Box::new(task))) + }; + let first = add(&one).await.unwrap(); + let both = manager.send(Command::KeepBoth(first)).await.unwrap(); + manager.send(Command::Pause(both)).await.unwrap(); + let site = add("site:h").await.unwrap(); + let last = add(&three).await.unwrap(); + // The other one has it still. + manager.send(Command::Remove { id: first, files: Files::Keep }).await.unwrap(); + let new = two.clone(); + manager.send(Command::Remove { id: site, files: Files::Keep }).await.unwrap(); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(secrets.load(&one).await.is_some() && secrets.load("site:h").await.is_some()); + manager.send(Command::Edit { id: both, edit: Box::new(move |t| t.secret = Some(new)) }).await.unwrap(); + kept(&one, false).await; + kept(&two, true).await; + manager.send(Command::Edit { id: both, edit: Box::new(|t| t.secret = None) }).await.unwrap(); + kept(&two, false).await; + // Removed, and Medlar ended before it was forgotten. + manager.close(); + b.store.edit_task(last, |t| t.removed_at = Some(1)).unwrap(); + assert!(secrets.load(&three).await.is_some()); + let _manager = open(); + kept(&three, false).await; + kept("site:h", true).await; +} + +#[tokio::test] +async fn links_are_looked_at_before_they_are_added() { + let b = Bench::new().await; + let shared = Shared { client: client(&ClientOptions::default()).unwrap(), store: b.store.clone(), hosts: Hosts::new(Caps::default()) }; + let mut config = Config::new(shared, Limits::default()); + config.sites = Some(b.sites.clone()); + let manager = Manager::open(config).unwrap(); + let found = manager.probe(b.task("/data/7/300000/f.bin"), None).await.unwrap(); + assert_eq!((&*found.name, found.size, found.ranges, found.page), ("f.bin", Some(300_000), true, false)); + let task = b.task(&format!("/basic/me/{PASSWORD}/data/7/300000/f.bin")); + let Err(medlar_core::manager::Error::Link(why)) = manager.probe(task.clone(), None).await else { panic!("no login asked for") }; + assert_eq!(why.kind, ErrorKind::Login); + let secret = Secret { home: Some(task.url.clone()), ..with_login(PASSWORD) }; + assert_eq!(manager.probe(task, Some(secret)).await.unwrap().size, Some(300_000)); + assert!(manager.snapshot().is_empty()); +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 0b93c8b..fbbacc7 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -58,3 +58,6 @@ - D-056 — 2026-11-25 — Streams are kept as pieces in one unfinished file with a record before each (`stream::tape`), and joined by ffmpeg with `-c copy` from sockets of this user: mp4 (m4a for sound alone) or what the name asks for, mkv where that can't hold it. — One file moves and bins like any other; needs twice, not three times the space. — 02, 06 - D-057 — 2026-11-25 — ffmpeg never opens links of lists: Medlar fetches all of HLS and DASH itself (proxy, logins, limits), and ffmpeg may open only `unix` sockets and known formats. For RTSP and MMS it connects itself, never when a proxy is set; logins go through its standard input. — Lists come from strangers; arguments are seen by all. — 02, 06 - D-058 — 2026-11-25 — Any sign of protection refuses the whole stream (`ErrorKind::Drm`): `ContentProtection`, keys other than AES-128 with `identity`, protected boxes in the first piece. — CLAUDE.md 4. — 02, 06 +- D-059 — 2026-11-25 — A pasted link is looked at 0.5 s after the last change, without being kept; links of a batch are not. A list makes 10,000 downloads at most, the rest is counted and said. Patterns count in what the user writes, never in what programs and files give. — One-time links, servers and the user's patience. — 03, 05 +- D-061 — 2026-11-25 — A task's keyring items are named `task:…`, one per site and login of what was added together, and deleted by the manager with the last task that has them. Folders by type and the recent ones are in `view.json`. A start time is a `Waiting` task with `Hold::Until`. — No secrets stay behind; no new setting. — 03, 04, 05 +- D-071 — 2026-11-25 — What the list knows comes first in the dialog: the same link or checksum offers Resume or Show, a likely match offers Continue; `Same` goes on at once, all other verdicts are shown before a second click, `Different` leaves only a new file. The same name alone changes nothing: the new file gets a number. — Nothing is lost or loaded twice by accident. — 03, 05 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index ba1458a..e116f64 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -182,3 +182,15 @@ Seen: tested in a second checkout on the shared target; S009 saw stale artifacts ## Later - + +## S016 — Add dialog, batch and duplicates (2026-11-25) +Done: `views::add` (dialog, batch, duplicates, "Continue from a new link"), `core::{batch, duplicate, portal}`. Choices: D-059, D-061, D-071. Outside the plan's files: `Manager::probe` and `Hold::Until` for start times, `secret::task_name`, `Sites::source_with`, `disk::free`, `bridge` (add, check, probe, poll), `dialog::shown`, `view.json` (folders), strings. +Verified: `nice cargo test -j 2 -p medlar --test add` green (14, four with the real engine), all medlar tests, core `--lib`, auth, manager, relink; clippy. Shots seen: empty, simple, advanced, error, batch, duplicate, continue, relink, at 1080×720 and simple at 480×360, some light, some dark. Built in a copy of the tree while S009 and S012 were half done. +- **Open it from outside: `app.main.adding.ask(views::add::Request { text, literal: true, name, size, mime, page, user_agent, cookies, headers, .. })`**; several wait in line (100 at most). `literal` for all that comes from a program (no patterns), `list` for a file with links. Cookies and secret headers end up in the keyring, not in the task. +- `adding.relink(&task)` asks for a new link; it compares first. "Get it from its page" sends `AwaitLink` and opens the page. +- `manager.probe(task, secret)` says what a link leads to (`Probed`); drop the reply to end it. `bridge::poll(&mut reply, ctx)` asks without waiting and draws a frame when it comes; `bridge::beside` runs something slow. +- Keyring: items named by `secret::task_name()` are deleted when no task has them any more (forgotten, edited, continued, removed before the program ended); shared ones stay. Other names (`site:`) are never touched. +- `Batch::of(text, patterns)`, `duplicate::Known::new(tasks).find(&New)`: for the connector, clipboard and rules. +Not done: the desktop's file chooser (portal) was never tried, only that it fails plainly is in the code; links of a batch are not asked about; what is known is found when the fields change, not when the list does; a start time is kept but queue schedules are S021's, and time asleep doesn't count; a metalink file is refused as a list (`read_metalink` is not wired, 3.3); files already on disk but not in the list are not noticed (the engine numbers names); no hidden release run. +Later: `App` doesn't set `ClientOptions::known_hosts` yet (S011). +Seen: boxes were ticked together after the tests, against rule 3. From d4eb7faf95dd4cd2ef2b7f233230aa82a93f33c8 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 14:28:13 -0600 Subject: [PATCH 06/70] S017: details panel, file actions, reveal in folder Co-Authored-By: Claude Sonnet 5.5 --- Plans/03 Interface/S017-details.md | 16 +- Plans/INDEX.md | 2 +- crates/app/src/app.rs | 1 + crates/app/src/keys.rs | 2 + crates/app/src/views/details/mod.rs | 198 ++++++++++++ crates/app/src/views/details/tabs.rs | 432 +++++++++++++++++++++++++++ crates/app/src/views/list/mod.rs | 4 + crates/app/src/views/main.rs | 30 +- crates/app/src/views/mod.rs | 1 + crates/core/lang/en.json | 73 ++++- crates/core/src/files.rs | 13 + crates/core/src/lib.rs | 1 + docs/PROGRESS.md | 5 + docs/tests/S017-details.md | 49 +++ 14 files changed, 816 insertions(+), 11 deletions(-) create mode 100644 crates/app/src/views/details/mod.rs create mode 100644 crates/app/src/views/details/tabs.rs create mode 100644 crates/core/src/files.rs create mode 100644 docs/tests/S017-details.md diff --git a/Plans/03 Interface/S017-details.md b/Plans/03 Interface/S017-details.md index 568da34..7632146 100644 --- a/Plans/03 Interface/S017-details.md +++ b/Plans/03 Interface/S017-details.md @@ -12,14 +12,14 @@ FEATURES 7.2, 7.3, 7.4, 9.3 in place. - crates/core/src/{verify,mirror}* ## Steps -- [ ] Side panel or bottom sheet by width: overview, parts map, graph, log, headers, mirrors, checksum -- [ ] File actions: open, show in folder (D-Bus FileManager1), move, rename, copy link, redownload, bin, "file is gone" state -- [ ] Tags and notes; tag colours from theme roles only -- [ ] Live edits: limit, parts, priority, queue, link, login -- [ ] Log with copy, filter and redaction; properties copyable -- [ ] Error section: what, why, when tried, next try, all fixes -- [ ] Test file `docs/tests/S017-details.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S017: …`, push +- [x] Side panel or bottom sheet by width: overview, parts map, graph, log, headers, mirrors, checksum +- [x] File actions: open, show in folder (D-Bus FileManager1), move, rename, copy link, redownload, bin, "file is gone" state +- [x] Tags and notes; tag colours from theme roles only +- [x] Live edits: limit, parts, priority, queue, link, login +- [x] Log with copy, filter and redaction; properties copyable +- [x] Error section: what, why, when tried, next try, all fixes +- [x] Test file `docs/tests/S017-details.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S017: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 9570c04..84571b5 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -28,7 +28,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S014](03%20Interface/S014-wavy-parts-shapes.md) Wavy bars, parts map, shapes and speed graph - [x] [S015](03%20Interface/S015-main-window.md) Main window and list - [x] [S016](03%20Interface/S016-add-dialog.md) Add dialog, batch and duplicates -- [ ] [S017](03%20Interface/S017-details.md) Details panel and file actions +- [x] [S017](03%20Interface/S017-details.md) Details panel and file actions - [x] [S018](03%20Interface/S018-settings-palette.md) Settings, colour, shortcuts and first run ## 04 Control diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 9edd68a..e7d86f2 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -373,6 +373,7 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode { } app.paths = Some(paths.clone()); app.main.outside = open_outside; + app.main.reveal = crate::views::main::reveal_outside; app.main.remember(paths.data.join("view.json")); if let Some(damage) = damage { app.main.toasts.error(damage_words(&damage), None); diff --git a/crates/app/src/keys.rs b/crates/app/src/keys.rs index d6d54fe..ccd944e 100644 --- a/crates/app/src/keys.rs +++ b/crates/app/src/keys.rs @@ -23,6 +23,7 @@ pub enum Action { SelectAll, OpenOrRun, Toggle, + Details, Show, Copy, Page, @@ -88,6 +89,7 @@ pub const ALL: &[Entry] = &[ entry(Action::SelectAll, "select_all", "select_all", Group::List, "Ctrl+A"), entry(Action::OpenOrRun, "open", "open_in_new", Group::List, "Enter"), entry(Action::Toggle, "toggle", "play_circle", Group::List, "Space"), + entry(Action::Details, "details", "info", Group::List, "Alt+Enter"), entry(Action::Show, "show", "folder_open", Group::List, "Ctrl+O"), entry(Action::Copy, "copy", "content_copy", Group::List, "Ctrl+C"), entry(Action::Page, "page", "public", Group::List, ""), diff --git a/crates/app/src/views/details/mod.rs b/crates/app/src/views/details/mod.rs new file mode 100644 index 0000000..748fb6f --- /dev/null +++ b/crates/app/src/views/details/mod.rs @@ -0,0 +1,198 @@ +//! The details panel of one download: a side panel in a wide window, a sheet at the bottom in a narrow one. + +mod tabs; + +use super::list::Order; +use crate::bridge::{self, Bridge, Lists}; +use crate::theme::Theme; +use crate::tokens::{radius, size, space, text}; +use crate::ui::graph; +use crate::ui::widgets::{Button, Tab, cr, tabs}; +use crate::fonts; +use eframe::egui::{Key, Rect, RichText, ScrollArea, Ui, UiBuilder, vec2}; +use medlar_core::model::{State, TaskId}; +use medlar_core::snapshot::{Snapshot, TaskView}; +use medlar_core::tr; +use std::path::PathBuf; +use std::time::{Duration, Instant}; +use tokio::sync::oneshot; + +/// Windows at least this wide get a side panel. +const SIDE_FROM: f32 = 900.0; +/// How often a finished file is looked for. +const LOOK: Duration = Duration::from_secs(3); +/// Seconds the speed graph shows. +const SPAN: usize = 300; + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub enum Pane { + #[default] + Overview, + Parts, + Speed, + Log, + Headers, + Mirrors, + Checksum, +} + +impl Pane { + const ALL: [(Pane, &'static str, &'static str); 7] = [ + (Pane::Overview, "info", "details.tab.overview"), + (Pane::Parts, "view_list", "details.tab.parts"), + (Pane::Speed, "speed", "details.tab.graph"), + (Pane::Log, "description", "details.tab.log"), + (Pane::Headers, "list", "details.tab.headers"), + (Pane::Mirrors, "public", "details.tab.mirrors"), + (Pane::Checksum, "verified", "details.tab.checksum"), + ]; +} + +pub struct Details { + /// The download shown; None when the panel is closed. + pub open: Option, + pub tab: Pane, + /// What the log is filtered by. + pub filter: String, + note: (TaskId, String), + paste: String, + graph: graph::History, + seen: u64, + /// The finished file is not where it was left. + missing: bool, + looked: Instant, + looking: Option>, + /// For the slots of later plans (media, archive): tabs they add. + pub extra: Vec, +} + +/// A tab added by another part of the program (the media and archive plans). +pub struct Extra { + pub name: String, + pub icon: &'static str, + pub body: fn(&mut Ui, &Theme, &TaskView), +} + +impl Default for Details { + fn default() -> Details { + Details { + open: None, + tab: Pane::Overview, + filter: String::new(), + note: (0, String::new()), + paste: String::new(), + graph: graph::History::new(SPAN + 2), + seen: 0, + missing: false, + looked: Instant::now(), + looking: None, + extra: vec![], + } + } +} + +impl Details { + /// Takes the room of the panel from `body`: the rest and the panel. + pub fn split(&mut self, body: Rect, shot: &Snapshot) -> (Rect, Option) { + if self.open.is_some_and(|id| shot.get(id).is_none()) { + self.close(); + } + if self.open.is_none() { + return (body, None); + } + let wide = body.width() + 2.0 * space::XL >= SIDE_FROM; + let (rest, panel) = if wide { + let width = (size::SHEET + size::DIALOG_S * 0.5).min(body.width() / 2.0); + let (rest, panel) = body.split_left_right_at_x(body.right() - width); + (rest.with_max_x(rest.right() - space::M), panel) + } else { + let (rest, panel) = body.split_top_bottom_at_y(body.bottom() - (body.height() * 0.55).max(size::DIALOG_S.min(body.height()))); + (rest.with_max_y(rest.bottom() - space::S), panel) + }; + (rest, Some(panel)) + } + + fn close(&mut self) { + self.open = None; + self.missing = false; + self.looking = None; + } + + /// Keeps the speed graph and the "file is gone" state up with the download. + fn follow(&mut self, ui: &Ui, v: &TaskView) { + let h = &v.history; + if h.pushed() < self.seen { + self.graph = graph::History::new(SPAN + 2); + self.seen = 0; + } + let new = (h.pushed() - self.seen).min(h.samples().len() as u64) as usize; + for s in h.samples().skip(h.samples().len() - new) { + self.graph.push(f64::from(s)); + } + self.seen = h.pushed(); + if v.state() != State::Done { + self.missing = false; + self.looking = None; + return; + } + if let Some(rx) = &mut self.looking { + if let Some(answer) = bridge::poll(rx, ui.ctx()) { + self.looking = None; + self.looked = Instant::now(); + self.missing = answer.unwrap_or(false); + } + } else if self.looked.elapsed() >= LOOK { + let file: PathBuf = v.task.folder.join(&v.task.name); + self.looking = Some(bridge::beside(move || file.is_absolute() && !file.exists())); + } + ui.ctx().request_repaint_after(LOOK); + } + + /// Draws the panel in `rect`. What needs the window comes back as orders. + pub fn show(&mut self, ui: &mut Ui, t: &Theme, rect: Rect, shot: &Snapshot, lists: &Lists, bridge: &Bridge) -> Vec { + let Some(v) = self.open.and_then(|id| shot.get(id)).cloned() else { return vec![] }; + if self.open != Some(self.note.0) { + self.note = (v.id(), v.task.notes.clone()); + self.graph = graph::History::new(SPAN + 2); + self.seen = 0; + } + self.follow(ui, &v); + let mut orders = vec![]; + let p = ui.painter(); + p.rect_filled(rect, cr(radius::L), t.container); + let inner = rect.shrink(space::L); + let mut ui = ui.new_child(UiBuilder::new().max_rect(inner).id_salt(("details", v.id()))); + let ui = &mut ui; + ui.horizontal(|ui| { + let name = super::list::model::title(&v); + ui.add_sized(vec2((inner.width() - size::HIT - space::S).max(0.0), size::HIT), eframe::egui::Label::new(RichText::new(name).font(fonts::semi(text::TITLE)).color(t.on_surface)).truncate()); + if Button::icon("close", &tr!("details.close")).show(ui, t).clicked() { + self.close(); + } + }); + let mut at = Pane::ALL.iter().position(|(k, ..)| *k == self.tab).unwrap_or(0); + let words: Vec = Pane::ALL.iter().map(|(_, _, key)| medlar_core::strings::text(key, &[])).collect(); + let options: Vec = Pane::ALL.iter().zip(&words).map(|((_, icon, _), text)| Tab { icon, text, count: None }).collect(); + if tabs(ui, t, "details", &options, &mut at) { + self.tab = Pane::ALL[at].0; + } + ui.add_space(space::S); + let tab = self.tab; + ScrollArea::vertical().auto_shrink(false).id_salt(("details-body", tab as u8)).show(ui, |ui| { + let mut cx = tabs::Cx { t, v: &v, lists, bridge, orders: &mut orders, missing: self.missing }; + match tab { + Pane::Overview => tabs::overview(ui, &mut cx, &mut self.note), + Pane::Parts => tabs::parts(ui, &mut cx), + Pane::Speed => tabs::speed(ui, &mut cx, &self.graph), + Pane::Log => tabs::log(ui, &mut cx, &mut self.filter), + Pane::Headers => tabs::headers(ui, &mut cx), + Pane::Mirrors => tabs::mirrors(ui, &mut cx), + Pane::Checksum => tabs::checksum(ui, &mut cx, &mut self.paste), + } + }); + if ui.input(|i| i.key_pressed(Key::Escape)) && ui.memory(|m| m.focused().is_none()) { + self.close(); + } + orders + } +} diff --git a/crates/app/src/views/details/tabs.rs b/crates/app/src/views/details/tabs.rs new file mode 100644 index 0000000..67bda01 --- /dev/null +++ b/crates/app/src/views/details/tabs.rs @@ -0,0 +1,432 @@ +//! The pages of the details panel. + +use super::super::list::model::{Status, host_name, queue_name, span, title, when}; +use super::super::list::row::state_label; +use super::super::list::{Act, Order, act_of_fix}; +use crate::bridge::{Bridge, Lists}; +use crate::theme::Theme; +use crate::tokens::{icon, radius, size, space, text}; +use crate::ui::field::{Combo, Field, Number}; +use crate::ui::graph; +use crate::ui::odometer::{amount, rate}; +use crate::ui::parts::{self, Block}; +use crate::ui::widgets::{Button, Chip, Kind}; +use crate::fonts; +use eframe::egui::{Color32, Grid, Id, Label, RichText, ScrollArea, Sense, TextStyle, Ui, vec2}; +use medlar_core::error::{Fix, Retry}; +use medlar_core::manager::{Command, Files}; +use medlar_core::model::{Priority, State, Tag, TaskId, Time, now}; +use medlar_core::snapshot::{Log, TaskView}; +use medlar_core::verify::{self, Checksum, Offer}; +use medlar_core::{redact, tr}; + +pub struct Cx<'a> { + pub t: &'a Theme, + pub v: &'a TaskView, + pub lists: &'a Lists, + pub bridge: &'a Bridge, + pub orders: &'a mut Vec, + /// A finished file that is not on the disk. + pub missing: bool, +} + +impl Cx<'_> { + fn id(&self) -> TaskId { + self.v.id() + } + + fn act(&mut self, act: Act) { + self.orders.push(Order::Do(act, vec![self.id()])); + } + + fn edit(&self, edit: impl FnOnce(&mut medlar_core::model::Task) + Send + 'static) { + self.bridge.send(Command::Edit { id: self.id(), edit: Box::new(edit) }); + } + + fn button(&mut self, ui: &mut Ui, icon: &str, words: &str, enabled: bool) -> bool { + Button::new(words).with_icon(icon).kind(Kind::Tonal).enabled(enabled).show(ui, self.t).clicked() + } +} + +/// A tag's colour comes from the theme's roles: its own number picks one. +pub fn tag_colour(t: &Theme, tag: &Tag) -> Color32 { + [t.primary, t.tertiary, t.secondary, t.warning, t.success, t.error][tag.id.unsigned_abs() as usize % 6] +} + +/// The lines of a log that hold `filter` (any case), as text for copying: time, then words. No secrets. +pub fn log_lines(log: &Log, filter: &str) -> Vec { + let f = filter.trim().to_lowercase(); + log.iter().filter(|l| f.is_empty() || l.text.to_lowercase().contains(&f)).map(|l| format!("{} {}", when(l.at), redact::text(&l.text))).collect() +} + +fn small(ui: &mut Ui, t: &Theme, words: &str) { + ui.add(Label::new(RichText::new(words).font(fonts::ui(text::BODY)).color(t.on_variant)).wrap()); +} + +fn head(ui: &mut Ui, t: &Theme, words: &str) { + ui.add_space(space::M); + ui.label(RichText::new(words).font(fonts::semi(text::BODY)).color(t.on_surface)); + ui.add_space(space::XS); +} + +/// Rows of name and value; a click copies the value. +fn props(ui: &mut Ui, t: &Theme, id: &str, rows: &[(String, String)]) { + Grid::new(id).num_columns(2).spacing(vec2(space::L, space::XS)).show(ui, |ui| { + for (name, value) in rows { + ui.label(RichText::new(name).font(fonts::ui(text::LABEL)).color(t.on_variant)); + let r = ui.add(Label::new(RichText::new(value).font(fonts::ui(text::BODY)).color(t.on_surface)).wrap().sense(Sense::click())); + if r.clicked() { + ui.ctx().copy_text(value.clone()); + } + r.on_hover_text(tr!("details.copy")); + ui.end_row(); + } + }); +} + +fn when_or(time: Option