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 link from the browser: ask again as MDM when its User-Agent is refused (#372) (#437)
Ahmed Nefzaoui87074c69b553
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a8ec2238..7e959d04 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- A link sent from the browser no longer fails with 403 on sites whose bot check refuses a browser's User-Agent on a connection that isn't a browser's: MDM asks once more with its own, as Add URL does ([#372](https://github.com/anefzaoui/misterdownloadmanager/issues/372)).- The video download button moves to a free corner instead of covering a control of the page, such as a thumbnail's watch-later button ([#421](https://github.com/anefzaoui/misterdownloadmanager/issues/421)). Dragging it still puts it where you want it.- Crash reports: no report any more when one of the download engine's background tasks panics while MDM is already closing ([#422](https://github.com/anefzaoui/misterdownloadmanager/issues/422)).- Crash reports: a freeze whose window had recovered by the time its dump was taken is reported as a freeze, not as a crash in MDM's own watchdog ([#420](https://github.com/anefzaoui/misterdownloadmanager/issues/420)).diff --git a/ROADMAP.md b/ROADMAP.mdindex f7adc827..1b93fa5c 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,8 @@ Everything below ships together, in version 0.5.0.### Done+- ✅ A link from the browser no longer ends in 403 where a site's bot check refuses the browser's+ User-Agent: MDM asks once more as itself ([#372](https://github.com/anefzaoui/misterdownloadmanager/issues/372))- ✅ The video button no longer covers a control of the page (a preview's own button): it takesa free corner, and dragging it keeps it where you put it([#421](https://github.com/anefzaoui/misterdownloadmanager/issues/421))diff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 20a9eb32..6dee2d2e 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -2370,6 +2370,15 @@ impl App {None if ua.is_empty() => Options::default().user_agent,None => ua.to_owned(),},+ // The browser's User-Agent may be refused on this connection (#372): MDM's own+ // (Options' or the default) is tried once then, as Add URL would.+ agent_fallback: context.user_agent.is_some().then(|| {+ if ua.is_empty() {+ Options::default().user_agent+ } else {+ ua.to_owned()+ }+ }),post: context.post.clone().map(|body| body.into_bytes().into()),on_file_created: Some(mark_hook(url, context.referer.as_deref())),..Options::default()diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rsindex b3ce5e75..385be0f1 100644--- a/crates/engine/src/download.rs+++ b/crates/engine/src/download.rs@@ -81,6 +81,11 @@ pub struct Options {/// The first retry is immediate (as IDM, lab S5); then this delay, doubling, capped at 30 s.pub retry_delay: Duration,pub user_agent: String,+ /// Asked with instead of `user_agent` when the server refuses the first request with 403+ /// (#372): a browser's User-Agent on a connection that isn't a browser's trips some sites'+ /// bot checks (Cloudflare, seen on a public PDF), while MDM's own passes. Set when+ /// `user_agent` is the browser's. A later 403 is left to the download.+ pub agent_fallback: Option<String>,/// How often resume state is saved (IDM: "several times per minute").pub save_interval: Duration,/// Speed limit for this download, bytes/s (IDM's limiter is per file). None = unlimited.@@ -209,6 +214,7 @@ impl Default for Options {max_retries: 5,retry_delay: Duration::from_secs(1),user_agent: DEFAULT_USER_AGENT.to_owned(),+ agent_fallback: None,save_interval: Duration::from_secs(2),speed_limit: None,verify_overlap: 64,@@ -813,15 +819,35 @@ pub async fn probe_kept(};let seen = Arc::new(crate::server::ServerSeen::default());let client = client(opts, &target, &as_get, &seen)?;- let (resp, headers, took) = get(+ // A browser's User-Agent refused (#372): asked once more as MDM.+ let (client, asked) = match get(&client,- target,- headers,+ target.clone(),+ headers.clone(),opts.post.as_ref(),&opts.user_agent,&CancellationToken::new(),)- .await?;+ .await+ {+ Err(e) if agent_refused(&e) && opts.agent_fallback.is_some() => {+ let mut plain = opts.clone();+ plain.user_agent = opts.agent_fallback.clone().unwrap_or_default();+ let client = self::client(&plain, &target, &as_get, &seen)?;+ let asked = get(+ &client,+ target,+ headers,+ opts.post.as_ref(),+ &plain.user_agent,+ &CancellationToken::new(),+ )+ .await;+ (client, asked)+ }+ asked => (client, asked),+ };+ let (resp, headers, took) = asked?;seen.answered(&resp);let final_url = resp.url().clone();let (size, from_zero) = match resp.status() {@@ -1486,6 +1512,8 @@ async fn run_fresh(kept: Option<KeptAnswer>,) -> Result<Outcome, Error> {let mut opts = opts;+ // The first request had to give up the browser's User-Agent (#372).+ let mut asked_as_mdm = false;shared.limiter.set(opts.speed_limit);let (shared, cancel) = (&shared, &cancel);shared.conn(0, |_| {});@@ -1513,8 +1541,23 @@ async fn run_fresh(let as_get = AsGet::default();let seen = shared.seen.get_or_init(Default::default).clone();let client0 = client(&opts, &target, &as_get, &seen)?;- let (answer, ttfb) =- first_get(&client0, &target, &asked, &opts, shared, cancel).await?;+ let (client0, first) = match first_get(&client0, &target, &asked, &opts, shared, cancel)+ .await+ {+ Err(e) if agent_refused(&e) && opts.agent_fallback.is_some() => {+ // #372: the rest of the download goes as MDM too.+ opts.user_agent = opts.agent_fallback.take().unwrap_or_default();+ asked_as_mdm = true;+ shared.event(+ "The server refused the browser's User-Agent; asking as Mister Download Manager",+ );+ let client1 = client(&opts, &target, &as_get, &seen)?;+ let first = first_get(&client1, &target, &asked, &opts, shared, cancel).await;+ (client1, first)+ }+ first => (client0, first),+ };+ let (answer, ttfb) = first?;seen.answered(&answer.0);(as_get, client0, answer, ttfb)}@@ -1614,6 +1657,7 @@ async fn run_fresh(saved.content_type = content_type.clone();saved.checksum = checksum.clone();saved.final_get = opts.post.is_some() && post.is_none();+ saved.asked_as_mdm = asked_as_mdm;let ctx = Arc::new(Ctx {client: client0.clone(),validators: Mutex::new(validators),@@ -1860,6 +1904,12 @@ async fn run_resume(shared: Arc<Shared>,cancel: CancellationToken,) -> Result<Outcome, Error> {+ let mut opts = opts;+ if saved.asked_as_mdm+ && let Some(agent) = opts.agent_fallback.take()+ {+ opts.user_agent = agent;+ }shared.limiter.set(opts.speed_limit);let bad = |what: &str| Error::BadState(format!("{}: {what}", state_file.display()));if state_file != state_path(&saved.dest) {@@ -2290,6 +2340,12 @@ async fn save_state(Ok(())}+/// A plain 403, which a browser's User-Agent may have brought on (#372). A site's bot check+/// isn't asked again: that one stays the site's call (#376).+fn agent_refused(e: &Error) -> bool {+ matches!(e, Error::Status(s) if s.as_u16() == 403)+}+/// A plain `GET` (no Range), or a POST of `post`, that must answer 200 or 206. A GET follows/// the HTTP redirects (the client's policy) and then the redirects a page makes itself (#28):/// a download site's "your download starts in a moment" page, sent with a `Refresh` header or adiff --git a/crates/engine/src/state.rs b/crates/engine/src/state.rsindex 5eeb96d6..357782f6 100644--- a/crates/engine/src/state.rs+++ b/crates/engine/src/state.rs@@ -39,6 +39,10 @@ pub struct ResumeState {/// The hash the finished file must have (the user's or the server's), if known.#[serde(default)]pub checksum: Option<crate::verify::Hash>,+ /// The first run got past a refusal by asking with `Options::agent_fallback` instead of the+ /// browser's User-Agent (#372): a resume asks the same way.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub asked_as_mdm: bool,/// A POST download (`Options::post`, its body not stored) whose redirects turned it into/// a GET (301, 302, 303): `final_url` is asked with GET.#[serde(default, skip_serializing_if = "std::ops::Not::not")]@@ -58,6 +62,7 @@ impl ResumeState {segments: Vec::new(),content_type: None,checksum: None,+ asked_as_mdm: false,final_get: false,}}diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rsindex 082b7c7b..2267280b 100644--- a/crates/engine/tests/e2e.rs+++ b/crates/engine/tests/e2e.rs@@ -1593,3 +1593,61 @@ async fn a_slow_flush_does_not_stop_the_transfer() {// planner's closing splits only.assert!(log.len() < 48, "{} requests: {log:?}", log.len());}++/// #372: a server that refuses a browser's User-Agent with 403 (seen on a public+/// PDF) is asked once more with MDM's own, and the download goes on.+#[tokio::test]+async fn a_refused_browser_agent_is_asked_again_as_mdm() {+ let s = server("rate=20M&refuse_agent=Chrome").await;+ let browser = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 Chrome/156.0 Safari/537.36";+ let dir = tempfile::tempdir().unwrap();+ // Without the fallback, the 403 is the end of it.+ let refused = Download::start(+ Request {+ url: s.url("/gen/2M/a.bin?seed=372").parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ Options {+ user_agent: browser.to_owned(),+ ..fast_opts()+ },+ )+ .wait()+ .await;+ assert!(+ matches!(refused, Err(mdm_engine::Error::Status(s)) if s.as_u16() == 403),+ "{refused:?}"+ );+ // With it, the same download succeeds under MDM's agent, every connection.+ let out = Download::start(+ Request {+ url: s.url("/gen/2M/a.bin?seed=372").parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ Options {+ user_agent: browser.to_owned(),+ agent_fallback: Some("MDM-test".to_owned()),+ ..fast_opts()+ },+ )+ .wait()+ .await+ .expect("download succeeds after the fallback");+ assert_eq!(out.size, 2 << 20);+ tokio::time::timeout(SETTLE, s.settled())+ .await+ .expect("every request ends");+ let log = s.log();+ assert!(+ log.iter().any(|e| e.outcome.contains("refuse_agent")),+ "{log:?}"+ );+ assert!(+ log.iter()+ .filter(|e| e.status == 200 || e.status == 206)+ .all(|e| e.user_agent.as_deref() == Some("MDM-test")),+ "{log:?}"+ );+}diff --git a/crates/labserver/src/faults.rs b/crates/labserver/src/faults.rsindex 582e4778..3a715dbb 100644--- a/crates/labserver/src/faults.rs+++ b/crates/labserver/src/faults.rs@@ -53,6 +53,9 @@ pub struct Faults {pub require_cookie: Option<String>,/// 403 unless the request's `Referer` starts with this (hotlink protection).pub require_referer: Option<String>,+ /// 403 when the request's `User-Agent` contains this (a bot check that refuses a+ /// browser's User-Agent on a connection that isn't a browser's, #372).+ pub refuse_agent: Option<String>,/// A one-time link: the first request for this path and query is served, every later one/// (HEAD and ranges included) gets 410 Gone.#[serde(deserialize_with = "flag_opt")]@@ -89,6 +92,7 @@ impl Faults {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()),+ refuse_agent: over.refuse_agent.clone().or(self.refuse_agent.clone()),require_referer: over.require_referer.clone()diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rsindex bca7c891..dab1504e 100644--- a/crates/labserver/src/server.rs+++ b/crates/labserver/src/server.rs@@ -540,6 +540,7 @@ GET|HEAD /gen/{size}[/{name}]?seed=N&<file params>&<faults> size: 12345, 64K,(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 itrequire_referer=PREFIX 403 unless the Referer starts with PREFIX (%-encode ? & =)+ refuse_agent=TEXT 403 when the User-Agent contains TEXTonce=1 a one-time link: the first request for this path and query is served, everylater one (HEAD and ranges too) gets 410 Gone; vary seed= for a fresh link"every Nth" counts file requests (/gen and /form) only.@@ -1071,6 +1072,15 @@ pub(crate) async fn serve(shared.record(entry, 403, "fault:require_referer");return (StatusCode::FORBIDDEN, format!("referer {want}… required\n")).into_response();}+ if let Some(want) = &f.refuse_agent+ && entry+ .user_agent+ .as_deref()+ .is_some_and(|ua| ua.contains(want.as_str()))+ {+ shared.record(entry, 403, "fault:refuse_agent");+ return (StatusCode::FORBIDDEN, format!("agent {want} refused\n")).into_response();+ }if let Some(ms) = f.latency_ms {tokio::time::sleep(Duration::from_millis(ms)).await;}