misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
A finished download no longer fails with "part file still in use"; the starved engine tests of #201 wait for what they check (#223)
Ahmed Nefzaoui9998d4b3ebec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6754b8b7..80bb4dc1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -323,6 +323,17 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Changed+- **Developers: the rest of the engine tests no longer fail on a busy computer**+ ([#201](https://github.com/anefzaoui/misterdownloadmanager/issues/201)). Nine tests checked a+ time, a speed or a byte count that a starved CPU or a busy CI runner can't keep. Each now+ checks the state itself, or times from the event it is about: a slow request's own duration, a+ stop measured from Stop against a wait of minutes, the first bytes before a pause, a speed+ limit against a download the server paces at the same time (and every byte paid for once),+ parts asked again instead of a deadline, links that expire after a number of requests instead+ of milliseconds, range attempts a server without ranges answers slowly enough not to fill the+ sockets, and the bytes a sparse file takes on the drive. The slow-connection test now fails+ without shedding (it passed without it before). The lab server can hand out such links+ (`/redirect?uses=N`) and pace answers to range requests on their own (`range_rate`).- **Developers: a Linux test machine, scripted** (part of [#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164)):`tools/lab/linux-vm/` sets up an Ubuntu 24.04 desktop in VirtualBox from a Windows host(`vm.ps1`: hardware, headless start, linked clones; `setup.sh`: packages, Rust, Node, the@@ -427,6 +438,13 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- **A finished download no longer fails with "part file still in use" on a busy computer**+ ([#201](https://github.com/anefzaoui/misterdownloadmanager/issues/201)): when the last bytes+ came in, the connections still running were cut off. One cut off while it read or wrote the+ part file (checking the bytes before a reconnect, for example) left that read or write to finish+ on its own, with the file still open, and renaming the finished file failed. The connections are+ now told to stop and waited for, when a download completes and when it is stopped or fails, so+ none of them outlives it. A stopped download's last writes are also in its saved progress now.- **Menus without a black band across their top**([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208)): on a Windows 11Insider build (22635), every menu and submenu showed a black band a title bar tall across itsdiff --git a/ROADMAP.md b/ROADMAP.mdindex 03a4dc67..77530aa8 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,11 @@ Everything below ships together, in one release, as version 0.3.0.### Done+- ✅ A finished download no longer fails with "part file still in use" on a busy computer, and+ the rest of the engine tests that failed now and then there (slow connections, a prompt stop,+ speed limits, links that expire, sparse files and a few more) wait for what they check, not for+ time; the slow-connection test now fails if the engine stops reconnecting slow connections,+ which it didn't before ([#201](https://github.com/anefzaoui/misterdownloadmanager/issues/201))- ✅ A window closed with its title bar's × keeps its contents until it goes, instead of turningblack for a moment (seconds on Linux) ([#207](https://github.com/anefzaoui/misterdownloadmanager/issues/207))- ✅ A freeze while MDM handles a command, or minimized, opens the crash report window and writesdiff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rsindex d6c92476..e6a3e251 100644--- a/crates/engine/src/download.rs+++ b/crates/engine/src/download.rs@@ -2584,8 +2584,7 @@ async fn supervise(ctx: Arc<Ctx>, first: Option<Body>) -> Result<(), Error> {};match joined.expect("worker panicked") {Err(e) if e.is_fatal() => {- ctx.cancel.cancel();- set.shutdown().await;+ stop_connections(&ctx, &mut set).await;return Err(e);}Err(e) => last_err = Some(e),@@ -2596,7 +2595,7 @@ async fn supervise(ctx: Arc<Ctx>, first: Option<Body>) -> Result<(), Error> {// a busy machine) have nothing left to fetch. Stopped now, a late answer can't start// the download over (#136: a server without ranges sent the whole file twice).if complete {- set.shutdown().await;+ stop_connections(&ctx, &mut set).await;break;}if set.is_empty() {@@ -2610,6 +2609,18 @@ async fn supervise(ctx: Arc<Ctx>, first: Option<Body>) -> Result<(), Error> {Ok(())}+/// Stop the connections still running, and wait until each has. They are told to stop, not+/// aborted: a connection aborted in a blocking read or write of the part file (the check of+/// its overlap, a write) leaves that call running, with the file open, after the download has+/// ended. A finished download then failed with "part file still in use", the rename's handle+/// still taken (#201: a connection taken over in its overlap check, on a busy machine), and a+/// stopped one went on writing after it had returned. Every wait of a connection ends on its+/// token, and a blocking call only takes as long as one read or write.+async fn stop_connections(ctx: &Ctx, set: &mut JoinSet<Result<(), Error>>) {+ ctx.cancel.cancel();+ while set.join_next().await.is_some() {}+}+/// One connection: take an assignment, fetch it, repeat until there is nothing left to do.async fn worker(ctx: Arc<Ctx>, id: WorkerId, mut first: Option<Body>) -> Result<(), Error> {let mut after = None;@@ -3048,7 +3059,11 @@ async fn receive(// A segment another connection shortened leaves an HTTP body far from its end// (dropped); an FTP session is kept either way.if err.is_none() && (pos >= to || matches!(body, Body::Ftp(_))) {- body.done(ended).await;+ // Not past a stop (`stop_connections` waits for this connection).+ tokio::select! {+ _ = ctx.cancel.cancelled() => {}+ () = body.done(ended) => {}+ }}return Ok(Some(end));}diff --git a/crates/engine/src/sparse.rs b/crates/engine/src/sparse.rsindex aabece4a..308c6d89 100644--- a/crates/engine/src/sparse.rs+++ b/crates/engine/src/sparse.rs@@ -6,7 +6,8 @@//! first second, so every large download paid it. A sparse file has no such fill. Elsewhere//! (`ftruncate` already makes sparse files) this is a no-op.//!-//! The engine's only unsafe code: one `DeviceIoControl` call.+//! The engine's only unsafe code: one `DeviceIoControl` call (and, in its test, one+//! `GetCompressedFileSizeW`).#![allow(unsafe_code)]use std::fs::File;@@ -70,25 +71,49 @@ mod tests {f.metadata().unwrap().file_attributes() & FILE_ATTRIBUTE_SPARSE_FILE != 0}+ /// The bytes the file takes on the drive (for a sparse file, only its written ranges).+ fn on_drive(path: &std::path::Path) -> u64 {+ use std::os::windows::ffi::OsStrExt;+ use windows_sys::Win32::Storage::FileSystem::GetCompressedFileSizeW;+ let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();+ let mut high = 0u32;+ // SAFETY: `wide` is a NUL-terminated UTF-16 path that outlives the call; `high` is a+ // valid u32 for the size's upper half.+ let low = unsafe { GetCompressedFileSizeW(wide.as_ptr(), &mut high) };+ if low == u32::MAX {+ // Also a valid low half: only the error code tells.+ let e = std::io::Error::last_os_error();+ assert_eq!(e.raw_os_error(), Some(0), "GetCompressedFileSizeW: {e}");+ }+ (u64::from(high) << 32) | u64::from(low)+ }+#[test]fn a_sparse_part_file_is_written_far_in_without_a_fill() {let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("p.bin");let mut f = File::options().read(true).write(true).create(true).truncate(true)- .open(dir.path().join("p.bin"))+ .open(&path).unwrap();assert!(set(&f, true), "NTFS temp folder");assert!(is_sparse(&f));f.set_len(4 << 30).unwrap();- let started = std::time::Instant::now();f.seek(SeekFrom::Start(2 << 30)).unwrap();f.write_all(&[7u8; 1 << 20]).unwrap();f.sync_data().unwrap();- // A fill would write 2 GiB first (0.5–4 s on this machine).- assert!(started.elapsed() < std::time::Duration::from_millis(400));+ // A fill would have written the 2 GiB before the write (0.5–4 s on this machine), and+ // a file that isn't sparse takes its whole 4 GiB on the drive. This one holds only what+ // was written: measured on the drive, not timed (#201: a 400 ms budget failed on a busy+ // CI runner and on a starved CPU).+ let used = on_drive(&path);+ assert!(+ ((1 << 20)..(64 << 20)).contains(&used),+ "{used} bytes on the drive"+ );// Clearing allocates any holes left, so only a fully written file is cleared: shrink// this mostly empty one first.f.set_len(0).unwrap();diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rsindex bca1fd54..8356183d 100644--- a/crates/engine/tests/e2e.rs+++ b/crates/engine/tests/e2e.rs@@ -145,8 +145,22 @@ async fn a_slow_download_does_not_rewrite_its_state_every_tick() {}};let first = std::fs::read(&state).unwrap();- // 20 save ticks while bytes trickle in: no flush is due, nothing is rewritten.- tokio::time::sleep(std::time::Duration::from_secs(1)).await;+ // Save ticks while bytes trickle in: no flush is due, nothing is rewritten. Waits for the+ // bytes themselves, not a time (#201: on a starved CPU none had come in a second): the first+ // ones, then more, over at least a second (20 ticks; fewer on a starved CPU, never none).+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);+ let running = &dl;+ let bytes_in = move |more_than: u64| async move {+ while running.snapshot().downloaded <= more_than {+ assert!(std::time::Instant::now() < deadline, "no bytes came in");+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ }+ running.snapshot().downloaded+ };+ let ticks = tokio::time::sleep(std::time::Duration::from_secs(1));+ let early = bytes_in(0).await;+ bytes_in(early).await;+ ticks.await;assert_eq!(std::fs::read(&state).unwrap(),first,@@ -412,19 +426,31 @@ async fn a_refusal_below_the_learned_cap_is_retried() {#[tokio::test]async fn slow_connections_reconnect_instead_of_holding_the_end() {- // Every third request crawls at 20 KB/s: without shedding, all connections end up on- // such requests and 8 MiB takes ~12 s.- let s = server("rate=8M&slow_every=3&slow_rate=20K").await;- let started = std::time::Instant::now();- let (log, size) = fetch(&s, "/gen/8M/slow.bin?seed=32", 32, fast_opts()).await;+ // Every third request crawls at 1 KB/s. The other connections split such a request's part+ // and take its halves over, down to pieces too small to split again (64 KiB here): without+ // shedding, a slow request holds the end on such a piece for over a minute.+ let s = server("rate=8M&slow_every=3&slow_rate=1K").await;+ let opts = Options {+ min_split: 64 << 10,+ ..fast_opts()+ };+ let (log, size) = fetch(&s, "/gen/8M/slow.bin?seed=32", 32, opts).await;assert_eq!(size, 8 << 20);+ // Timed from each slow request's own start, not the download's (#201: on a starved CPU the+ // whole download took 8-25 s against an 8 s budget, and at 20 KB/s it took under 8 s without+ // shedding too). Shedding drops a slow request once 2 s have shown it slow (or lets it end+ // with under 2 s of its own pace left): about 2 s on an idle machine, up to 8 s on a starved+ // one. Without shedding the last ones run 64 s or more.+ let slow: Vec<_> = log+ .iter()+ .filter(|e| e.rate == Some(1024))+ .map(|e| (e.t_end_ms - e.t_start_ms, e.bytes_sent, e.body_len))+ .collect();+ assert!(!slow.is_empty(), "the fault was there");assert!(- started.elapsed() < std::time::Duration::from_secs(8),- "took {:?}",- started.elapsed()+ slow.iter().all(|(ms, ..)| *ms < 20_000),+ "a slow request held its piece (ms, sent, asked): {slow:?}");- let slow = log.iter().filter(|e| e.rate == Some(20 * 1024)).count();- assert!(slow > 0, "the fault was there");}#[tokio::test]@@ -577,8 +603,11 @@ async fn no_range_server_uses_one_connection() {#[tokio::test]async fn a_server_without_ranges_sends_the_file_once() {// The probe takes about 375 ms; every range attempt is answered after 300 ms, so the first- // answers come while it runs and a retry's after it has ended.- let s = server("no_range=true&rate=8M&range_latency_ms=300").await;+ // answers come while it runs and a retry's after it has ended. The range attempts' answers+ // (the whole file, which the engine drops at their headers) come at 32 KB/s: at the probe's+ // 8 MB/s the server filled each one's socket (1.3 MiB on Windows) before a starved CPU had+ // dropped them, and 7 of them made 12.8 MB served for 3 MiB (#201).+ let s = server("no_range=true&rate=8M&range_latency_ms=300&range_rate=32K").await;let (log, size) = fetch(&s, "/gen/3M?seed=41", 41, fast_opts()).await;assert_eq!(size, 3 << 20);let sent: u64 = log.iter().map(|e| e.bytes_sent).sum();@@ -588,7 +617,7 @@ async fn a_server_without_ranges_sends_the_file_once() {.collect();// One plain GET, the probe: no start over on one connection. The bytes served beyond the// file are what the server had written into the range attempts' sockets when the engine- // dropped them (a few hundred KiB on a busy machine); a second copy would double them.+ // dropped them (32 KB a second each); a second copy would double them.assert_eq!(log.iter().filter(|e| e.range.is_none()).count(),1,@@ -968,11 +997,13 @@ async fn a_plain_web_page_is_still_downloaded() {#[tokio::test]async fn signed_links_that_expire_while_downloading_are_refreshed() {- // Each redirect hands out a link valid for 400 ms; connections drop every 256 KB, so they- // keep asking for new ranges after their link expired.+ // Each redirect hands out a link good for 4 requests; connections drop every 256 KB, so they+ // keep asking for new ranges after their link expired. Counted in requests, not time (#201:+ // a link valid for 400 ms could expire on a starved CPU before the refresh that asked for it+ // had used it, and the download failed with LinkExpired).let s = server("rate=1M&drop_after=256K").await;let target = s.url("/gen/4M/signed.bin?seed=23");- let path = format!("{}&ttl_ms=400", redirect_path(&target));+ let path = format!("{}&uses=4", redirect_path(&target));let opts = Options {max_connections: 4,..fast_opts()@@ -1031,14 +1062,15 @@ async fn resume_follows_the_original_address_when_the_redirected_one_expired() {async fn a_dead_link_fails_fast_instead_of_retrying() {let s = server("rate=1M").await;let (_dir, state) = paused(&s, "/gen/8M/d.bin?seed=15").await;- // The address now answers 404 (and there is no other address to fall back to).+ // The address now answers 404 (and there is no other address to fall back to); the server+ // logs it ("gone" is no size).let mut saved = mdm_engine::state::ResumeState::load(&state).unwrap();- let gone: url::Url = s.url("/gone").parse().unwrap();+ let gone: url::Url = s.url("/gen/gone/d.bin").parse().unwrap();saved.url = gone.clone();saved.final_url = gone;std::fs::write(&state, serde_json::to_vec(&saved).unwrap()).unwrap();- let started = std::time::Instant::now();- // Default options: retries back off from 1 s, so retrying a 404 would take far longer.+ s.clear_log();+ // Default options: a retry would wait 1 s first, then longer.let err = Download::resume(state, Default::default(), Options::default()).unwrap().wait()@@ -1048,11 +1080,26 @@ async fn a_dead_link_fails_fast_instead_of_retrying() {matches!(err, mdm_engine::Error::Status(s) if s.as_u16() == 404),"{err}");- assert!(- started.elapsed() < std::time::Duration::from_secs(3),- "took {:?}",- started.elapsed()- );+ asked_once(&s).await;+}++/// Every request the server got since its log was cleared asks for another part: nothing was+/// asked again, so nothing was retried. Counted, not timed (#201: a 3 s budget, against the 1 s+/// a first retry waits, failed on a starved CPU).+async fn asked_once(s: &LabServer) {+ tokio::time::timeout(SETTLE, s.settled())+ .await+ .expect("every request ends");+ let log = s.log();+ let asked: Vec<_> = log+ .iter()+ .map(|e| (e.range.clone(), e.status, e.outcome.clone()))+ .collect();+ let mut ranges: Vec<_> = log.iter().map(|e| e.range.clone()).collect();+ ranges.sort();+ ranges.dedup();+ assert!(!log.is_empty(), "nothing was asked");+ assert_eq!(ranges.len(), log.len(), "a part was asked again: {asked:?}");}/// Point a paused download's state at its own address plus the fault overrides `faults`.@@ -1071,14 +1118,15 @@ async fn a_web_page_instead_of_the_file_stops_the_resume() {let (_dir, state) = paused(&s, "/gen/8M/w.bin?seed=16").await;// The link now leads to a sign-in page.with_faults(&state, "html=true");- let started = std::time::Instant::now();+ s.clear_log();+ // Default options: a retry would wait 1 s first, then longer.let err = Download::resume(state.clone(), Default::default(), Options::default()).unwrap().wait().await.unwrap_err();assert!(matches!(err, mdm_engine::Error::GotWebPage), "{err}");- assert!(started.elapsed() < std::time::Duration::from_secs(3));+ asked_once(&s).await;assert!(state.exists(), "the data is kept for a later resume");}@@ -1247,17 +1295,63 @@ async fn changed_file_fails() {async fn speed_limit_caps_the_whole_download() {// 8 connections, but the limit is per download (IDM: "for one file").let s = server("").await;- let opts = Options {+ // The download alone is timed, not the wait for the server's log (#201: `fetch` waits for+ // it, which a starved CPU stretched to seconds).+ let timed = |path: &str, seed: u64, opts: Options| {+ let dir = tempfile::tempdir().unwrap();+ let req = Request {+ url: s.url(path).parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ };+ async move {+ let started = std::time::Instant::now();+ let out = Download::start(req, opts)+ .wait()+ .await+ .expect("download succeeds");+ let secs = started.elapsed().as_secs_f64();+ let mut want = vec![0; 2 << 20];+ content::fill(seed, 0, &mut want);+ assert!(+ std::fs::read(&out.path).unwrap() == want,+ "content mismatch"+ );+ drop(dir);+ secs+ }+ };+ // At the same time, a yardstick: the same 2 MiB at 1 MiB/s, paced by the server on one+ // connection, with no limit of ours. It takes 2 s on an idle machine, and as long as the+ // machine makes it on a busy one.+ // An unlimited global cap beside the limit counts the bytes the connections pay for.+ let paid = std::sync::Arc::new(mdm_engine::limiter::Limiter::new(None));+ let limited = Options {speed_limit: Some(1 << 20),+ global: Some(paid.clone()),..fast_opts()};- let t = std::time::Instant::now();- let (_, size) = fetch(&s, "/gen/2M?seed=12", 12, opts).await;- let secs = t.elapsed().as_secs_f64() - 0.3; // fetch() waits 300 ms for the server log- assert_eq!(size, 2 << 20);- // At least the time the limit allows (without it: well under a second). The upper bound- // only catches a limit far too strict; a busy CI runner adds seconds of its own.- assert!((1.5..6.0).contains(&secs), "2 MB at 1 MB/s took {secs:.2}s");+ let one = Options {+ max_connections: 1,+ ..fast_opts()+ };+ let (secs, paced) = tokio::join!(+ timed("/gen/2M/limited.bin?seed=12", 12, limited),+ timed("/gen/2M/paced.bin?seed=13&rate=1M", 13, one),+ );+ // At least the time the limit allows: the budget builds up from the download's start, so+ // 2 MiB can't come in under 2 s (without the limit: well under a second).+ assert!(secs >= 1.9, "2 MB at 1 MB/s took {secs:.2}s");+ // Every byte kept was paid for once: no byte waits for the limit twice (or for bytes thrown+ // away), whatever the machine's speed.+ assert_eq!(paid.taken(), 2 << 20, "bytes paid for");+ // The upper bound only catches a limit far too strict: 5 times the yardstick, about 10 s on+ // an idle machine (#201: a fixed 6 s failed on a starved CPU or a busy CI runner, which took+ // 6-17 s; there the limited download took up to 3.9 times as long as the yardstick).+ assert!(+ secs < 5.0 * paced,+ "2 MB at 1 MB/s took {secs:.2}s (paced by the server: {paced:.2}s)"+ );}/// #39: under a low limit each connection waits seconds for its turn; Stop ends those waits@@ -1271,21 +1365,45 @@ async fn stop_is_prompt_under_a_low_limit() {headers: Default::default(),dest: Destination::Dir(dir.path().to_owned()),};+ // The global cap starts unlimited: it only counts the bytes each connection pays for, until+ // the test needs a connection in a long wait.+ let global = std::sync::Arc::new(mdm_engine::limiter::Limiter::new(None));let opts = Options {speed_limit: Some(32 << 10),+ global: Some(global.clone()),..fast_opts()};let dl = Download::start(req, opts);- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);while dl.snapshot().downloaded < 64 << 10 {assert!(std::time::Instant::now() < deadline, "never started");tokio::time::sleep(std::time::Duration::from_millis(50)).await;}- let t = std::time::Instant::now();+ // A wait that can't pass for a slow machine (#201: a 1 s budget failed on a starved CPU,+ // where the stop itself took up to 3.4 s, about as long as the waits it must not sit out).+ // The cap goes to 32 KB/s with 4 MiB owed: any connection paying from now on waits two+ // minutes. Stop is pressed once one of them is in that wait.+ global.set(Some(32 << 10));+ let _ = tokio::time::timeout(std::time::Duration::ZERO, global.acquire(4 << 20)).await;+ let owed = global.taken();+ while global.taken() == owed {+ assert!(+ std::time::Instant::now() < deadline,+ "no connection paid again"+ );+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ // Measured from Stop: a stop that waited would take 2 minutes, a prompt one well under 10 s+ // however busy the machine (it still writes what arrived, and the resume state).dl.cancel();- let _ = dl.wait().await;- let secs = t.elapsed().as_secs_f64();- assert!(secs < 1.0, "stopping took {secs:.2}s");+ let stopped = tokio::time::timeout(std::time::Duration::from_secs(10), dl.wait())+ .await+ .expect("Stop waited out the speed limit");+ assert!(+ matches!(stopped, Err(mdm_engine::Error::Cancelled)),+ "{:?}",+ stopped.map(|o| o.size)+ );}#[tokio::test]diff --git a/crates/labserver/src/faults.rs b/crates/labserver/src/faults.rsindex 08b9a16b..582e4778 100644--- a/crates/labserver/src/faults.rs+++ b/crates/labserver/src/faults.rs@@ -43,6 +43,11 @@ pub struct Faults {/// Delay before answering a request that asks for a range, ms (on top of `latency_ms`): the/// probe's plain GET runs ahead of the range attempts, as on a busy machine.pub range_latency_ms: Option<u64>,+ /// Per-response speed cap for the answers to requests that ask for a range (instead of+ /// `rate`): a range attempt a server without ranges answers in full can't fill the sockets+ /// of a busy machine before the client drops it.+ #[serde(deserialize_with = "size_opt")]+ pub range_rate: Option<u64>,/// 403 unless the request's `Cookie` holds this pair (`sid=1`), or a cookie of this name/// (`sid`): a file behind a session.pub require_cookie: Option<String>,@@ -82,6 +87,7 @@ impl Faults {etag: over.etag.clone().or(self.etag.clone()),latency_ms: over.latency_ms.or(self.latency_ms),range_latency_ms: over.range_latency_ms.or(self.range_latency_ms),+ range_rate: over.range_rate.or(self.range_rate),require_cookie: over.require_cookie.clone().or(self.require_cookie.clone()),require_referer: over.require_refererdiff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rsindex 94037ff1..16d21d7f 100644--- a/crates/labserver/src/server.rs+++ b/crates/labserver/src/server.rs@@ -7,9 +7,10 @@//! for a form post that carries `FIELD=VALUE`//! - `GET /files/{name}` — a real file from `--files DIR` (Range too; 404 without it): archives//! for the link grabber's tests-//! - `GET /redirect?to=URL[&ttl_ms=N][&code=3xx]` — a redirect (302 unless `code` says) to `URL`-//! (cross-host redirects, credential scoping); with `ttl_ms` the target gets `expires=<unix ms>`-//! and answers 403 after it (signed CDN links)+//! - `GET /redirect?to=URL[&ttl_ms=N][&uses=N][&code=3xx]` — a redirect (302 unless `code` says)+//! to `URL` (cross-host redirects, credential scoping); with `ttl_ms` the target gets+//! `expires=<unix ms>` and answers 403 after it (signed CDN links); with `uses` it is a link of+//! its own that answers 403 after N requests (a link that expires however slow the machine)//! - `GET /hop?to=URL&how=meta|header[&wait=S][&cookie=N=V]` — a page that sends the browser on to//! `URL` itself (`<meta http-equiv="refresh">` or a `Refresh` header), as download sites' waiting pages do//! - `GET /page`, `/formpage`, `/cookie`, `/assets/*` — web pages for the browser tests (`pages`)@@ -183,6 +184,8 @@ pub(crate) struct Shared {seq: AtomicU64,/// One-time links already used (path and query).used_once: Mutex<HashSet<String>>,+ /// Requests each signed link with `uses` has served (path and query).+ link_uses: Mutex<HashMap<String, u64>>,conn_reqs: Mutex<HashMap<SocketAddr, u64>>,active: Mutex<HashMap<IpAddr, u32>>,log: Mutex<Vec<LogEntry>>,@@ -298,6 +301,7 @@ impl LabServer {requests: AtomicU64::new(0),seq: AtomicU64::new(0),used_once: Mutex::default(),+ link_uses: Mutex::default(),conn_reqs: Mutex::default(),active: Mutex::default(),log: Mutex::default(),@@ -457,10 +461,13 @@ GET|HEAD /gen/{size}[/{name}]?seed=N&<file params>&<faults> size: 12345, 64K,video/mp4, ...): a browser displays or plays itinline=bare the real Content-Type and no Content-Disposition at allexpires=UNIXMS 403 after that time (what /redirect?ttl_ms= adds)+ uses=N 403 once this path and query has served N requests (what /redirect?uses= adds,+ with a link= of its own)faults (also server-wide with --faults; per-URL values override):rate=SIZE slow_every=N slow_rate=SIZE max_conns=N drop_after=SIZE drop_every=Nfail_every=N fail_first=N no_range=1 no_range_every=N html=1 etag_change_every=Netag=weak|per-request|none latency_ms=N range_latency_ms=N (only requests with a Range)+ range_rate=SIZE the rate of answers to requests with a Range (instead of rate)stall_at=SIZE never send the file's byte at that offset: a response stops there and waits(until the server's faults change, from a test; a URL's own value stays)require_cookie=NAME=VALUE|NAME 403 unless the Cookie header has it@@ -473,7 +480,7 @@ POST /form/{size}[/{name}]?need=FIELD=VALUE&see_other=1&<as /gen>(default need=token=abc): 405 to other methods, 403 to a form without it;see_other=1: 303 to /gen/{size}/{name}?<the rest of the query> insteadGET /files/{name} a real file from --files DIR (Range too; 404 without --files)-GET /redirect?to=URL[&ttl_ms=N][&code=3xx] 302 (or code) to URL (not logged); ttl_ms: a signed link expiring after N ms+GET /redirect?to=URL[&ttl_ms=N][&uses=N][&code=3xx] 302 (or code) to URL (not logged); ttl_ms: a signed link expiring after N ms; uses: a new link each time, expiring after N requests/rd/rest/1.0/{user,hosts/domains,unrestrict/link,disable_access_token}, /rd/oauth/v2/{device/code,device/credentials,token}a fake Real-Debrid (#44): tokens good (premium), free; links http://hoster.test/file/SIZE/NAME[?gone=1&down=1&chunks=N&ttl_ms=N&rate=SIZE]/ad/v4/{user,hosts/domains,link/unlock,link/delayed,pin/check}, /ad/v4.1/pin/get a fake AllDebrid: the same tokens and links, plus delayed=N@@ -588,8 +595,9 @@ async fn log_simple(resp}-/// `/redirect?to=URL[&ttl_ms=N][&code=3xx]`: a redirect (302 unless `code` says) to `URL`; with-/// `ttl_ms`, to a signed link that expires.+/// `/redirect?to=URL[&ttl_ms=N][&uses=N][&code=3xx]`: a redirect (302 unless `code` says) to+/// `URL`; with `ttl_ms`, to a signed link that expires; with `uses`, to a link of its own that+/// expires after that many requests.async fn redirect(RawQuery(q): RawQuery) -> Response {let mut m = q.and_then(|q| serde_urlencoded::from_str::<HashMap<String, String>>(&q).ok())@@ -601,6 +609,12 @@ async fn redirect(RawQuery(q): RawQuery) -> Response {let sep = if to.contains('?') { '&' } else { '?' };to = format!("{to}{sep}expires={}", unix_ms() + ttl);}+ if let Some(uses) = m.get("uses").and_then(|n| n.parse::<u64>().ok()) {+ static LINKS: AtomicU64 = AtomicU64::new(0);+ let sep = if to.contains('?') { '&' } else { '?' };+ let link = LINKS.fetch_add(1, Ordering::Relaxed);+ to = format!("{to}{sep}uses={uses}&link={link}");+ }let code = m.get("code").and_then(|c| c.parse::<u16>().ok())@@ -886,6 +900,8 @@ struct FileQuery {seed: u64,/// A signed link's end, unix ms.expires: Option<u64>,+ /// The requests a signed link serves (`link` tells the links apart).+ uses: Option<u64>,cd: Option<String>,cdstar: Option<String>,disposition: Disposition,@@ -917,7 +933,14 @@ pub(crate) async fn serve(}};let seed = q.seed;- if q.expires.is_some_and(|t| unix_ms() > t) {+ let used_up = q.uses.is_some_and(|uses| {+ let key = format!("{}?{query}", entry.path);+ let mut served = shared.link_uses.lock().unwrap();+ let n = served.entry(key).or_insert(0);+ *n += 1;+ *n > uses+ });+ if used_up || q.expires.is_some_and(|t| unix_ms() > t) {shared.record(entry, 403, "expired");return (StatusCode::FORBIDDEN, "link expired\n").into_response();}@@ -1062,6 +1085,8 @@ pub(crate) async fn serve(let rate = if every(n, f.slow_every) {f.slow_rate.or(f.rate)+ } else if entry.range.is_some() {+ f.range_rate.or(f.rate)} else {f.rate};@@ -1166,6 +1191,7 @@ fn split_query(q: &str) -> Result<FileQuery, String> {let mut out = FileQuery {seed: 0,expires: None,+ uses: None,cd: None,cdstar: None,disposition: Disposition::Attachment,@@ -1185,6 +1211,8 @@ fn split_query(q: &str) -> Result<FileQuery, String> {"expires" => {out.expires = Some(v.parse().map_err(|_| format!("invalid expires `{v}`\n"))?)}+ "uses" => out.uses = Some(v.parse().map_err(|_| format!("invalid uses `{v}`\n"))?),+ "link" => {}"cd" => out.cd = name(&k, v)?,"cdstar" => out.cdstar = name(&k, v)?,"inline" => {