Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

A link refused before any byte goes on where the browser's download ended (#630) (#642)

Ahmed Nefzaoui0198cc4f74e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb11a362..dda525cb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- A download handed over by the browser whose link the site refuses to MDM before sending anything (FileHippo's links answered **412 Precondition Failed**; a one-time link the browser has already used, or one tied to its session, answers 403, 404 or 410) goes on from the address the browser's own download of it had reached, once; if that is refused too, the link's own answer is the error shown. Its cookies go there only when it is the same site ([#630](https://github.com/anefzaoui/misterdownloadmanager/issues/630)).
- Raising a speed limit, or turning it off, applies at once: to a download's own limit (its progress window's **Speed Limiter** tab), the limit for one file and the limit for all downloads together. A connection already waiting its turn under the old limit sat out the wait the old limit gave it, many seconds at a low limit, before the new speed showed; it now counts what is left at the new limit, and ends its wait as soon as there is no limit ([#621](https://github.com/anefzaoui/misterdownloadmanager/issues/621)).
- **Download video**: a sound-only choice (MP3, Opus, FLAC, the original sound) saves in the Music category's folder and is listed under Music, as a playlist downloaded as sound only does; choosing a video again goes back to the Video folder. A folder you typed or picked in **Save to** stays as it is ([#611](https://github.com/anefzaoui/misterdownloadmanager/issues/611)).
- **Options → Save to**: changing the **General** category's default download directory now moves the default folders of all other categories without their own folder (`Video`, `Music`, `Torrents`, etc.) under it, instead of leaving them under the system's `Downloads` folder ([#556](https://github.com/anefzaoui/misterdownloadmanager/issues/556)). **Add torrent** also starts with the **Torrents** category's folder from the moment it opens (so **Save to** no longer flips when a magnet link's metadata arrives) and remembers a changed folder when **Change folder for this category on last selected** is ticked ([#550](https://github.com/anefzaoui/misterdownloadmanager/issues/550)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 78245448..d46b22f8 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -561,6 +561,10 @@ These ship in a later version, when they're ready.
### Bugs being looked into
+- 🔄 Downloads from FileHippo failing at once with 412 Precondition Failed
+ ([#630](https://github.com/anefzaoui/misterdownloadmanager/issues/630)): a link the site refuses
+ to MDM now goes on from where the browser's own download of it had reached; fix in review, still
+ to check on FileHippo itself. A link pasted into Add URL has no such address to go on from
- 🔄 Windows: a crash when the clipboard was read in two places at once (the clipboard monitor and
Add URL) ([#629](https://github.com/anefzaoui/misterdownloadmanager/issues/629)): every read and
write of the clipboard now goes one at a time; fix in review
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index bc95792c..ed12b610 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -2545,6 +2545,13 @@ impl App {
ua.to_owned()
}
}),
+ // Where the browser's own download of it ended: asked when the link itself is
+ // refused (#630, a one-time or session-bound token the browser already used).
+ browser_final: context
+ .final_url
+ .as_deref()
+ .and_then(|u| url::Url::parse(u).ok())
+ .filter(|f| f != url && mdm_engine::supported(f)),
post: context.post.clone().map(|body| body.into_bytes().into()),
on_file_created: Some(mark_hook(url, context.referer.as_deref())),
// The browser's own download's type: a web page instead is an error (#533).
@@ -3349,6 +3356,8 @@ impl App {
saved.final_url = url.clone();
let _ = saved.write(&state);
}
+ // Where the browser's download of the old address ended isn't this one's (#630).
+ item.context.final_url = None;
item.note(crate::i18n::fmt(
crate::i18n::t("Address changed to {host}"),
&[("host", &crate::i18n::ltr(url.host_str().unwrap_or("?")))],
diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rs
index 2a5a6e50..bcd67224 100644
--- a/crates/app/src/dialogs.rs
+++ b/crates/app/src/dialogs.rs
@@ -1045,6 +1045,7 @@ impl FileInfo {
self.context.post = None;
self.context.post_type = None;
self.request.opts.post = None;
+ self.request.opts.browser_final = None;
self.request.headers.remove(reqwest::header::CONTENT_TYPE);
// Another address isn't the download the browser had started: it goes through
// the debrid account that takes its host (#44), unless the user unticked it.
diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rs
index b1460cbf..67c7bc70 100644
--- a/crates/engine/src/download.rs
+++ b/crates/engine/src/download.rs
@@ -86,6 +86,13 @@ pub struct Options {
/// 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>,
+ /// From the browser: the address its own download of this file ended at, its redirects
+ /// followed. When the address asked for is refused before any byte (`link_refused`: a
+ /// one-time link the browser already spent, a token bound to its session, a site that
+ /// turns away whatever isn't that browser), the download asks there once instead (#630),
+ /// the address's cookies and logins going only if it is the same site (`scoped_headers`).
+ /// Never for a form's POST (its body goes where it was given) or through a service account.
+ pub browser_final: Option<Url>,
/// 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.
@@ -219,6 +226,7 @@ impl Default for Options {
retry_delay: Duration::from_secs(1),
user_agent: DEFAULT_USER_AGENT.to_owned(),
agent_fallback: None,
+ browser_final: None,
save_interval: Duration::from_secs(2),
speed_limit: None,
verify_overlap: 64,
@@ -1564,26 +1572,44 @@ 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 (client0, first) = match first_get(
- &client0, &target, &asked, &opts, expects, shared, cancel,
- )
- .await
+ let as_given = opts.clone();
+ let ask = FirstAsk {
+ as_get: &as_get,
+ seen: &seen,
+ expects,
+ shared,
+ cancel,
+ };
+ let (mut client0, mut first, as_mdm) = ask.at(&mut opts, &target, &asked).await?;
+ asked_as_mdm = as_mdm;
+ // #630: the link refused, where the browser's own download of it ended is asked
+ // once, as the link was (the browser's User-Agent first). The link's refusal is
+ // the one told if that fails too.
+ if let Err(e) = &first
+ && link_refused(e)
+ && unlocked.is_none()
+ && opts.post.is_none()
+ && let Some(other) = opts.browser_final.clone().filter(|o| *o != target)
{
- 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, expects, shared, cancel).await;
- (client1, first)
+ shared.event(format!(
+ "{}: {e}; asking where the browser's download ended ({})",
+ target.host_str().unwrap_or("?"),
+ other.host_str().unwrap_or("?"),
+ ));
+ let mut again = as_given;
+ let headers = scoped_headers(&asked, &target, &other);
+ match ask.at(&mut again, &other, &headers).await {
+ Ok((client1, Ok(answer), as_mdm)) => {
+ (opts, client0, first, asked_as_mdm) = (again, client1, Ok(answer), as_mdm);
+ }
+ Ok((_, Err(Error::Cancelled), _)) | Err(Error::Cancelled) => {
+ return Err(Error::Cancelled);
+ }
+ Ok((_, Err(e), _)) | Err(e) => {
+ shared.event(format!("{}: {e}", other.host_str().unwrap_or("?")));
+ }
}
- first => (client0, first),
- };
+ }
let (answer, ttfb) = first?;
seen.answered(&answer.0);
(as_get, client0, answer, ttfb)
@@ -2385,6 +2411,57 @@ fn forced_gap(force: bool, took: Duration) -> Duration {
if force { Duration::ZERO } else { took }
}
+/// A refusal of the address asked for that the browser's own download got past (#630): 401
+/// and 403 (a token bound to the browser's session), 404 and 410 (a one-time link the browser
+/// already spent, which some servers then forget, others call gone), 412 (FileHippo's answer
+/// to whatever isn't a browser). A site's bot check stays the site's call (#376).
+fn link_refused(e: &Error) -> bool {
+ matches!(e, Error::Status(s) if matches!(s.as_u16(), 401 | 403 | 404 | 410 | 412))
+}
+
+/// What a download's first request needs besides its address, headers and options.
+struct FirstAsk<'a> {
+ as_get: &'a AsGet,
+ seen: &'a Arc<crate::server::ServerSeen>,
+ expects: bool,
+ shared: &'a Shared,
+ cancel: &'a CancellationToken,
+}
+
+/// A first request's client, its answer (or why not) and whether it went as MDM (#372).
+type FirstAnswer = (
+ Client,
+ Result<((Response, HeaderMap), Duration), Error>,
+ bool,
+);
+
+impl FirstAsk<'_> {
+ /// `first_get` at `url` with its client; asked once more as MDM when the browser's
+ /// User-Agent is refused (#372, `opts` then goes on as MDM: the third value says so).
+ async fn at(
+ &self,
+ opts: &mut Options,
+ url: &Url,
+ headers: &HeaderMap,
+ ) -> Result<FirstAnswer, Error> {
+ let (shared, cancel, expects) = (self.shared, self.cancel, self.expects);
+ let client0 = client(opts, url, self.as_get, self.seen)?;
+ match first_get(&client0, url, headers, opts, expects, 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();
+ shared.event(
+ "The server refused the browser's User-Agent; asking as Mister Download Manager",
+ );
+ let client1 = client(opts, url, self.as_get, self.seen)?;
+ let first = first_get(&client1, url, headers, opts, expects, shared, cancel).await;
+ Ok((client1, first, true))
+ }
+ first => Ok((client0, first, false)),
+ }
+ }
+}
+
/// 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 {
diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs
index c3b3b400..79b0d117 100644
--- a/crates/engine/tests/e2e.rs
+++ b/crates/engine/tests/e2e.rs
@@ -1805,3 +1805,114 @@ async fn a_refused_browser_agent_is_asked_again_as_mdm() {
"{log:?}"
);
}
+
+/// A download handed over by the browser: `link` with a session cookie and the page as Referer,
+/// and where the browser's own download of it ended (`browser_final`).
+async fn handed_over(
+ link: String,
+ browser_final: Option<&str>,
+ dir: &std::path::Path,
+) -> Result<mdm_engine::Outcome, mdm_engine::Error> {
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert(reqwest::header::COOKIE, "sid=1".parse().unwrap());
+ headers.insert(
+ reqwest::header::REFERER,
+ "http://127.0.0.1/program/".parse().unwrap(),
+ );
+ Download::start(
+ Request {
+ url: link.parse().unwrap(),
+ headers,
+ dest: Destination::Dir(dir.to_owned()),
+ },
+ Options {
+ browser_final: browser_final.map(|u| u.parse().unwrap()),
+ ..fast_opts()
+ },
+ )
+ .wait()
+ .await
+}
+
+/// #630: a site that refuses MDM the link (FileHippo's 412) while the browser's own download of
+/// it ended on another host (its CDN): the download goes on from there, without the link's
+/// cookie (another host) but with the page as Referer.
+#[tokio::test]
+async fn a_refused_link_goes_on_where_the_browser_download_ended() {
+ let s = server("rate=20M").await;
+ let port = s.addr().port();
+ let link = s.url("/gen/2M/fh.bin?seed=630&refuse=412");
+ let cdn = format!("http://localhost:{port}/gen/2M/fh.bin?seed=630");
+ let dir = tempfile::tempdir().unwrap();
+ // Without the browser's address, the 412 is the end of it (what 0.5.2 did).
+ let refused = handed_over(link.clone(), None, dir.path()).await;
+ assert!(
+ matches!(refused, Err(mdm_engine::Error::Status(s)) if s.as_u16() == 412),
+ "{refused:?}"
+ );
+ let out = handed_over(link, Some(&cdn), dir.path())
+ .await
+ .expect("the download goes on where the browser's ended");
+ let mut want = vec![0; 2 << 20];
+ content::fill(630, 0, &mut want);
+ assert!(
+ std::fs::read(&out.path).unwrap() == want,
+ "content mismatch"
+ );
+ assert_eq!(out.path.file_name().unwrap(), "fh.bin");
+ tokio::time::timeout(SETTLE, s.settled())
+ .await
+ .expect("every request ends");
+ let log = s.log();
+ assert_eq!(
+ log.iter().filter(|e| e.outcome == "fault:refuse").count(),
+ 2,
+ "the link was asked once per download: {log:?}"
+ );
+ let served: Vec<_> = log
+ .iter()
+ .filter(|e| e.status == 200 || e.status == 206)
+ .collect();
+ assert!(!served.is_empty());
+ for e in served {
+ assert!(
+ e.host
+ .as_deref()
+ .is_some_and(|h| h.starts_with("localhost")),
+ "{e:?}"
+ );
+ assert_eq!(e.cookie, None, "the link's cookie reached another host");
+ assert_eq!(e.referer.as_deref(), Some("http://127.0.0.1/program/"));
+ }
+}
+
+/// #630: a one-time link the browser already spent (410) is followed on the same site, where
+/// the session's cookie still goes; when the browser's address is refused too, the link's own
+/// refusal is the one told.
+#[tokio::test]
+async fn a_spent_link_goes_on_where_the_browser_download_ended() {
+ let s = server("rate=20M").await;
+ let link = s.url("/gen/1M/once.bin?seed=631&once=1");
+ // The browser's own download used it up.
+ let spent = reqwest::get(&link).await.unwrap();
+ assert_eq!(spent.status(), 200);
+ drop(spent.bytes().await);
+ let dir = tempfile::tempdir().unwrap();
+ let final_url = s.url("/gen/1M/once.bin?seed=631&require_cookie=sid=1");
+ let out = handed_over(link.clone(), Some(&final_url), dir.path())
+ .await
+ .expect("the download goes on where the browser's ended");
+ let mut want = vec![0; 1 << 20];
+ content::fill(631, 0, &mut want);
+ assert!(
+ std::fs::read(&out.path).unwrap() == want,
+ "content mismatch"
+ );
+ // Both refused: the link's 410 is told, not the other address's 403.
+ let gone = s.url("/gen/1M/once.bin?seed=631&refuse=403");
+ let refused = handed_over(link, Some(&gone), dir.path()).await;
+ assert!(
+ matches!(refused, Err(mdm_engine::Error::Status(s)) if s.as_u16() == 410),
+ "{refused:?}"
+ );
+}
diff --git a/crates/labserver/src/faults.rs b/crates/labserver/src/faults.rs
index 3a715dbb..7ae016af 100644
--- a/crates/labserver/src/faults.rs
+++ b/crates/labserver/src/faults.rs
@@ -56,6 +56,10 @@ pub struct Faults {
/// 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>,
+ /// Every file request answered with this status (4xx or 5xx) before any byte: a site that
+ /// turns away whatever isn't a browser (FileHippo's 412, #630), or a link the browser
+ /// already spent.
+ pub refuse: Option<u16>,
/// 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")]
@@ -93,6 +97,7 @@ impl Faults {
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()),
+ refuse: over.refuse.or(self.refuse),
require_referer: over
.require_referer
.clone()
diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rs
index dab1504e..5d662f24 100644
--- a/crates/labserver/src/server.rs
+++ b/crates/labserver/src/server.rs
@@ -541,6 +541,8 @@ GET|HEAD /gen/{size}[/{name}]?seed=N&<file params>&<faults> size: 12345, 64K,
require_cookie=NAME=VALUE|NAME 403 unless the Cookie header has it
require_referer=PREFIX 403 unless the Referer starts with PREFIX (%-encode ? & =)
refuse_agent=TEXT 403 when the User-Agent contains TEXT
+ refuse=STATUS every request answered with that 4xx or 5xx status, before any byte (a site
+ that turns away whatever isn't a browser: FileHippo's 412, #630)
once=1 a one-time link: the first request for this path and query is served, every
later one (HEAD and ranges too) gets 410 Gone; vary seed= for a fresh link
"every Nth" counts file requests (/gen and /form) only.
@@ -1081,6 +1083,14 @@ pub(crate) async fn serve(
shared.record(entry, 403, "fault:refuse_agent");
return (StatusCode::FORBIDDEN, format!("agent {want} refused\n")).into_response();
}
+ if let Some(status) = f
+ .refuse
+ .and_then(|c| StatusCode::from_u16(c).ok())
+ .filter(|s| s.is_client_error() || s.is_server_error())
+ {
+ shared.record(entry, status.as_u16(), "fault:refuse");
+ return status.into_response();
+ }
if let Some(ms) = f.latency_ms {
tokio::time::sleep(Duration::from_millis(ms)).await;
}
diff --git a/docs/browser-integration.md b/docs/browser-integration.md
index 3a02769f..9fd28e55 100644
--- a/docs/browser-integration.md
+++ b/docs/browser-integration.md
@@ -2,7 +2,7 @@
[← Back to docs index](README.md)
-With the MDM extension, clicking a download link in your browser hands the download to MDM. MDM gets the address together with the page it came from (the referrer), your cookies for the site and the browser's User-Agent, so downloads that need you to be signed in still work.
+With the MDM extension, clicking a download link in your browser hands the download to MDM. MDM gets the address together with the page it came from (the referrer), your cookies for the site and the browser's User-Agent, so downloads that need you to be signed in still work. It also gets the address the browser's own download had reached: when a site refuses MDM the link itself (a one-time link the browser has already used, or a site that lets only browsers ask for its links), MDM goes on from there once, without your cookies if it is another site.
The extension works in **Google Chrome**, **Microsoft Edge**, **Brave**, **Opera** and **Vivaldi**, in **Firefox** 140 or later, and in **Safari** 17 or later on a Mac (see [Safari](#safari-macos)).