Skip to content

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

A web page where a file was expected is an error, not the file (part of #533) (#549)

Ahmed Nefzaoui543adfb4b5d1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 692cb4bd..2a4c44b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
- The progress window of a video whose size isn't known says no percentage (it read 0 % in the title and 0.00 % on the Downloaded line), and **File size** stays the file's size at the end (it read 0.1 % too high while yt-dlp finished).
- A **gofile** share link (`gofile.io/d/...`) now says it is a web page to open in your browser, instead of saving that page as if it were the file ([#346](https://github.com/anefzaoui/misterdownloadmanager/issues/346)).
+- A download that gets a web page where a file was expected (a server's "The requested URL was rejected", a sign-in page) now stops with "the server sent a web page instead of the file" instead of saving that page under the file's name and calling it complete. MDM knows a file was expected from the type the browser had for it, or from a file's name (.doc, .pdf, .zip, .mp4...); a page the browser saved as one, a `.html` link, and a server's own name for what it sends are downloaded as before (part of [#533](https://github.com/anefzaoui/misterdownloadmanager/issues/533)).
- **Download video**: when a site's bot check (Cloudflare) turns yt-dlp away, the message says so and what to try, instead of yt-dlp's cut-off words ([#317](https://github.com/anefzaoui/misterdownloadmanager/issues/317)).
- The **Download video** window remembers the folder you save into, per **Options → Save to**'s "Change folder for this category on last selected", as **Download File Info** does: it no longer goes back to the Video category's folder each time ([#475](https://github.com/anefzaoui/misterdownloadmanager/issues/475)).
- X (Twitter) videos sent from the browser's media list are named after the tab, not the random name of their file on X's video server ([#493](https://github.com/anefzaoui/misterdownloadmanager/issues/493)).
diff --git a/ROADMAP.md b/ROADMAP.md
index eb0b8a76..9c5f5025 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -581,6 +581,9 @@ These ship in a later version, when they're ready.
([#374](https://github.com/anefzaoui/misterdownloadmanager/issues/374)): fix in review
- 🔄 A gofile share link saving a web page instead of the file
([#346](https://github.com/anefzaoui/misterdownloadmanager/issues/346)): fix in review
+- 🔄 A server's refusal page saved under the document's name and shown as complete, where the
+ browser had the file (part of [#533](https://github.com/anefzaoui/misterdownloadmanager/issues/533)):
+ fix in review
- 🔄 "Hide tab" in a download's window only going back to Download status, the tab still
there ([#326](https://github.com/anefzaoui/misterdownloadmanager/issues/326)): fix in review
- 🔍 A site's bot check refusing MDM's request (testfile.org, a Cloudflare challenge): the\n message now says so ([#376](https://github.com/anefzaoui/misterdownloadmanager/issues/376)); a way to hand the download back to the browser is still to decide
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 4f815999..63df73f5 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -2517,6 +2517,8 @@ impl App {
}),
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).
+ expected_type: context.mime.clone(),
..Options::default()
};
RequestParts { headers, opts }
diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rs
index ec9b586b..b1460cbf 100644
--- a/crates/engine/src/download.rs
+++ b/crates/engine/src/download.rs
@@ -142,6 +142,10 @@ pub struct Options {
/// name, so whatever the hook attaches to it — Windows' Mark of the Web stream, macOS'
/// quarantine attribute — stays with the finished file.
pub on_file_created: Option<FileHook>,
+ /// From the browser: the MIME type its own download had. A web page where it had another
+ /// type is the server refusing MDM (a firewall's "The requested URL was rejected"), an error
+ /// and never saved as the file (#533, `expects_other_file`).
+ pub expected_type: Option<String>,
/// Tests: a disk whose flush takes this long and holds every write to the file meanwhile
/// (as NTFS does, #361). None: the real disk.
#[doc(hidden)]
@@ -233,6 +237,7 @@ impl Default for Options {
extra_roots: Vec::new(),
post: None,
on_file_created: None,
+ expected_type: None,
slow_flush: None,
}
}
@@ -819,6 +824,7 @@ pub async fn probe_kept(
};
let seen = Arc::new(crate::server::ServerSeen::default());
let client = client(opts, &target, &as_get, &seen)?;
+ let expects = expects_other_file(opts.expected_type.as_deref(), None, &url);
// A browser's User-Agent refused (#372): asked once more as MDM.
let (client, asked) = match get(
&client,
@@ -826,6 +832,7 @@ pub async fn probe_kept(
headers.clone(),
opts.post.as_ref(),
&opts.user_agent,
+ expects,
&CancellationToken::new(),
)
.await
@@ -840,6 +847,7 @@ pub async fn probe_kept(
headers,
opts.post.as_ref(),
&plain.user_agent,
+ expects,
&CancellationToken::new(),
)
.await;
@@ -1524,7 +1532,18 @@ async fn run_fresh(
shared.conn(0, |_| {});
// Probe on connection 0: a plain GET (or the form's POST) whose body becomes the segment
// starting at 0; or the look's answer kept for it (#28), not asked for again.
- let kept = kept.filter(|k| k.url == req.url && k.at.elapsed() < KEEP_ANSWER_FOR);
+ // A web page where the download expects another kind of file is an error (#533): the look's
+ // answer, asked before the file's name was settled, is asked for again then (`get` says so).
+ let expects = expects_other_file(
+ opts.expected_type.as_deref(),
+ dest_name(&req.dest),
+ &req.url,
+ );
+ let kept = kept.filter(|k| {
+ k.url == req.url
+ && k.at.elapsed() < KEEP_ANSWER_FOR
+ && !(expects && is_web_page(k.resp.headers()) && !named(k.resp.headers()))
+ });
let mut unlocked = kept.as_ref().and_then(|k| k.unlocked.clone());
let (as_get, client0, (resp, headers), ttfb) = match kept {
Some(k) => {
@@ -1546,8 +1565,10 @@ 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, shared, cancel)
- .await
+ let (client0, first) = match first_get(
+ &client0, &target, &asked, &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.
@@ -1557,7 +1578,8 @@ async fn run_fresh(
"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;
+ let first =
+ first_get(&client1, &target, &asked, &opts, expects, shared, cancel).await;
(client1, first)
}
first => (client0, first),
@@ -1697,8 +1719,16 @@ async fn run_fresh(
*shared.planner.lock().unwrap() = None;
shared.view.lock().unwrap().resumable = Some(false);
let agent = &opts.user_agent;
- let (resp, ..) =
- get(&client0, final_url, headers, post.as_ref(), agent, cancel).await?;
+ let (resp, ..) = get(
+ &client0,
+ final_url,
+ headers,
+ post.as_ref(),
+ agent,
+ expects,
+ cancel,
+ )
+ .await?;
let body = Body::Http(resp);
single_stream(body, &file, shared, opts.global.as_deref(), cancel).await?
}
@@ -2088,7 +2118,9 @@ async fn refresh_final_url(
None => (origin.clone(), headers.clone()),
};
asked.insert(header::RANGE, HeaderValue::from_static("bytes=0-0"));
- let (resp, mut headers, _) = get(client, target, asked, post, agent, cancel).await.ok()?;
+ let (resp, mut headers, _) = get(client, target, asked, post, agent, false, cancel)
+ .await
+ .ok()?;
headers.remove(header::RANGE);
if resp.status() != StatusCode::PARTIAL_CONTENT {
return None;
@@ -2369,17 +2401,21 @@ fn agent_refused(e: &Error) -> bool {
/// A site whose links aren't the file's address (`sites`, #34: Google Drive) is asked its own
/// way: its link goes to the file's address first, its pages say where to go next or why it
/// refuses (`Error::Refused`), and a page of its where the file was expected is an error, never
-/// the file.
+/// the file. So is any web page when the download `expects` another kind of file (#533,
+/// `expects_other_file`): a server's refusal, a sign-in wall. A small answer without a type is
+/// looked into then, and asked for again if it isn't a page.
///
/// With the answer, `headers` as the download goes on with them at the address it ended at:
/// credentials scoped to it (`scoped_headers`), the pages' cookies added; and how long the last
/// request took to answer (a page's wait and its own request not counted: the time to first byte).
+#[allow(clippy::too_many_arguments)]
async fn get(
client: &Client,
url: Url,
headers: HeaderMap,
post: Option<&Bytes>,
agent: &str,
+ expects: bool,
cancel: &CancellationToken,
) -> Result<(Response, HeaderMap, Duration), Error> {
let (mut url, mut headers) = (url, headers);
@@ -2453,8 +2489,16 @@ async fn get(
let site_page = post.is_none()
&& resp.status() == StatusCode::OK
&& is_web_page(resp.headers())
- && !resp.headers().contains_key(header::CONTENT_DISPOSITION)
- && sites::expects_file(&from);
+ && !named(resp.headers())
+ && (sites::expects_file(&from) || expects);
+ // No type said where another kind of file is expected (#533): small, it is looked into.
+ let untyped = post.is_none()
+ && expects
+ && hops < MAX_PAGE_REDIRECTS
+ && resp.status() == StatusCode::OK
+ && !resp.headers().contains_key(header::CONTENT_TYPE)
+ && !named(resp.headers())
+ && resp.content_length().is_none_or(|n| n <= PAGE_PEEK as u64);
// A form is never posted again, and a page's own redirects end somewhere.
if post.is_some() || resp.status() != StatusCode::OK || hops >= MAX_PAGE_REDIRECTS {
if site_page {
@@ -2474,11 +2518,19 @@ async fn get(
next
} else if let Some(next) = site_link {
(Duration::ZERO, next)
- } else if is_web_page(resp.headers())
+ } else if (is_web_page(resp.headers()) || untyped)
// A web page small enough to look into (larger ones aren't waiting pages).
&& resp.content_length().is_none_or(|n| n <= PAGE_PEEK as u64)
{
let page = read_up_to(resp, PAGE_PEEK, cancel).await?;
+ // Without a type and not a page: the file, asked for again as is.
+ let site_page = site_page || (untyped && sniffs_as_html(&page));
+ if untyped && !site_page {
+ add_cookies(&mut headers, &cookies);
+ url = from;
+ hops = MAX_PAGE_REDIRECTS;
+ continue;
+ }
match sites::read_page(&from, &page) {
PageSays::Next(next) => (Duration::ZERO, next),
PageSays::Refused(r) => match sites::second_look(&from).filter(|_| !looked) {
@@ -2637,6 +2689,7 @@ async fn first_get(
url: &Url,
headers: &HeaderMap,
opts: &Options,
+ expects: bool,
shared: &Shared,
cancel: &CancellationToken,
) -> Result<((Response, HeaderMap), Duration), Error> {
@@ -2647,6 +2700,7 @@ async fn first_get(
headers.clone(),
opts.post.as_ref(),
&opts.user_agent,
+ expects,
cancel,
)
})
@@ -3074,6 +3128,136 @@ fn is_web_page_type(content_type: &str) -> bool {
mime.eq_ignore_ascii_case("text/html") || mime.eq_ignore_ascii_case("application/xhtml+xml")
}
+/// The server names what it sends (`Content-Disposition`): its own file, page or not.
+fn named(h: &HeaderMap) -> bool {
+ h.contains_key(header::CONTENT_DISPOSITION)
+}
+
+/// Where a download is saved under a name of its own (the browser's, the user's), that name.
+fn dest_name(dest: &Destination) -> Option<&str> {
+ match dest {
+ Destination::File(p) => p.file_name().and_then(|n| n.to_str()),
+ Destination::Dir(_) => None,
+ }
+}
+
+/// Types of file a web page never is, by extension: documents, archives, programs, disk images,
+/// audio, video and pictures. A name without one of these (a page's `.php`, no extension at all)
+/// says nothing.
+const FILE_EXTENSIONS: &[&str] = &[
+ "doc",
+ "docx",
+ "docm",
+ "dot",
+ "dotx",
+ "xls",
+ "xlsx",
+ "xlsm",
+ "xlsb",
+ "ppt",
+ "pptx",
+ "pps",
+ "ppsx",
+ "odt",
+ "ods",
+ "odp",
+ "rtf",
+ "pdf",
+ "epub",
+ "mobi",
+ "djvu",
+ "zip",
+ "rar",
+ "7z",
+ "gz",
+ "tgz",
+ "bz2",
+ "xz",
+ "zst",
+ "tar",
+ "cab",
+ "arj",
+ "lz",
+ "lzh",
+ "exe",
+ "msi",
+ "msix",
+ "msixbundle",
+ "appx",
+ "apk",
+ "deb",
+ "rpm",
+ "appimage",
+ "dmg",
+ "pkg",
+ "jar",
+ "iso",
+ "img",
+ "vhd",
+ "vhdx",
+ "mp3",
+ "m4a",
+ "aac",
+ "flac",
+ "wav",
+ "wma",
+ "ogg",
+ "opus",
+ "mp4",
+ "m4v",
+ "mkv",
+ "avi",
+ "mov",
+ "wmv",
+ "flv",
+ "webm",
+ "mpg",
+ "mpeg",
+ "jpg",
+ "jpeg",
+ "png",
+ "gif",
+ "bmp",
+ "webp",
+ "tif",
+ "tiff",
+ "psd",
+ "torrent",
+];
+
+/// The download expects a kind of file a web page isn't (#533): the browser's own download had
+/// another type (`expected_type`), or its name (`name`, else the address's) is a file's. A web
+/// page in its place, without a name of the server's, is an error (`Error::GotWebPage`). A page
+/// the browser saved as one (`text/html`), a `.html` link, or a server's own type for the file
+/// (`application/octet-stream`) are downloads like any other.
+fn expects_other_file(expected_type: Option<&str>, name: Option<&str>, url: &Url) -> bool {
+ if let Some(t) = expected_type.map(str::trim).filter(|t| !t.is_empty()) {
+ return !is_web_page_type(t);
+ }
+ let name = name.map_or_else(|| naming::file_name(None, url), str::to_owned);
+ Path::new(&name)
+ .extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| FILE_EXTENSIONS.iter().any(|x| e.eq_ignore_ascii_case(x)))
+}
+
+/// Bytes that start as an HTML document (after a byte order mark and white space).
+fn sniffs_as_html(body: &[u8]) -> bool {
+ let body = body.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(body);
+ let start = body
+ .iter()
+ .position(|b| !b.is_ascii_whitespace())
+ .unwrap_or(body.len());
+ let head: Vec<u8> = body[start..]
+ .iter()
+ .take(16)
+ .map(u8::to_ascii_lowercase)
+ .collect();
+ ["<!doctype html", "<html", "<head", "<body", "<title"]
+ .iter()
+ .any(|t| head.starts_with(t.as_bytes()))
+}
+
/// Whether the download is itself a web page (it was served as one, or is named like one).
fn expects_web_page(dest: &Path, content_type: Option<&str>) -> bool {
content_type.is_some_and(is_web_page_type)
diff --git a/crates/engine/tests/web_page.rs b/crates/engine/tests/web_page.rs
new file mode 100644
index 00000000..0fd5091d
--- /dev/null
+++ b/crates/engine/tests/web_page.rs
@@ -0,0 +1,164 @@
+//! #533: a web page (a firewall's "The requested URL was rejected") where the download expects
+//! another kind of file is an error, never saved as the file; real pages and files still are.
+
+use mdm_engine::{Destination, Download, Error, Options, Request};
+use mdm_labserver::{Config, LabServer, content};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+async fn server() -> LabServer {
+ LabServer::start(Config::default()).await.unwrap()
+}
+
+/// Downloads `url` to `dest` (a name in a fresh folder, or the folder itself), with the
+/// browser's type `mime`; the file saved (its bytes) or the error, and what the folder holds.
+async fn get(
+ url: &str,
+ name: Option<&str>,
+ mime: Option<&str>,
+) -> (Result<Vec<u8>, Error>, Vec<String>) {
+ let dir = tempfile::tempdir().unwrap();
+ let dest = match name {
+ Some(n) => Destination::File(dir.path().join(n)),
+ None => Destination::Dir(dir.path().to_owned()),
+ };
+ let req = Request {
+ url: url.parse().unwrap(),
+ headers: Default::default(),
+ dest,
+ };
+ let opts = Options {
+ expected_type: mime.map(str::to_owned),
+ retry_delay: std::time::Duration::from_millis(50),
+ ..Options::default()
+ };
+ let out = Download::start(req, opts)
+ .wait()
+ .await
+ .map(|o| std::fs::read(o.path).unwrap());
+ let mut files: Vec<String> = std::fs::read_dir(dir.path())
+ .unwrap()
+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
+ .collect();
+ files.sort();
+ (out, files)
+}
+
+fn refused(out: &Result<Vec<u8>, Error>) -> bool {
+ matches!(out, Err(Error::GotWebPage))
+}
+
+#[tokio::test]
+async fn a_page_saved_as_a_document_is_an_error() {
+ let s = server().await;
+ // The reporter's case: the browser named it x.doc, the server sent its refusal page.
+ let (out, files) = get(&s.url("/gen/245/x.doc?html=1"), Some("x.doc"), None).await;
+ assert!(refused(&out), "{:?}", out.map(|b| b.len()));
+ assert!(
+ files.iter().all(|f| !f.starts_with("x.doc")),
+ "nothing saved: {files:?}"
+ );
+}
+
+#[tokio::test]
+async fn a_page_where_the_browser_had_another_type_is_an_error() {
+ let s = server().await;
+ // An address without a file's name (OWA's attachment.ashx), the browser's own type.
+ let url = s.url("/gen/245/attachment.ashx?html=1");
+ let (out, files) = get(&url, None, Some("application/msword")).await;
+ assert!(refused(&out), "{:?}", out.map(|b| b.len()));
+ assert!(files.is_empty(), "nothing saved: {files:?}");
+ // The file's information window says so too, before anything is saved.
+ let opts = Options {
+ expected_type: Some("application/msword".into()),
+ ..Options::default()
+ };
+ let probed = mdm_engine::probe_kept(url.parse().unwrap(), Default::default(), &opts).await;
+ assert!(matches!(probed, Err(Error::GotWebPage)), "{probed:?}");
+ // An address named like a file, added by hand (no browser): the same.
+ let (out, _) = get(&s.url("/gen/245/report.pdf?html=1"), None, None).await;
+ assert!(refused(&out), "{:?}", out.map(|b| b.len()));
+}
+
+#[tokio::test]
+async fn pages_and_files_are_still_saved() {
+ let s = server().await;
+ // A page that is one: a .html link, a page the browser saved as one, a name saying nothing.
+ for (url, name, mime) in [
+ ("/gen/245/page.html?html=1", Some("page.html"), None),
+ ("/gen/245/x.doc?html=1", Some("x.doc"), Some("text/html")),
+ ("/gen/245/view.php?html=1", None, None),
+ ("/gen/245/download?html=1", None, None),
+ ] {
+ let (out, files) = get(&s.url(url), name, mime).await;
+ assert!(out.is_ok(), "{url}: {:?}", out.err());
+ assert_eq!(files.len(), 1, "{url}: {files:?}");
+ }
+ // A document sent as application/octet-stream (the lab's type for .doc), and as its own.
+ for (url, name, mime) in [
+ (
+ "/gen/64K/x.doc?seed=5",
+ Some("x.doc"),
+ Some("application/msword"),
+ ),
+ ("/gen/64K/x.pdf?seed=5&inline=bare", Some("x.pdf"), None),
+ ] {
+ let (out, _) = get(&s.url(url), name, mime).await;
+ let out = out.unwrap_or_else(|e| panic!("{url}: {e}"));
+ let mut want = vec![0; 64 << 10];
+ content::fill(5, 0, &mut want);
+ assert!(out == want, "{url}");
+ }
+ // A server's own name for what it sends (Content-Disposition) is taken at its word.
+ let named =
+ "Content-Type: text/html\r\nContent-Disposition: attachment; filename=\"x.doc\"\r\n";
+ let (base, _) = answers(named, b"<html>a document, as its server calls it</html>").await;
+ let (out, _) = get(&format!("{base}/x.doc"), Some("x.doc"), None).await;
+ assert!(out.is_ok(), "{:?}", out.err());
+}
+
+/// A server that answers every request with `body` and the header lines `head` (each ending in
+/// CRLF; none: no Content-Type); how many requests it got.
+async fn answers(
+ head: &'static str,
+ body: &'static [u8],
+) -> (String, std::sync::Arc<std::sync::atomic::AtomicU32>) {
+ use std::sync::atomic::{AtomicU32, Ordering};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let asked = std::sync::Arc::new(AtomicU32::new(0));
+ let count = asked.clone();
+ tokio::spawn(async move {
+ while let Ok((mut sock, _)) = listener.accept().await {
+ count.fetch_add(1, Ordering::SeqCst);
+ tokio::spawn(async move {
+ let mut buf = vec![0; 4096];
+ let _ = sock.read(&mut buf).await;
+ let head = format!(
+ "HTTP/1.1 200 OK\r\n{head}Content-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = sock.write_all(head.as_bytes()).await;
+ let _ = sock.write_all(body).await;
+ let _ = sock.shutdown().await;
+ });
+ }
+ });
+ (format!("http://{addr}"), asked)
+}
+
+#[tokio::test]
+async fn an_untyped_answer_is_looked_into() {
+ let page: &[u8] =
+ b"\r\n<!DOCTYPE html><html><body>The requested URL was rejected.</body></html>";
+ let (base, _) = answers("", page).await;
+ let (out, files) = get(&format!("{base}/x.doc"), Some("x.doc"), None).await;
+ assert!(refused(&out), "{:?}", out.map(|b| b.len()));
+ assert!(files.is_empty(), "nothing saved: {files:?}");
+ // A file without a type is the file (asked for again once it has been looked into).
+ let file: &[u8] = b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1 a document";
+ let (base, asked) = answers("", file).await;
+ let (out, _) = get(&format!("{base}/x.doc"), Some("x.doc"), None).await;
+ let out = out.unwrap_or_else(|e| panic!("{e}"));
+ assert_eq!(out, file);
+ assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 2);
+}