Skip to content

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

Long-token addresses no longer fail; every kind of redirect followed (#28) (#30)

Ahmed Nefzaouia6323f95aa29
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d787a708..b4620119 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -79,9 +79,22 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
- Files downloaded from the web are marked as downloaded from the internet, as the browser marks
its own: Windows' Mark of the Web (SmartScreen, Office's Protected View), macOS' quarantine.
- Downloads from a private window are kept out of the saved list.
+- **MDM follows every kind of redirect a browser does** ([#28](https://github.com/anefzaoui/misterdownloadmanager/issues/28)):
+ any HTTP redirect (301, 302, 303, 307, 308), up to 20 in a row instead of 10, and the pages
+ download sites put in between ("your download starts in a moment"), which lead on with a
+ `Refresh` header or a `<meta http-equiv="refresh">`: their wait is kept (up to 10 seconds), and
+ the cookies they set go along while the download runs (not into a resume later). A page that
+ leads on only through its own script still stops there.
### Fixed
+- A download whose address ends in a long token (file hosts such as AnkerGames' mirrors) failed
+ with "the path is too long for Windows" before it started
+ ([#28](https://github.com/anefzaoui/misterdownloadmanager/issues/28)). Every new download's name
+ is now shortened to fit its folder (keeping the extension), and when nobody named the file
+ (no name from the browser, no answer to the look-up, not edited), it gets the name the server
+ gives, as in a browser: `Call-of-Duty-Infinite-Warfare-AnkerGames.zip` rather than the
+ address's token.
- Bangla shows Bangladesh's flag instead of India's, in the language picker, on the website and
in the README ([#27](https://github.com/anefzaoui/misterdownloadmanager/issues/27)).
- MDM closed with an internal error when a window opened while the main window was minimized
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 20a86ada..1fefcf99 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -169,10 +169,15 @@ fn move_file(from: &std::path::Path, to: &std::path::Path) -> Result<(), String>
})
}
-/// A download's new place (its name from it).
+/// A download's new place (its name from it). A name the user gave is no longer the address's
+/// guess (`Item::name_from_url`); another folder alone keeps the server's say.
fn take_place(item: &mut Item, target: PathBuf) {
if let Some(name) = target.file_name() {
- item.file_name = name.to_string_lossy().into_owned();
+ let name = name.to_string_lossy().into_owned();
+ if name != item.file_name {
+ item.name_from_url = false;
+ }
+ item.file_name = name;
}
item.dest = target;
}
@@ -988,6 +993,7 @@ impl App {
crate::i18n::mark("with Add URL")
},
);
+ self.name_guessed(id, fi.name_guessed());
self.selection.set(id);
if matches!(start, Start::Now) {
self.start(id, true);
@@ -1169,6 +1175,14 @@ impl App {
id
}
+ /// Download `id`'s name is only its address's guess (`guessed`): the server names it when
+ /// it starts (`Item::name_from_url`).
+ fn name_guessed(&mut self, id: u64, guessed: bool) {
+ if guessed && let Some(item) = self.item(id) {
+ item.name_from_url = true;
+ }
+ }
+
/// `/show <window>` (mdm_ipc::Command::show): open one of the windows by name, as its menu
/// command does. Unknown names do nothing.
fn show_named(&mut self, name: &str, ctx: &egui::Context) {
@@ -1315,6 +1329,7 @@ impl App {
// Options → Downloads → "Show start download dialog" off: start (or only queue) at once.
let skip_dialog = !self.settings.show_start_dialog;
if cmd.later || cmd.silent || skip_dialog {
+ let guessed = cmd.name.is_none();
let name = cmd
.name
.clone()
@@ -1326,7 +1341,7 @@ impl App {
.clone()
.map(PathBuf::from)
.unwrap_or_else(|| self.settings.category_dir(category, &self.downloads));
- let dest = mdm_engine::naming::unique_path(&dir, &name);
+ let dest = mdm_engine::naming::destination(&dir, &name);
let later = cmd.later || (skip_dialog && self.settings.only_add_to_queue);
let source = if cmd.referer.is_some() || cmd.cookies.is_some() {
crate::i18n::mark("from the browser")
@@ -1335,6 +1350,7 @@ impl App {
};
let size = cmd.size;
let id = self.push_item(url, dest, category, String::new(), size, None, cmd, source);
+ self.name_guessed(id, guessed);
if later {
self.queues[0].items.push(id);
} else {
@@ -1462,11 +1478,17 @@ impl App {
if item.dest.parent().is_none_or(std::path::Path::is_dir) {
item.downloaded = 0;
}
+ // A name nobody gave (the address's guess) is the server's to give: into the folder,
+ // under its Content-Disposition name (#28); the row follows the file made.
+ let dest = match item.dest.parent() {
+ Some(dir) if item.name_from_url => Destination::Dir(dir.to_owned()),
+ _ => Destination::File(item.dest.clone()),
+ };
Download::start(
Request {
url: item.url.clone(),
headers,
- dest: Destination::File(item.dest.clone()),
+ dest,
},
opts,
)
@@ -1796,7 +1818,7 @@ impl App {
let move_to = c
.move_to
.filter(|dir| item.dest.parent() != Some(dir.as_path()))
- .map(|dir| mdm_engine::naming::unique_path(&dir, &item.file_name));
+ .map(|dir| mdm_engine::naming::destination(&dir, &item.file_name));
self.dirty = true;
if let Some(target) = move_to {
self.start_move(c.id, target);
@@ -1902,7 +1924,7 @@ impl App {
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "video".into());
- let dest = mdm_engine::naming::unique_path(&folder, &name);
+ let dest = mdm_engine::naming::destination(&folder, &name);
let id = self.push_item(
add.page,
dest,
@@ -2112,7 +2134,7 @@ impl App {
let name = mdm_engine::naming::file_name(None, &url);
let category = Category::of(&name);
let dir = self.settings.category_dir(category, &self.downloads);
- let dest = mdm_engine::naming::unique_path(&dir, &name);
+ let dest = mdm_engine::naming::destination(&dir, &name);
let id = self.push_item(
url,
dest,
@@ -2123,6 +2145,7 @@ impl App {
Default::default(),
crate::i18n::mark("by batch download"),
);
+ self.name_guessed(id, true);
ids.push(id);
}
self.queue_later(ids, self.settings.queue_panel_batch);
@@ -4522,7 +4545,7 @@ impl App {
let name = mdm_engine::naming::sanitize(&mdm_engine::naming::file_name(None, &url));
let category = Category::of(&name);
let dir = self.settings.category_dir(category, &self.downloads);
- let dest = mdm_engine::naming::unique_path(&dir, &name);
+ let dest = mdm_engine::naming::destination(&dir, &name);
let context = ipc::Command {
referer: d.referer,
cookies: d.cookies,
@@ -4540,6 +4563,7 @@ impl App {
context,
crate::i18n::mark("by import"),
);
+ self.name_guessed(id, true);
self.queues[0].items.push(id);
}
self.dirty = true;
@@ -5328,6 +5352,7 @@ impl App {
}
}
for (url, login, context) in unseen {
+ let guessed = context.name.is_none();
let name = context
.name
.clone()
@@ -5335,7 +5360,7 @@ impl App {
let name = mdm_engine::naming::sanitize(&name);
let category = Category::of(&name);
let dir = self.settings.category_dir(category, &self.downloads);
- let dest = mdm_engine::naming::unique_path(&dir, &name);
+ let dest = mdm_engine::naming::destination(&dir, &name);
let size = context.size;
let id = self.push_item(
url,
@@ -5347,6 +5372,7 @@ impl App {
context,
crate::i18n::mark("from the browser"),
);
+ self.name_guessed(id, guessed);
self.queues[0].items.push(id);
}
// The channel's receiver goes with it: later commands are answered "gone".
diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rs
index 75499384..58d205ed 100644
--- a/crates/app/src/dialogs.rs
+++ b/crates/app/src/dialogs.rs
@@ -542,7 +542,7 @@ impl FileInfo {
.unwrap_or_else(|| mdm_engine::naming::file_name(None, &new.url));
let category = Category::of(&name);
let folder = crate::model::category_folder(category, &downloads, &dirs);
- let save_as = display_path(&mdm_engine::naming::unique_path(&folder, &name));
+ let save_as = display_path(&mdm_engine::naming::destination(&folder, &name));
let (probe, info) = match from_browser {
Some(file_name) => (
Arc::new(Mutex::new(None)),
@@ -600,7 +600,7 @@ impl FileInfo {
self.category = Category::of(&name);
let dir =
crate::model::category_folder(self.category, &self.downloads, &self.dirs);
- self.save_as = display_path(&dir.join(&name));
+ self.save_as = display_path(&mdm_engine::naming::destination(&dir, &name));
}
// Another address: the browser's name, size and form are not its own, and on
// another site neither are its cookies and page (never sent there).
@@ -631,7 +631,8 @@ impl FileInfo {
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
- self.save_as = display_path(&folder.join(name));
+ // Fitted to the new folder too (#28): a deeper one leaves a long name less room.
+ self.save_as = display_path(&mdm_engine::naming::destination(folder, &name));
self.edited = true;
}
@@ -652,6 +653,12 @@ impl FileInfo {
matches!(self.info, Some(Ok(_)))
}
+ /// The name in Save As is only the address's guess: not edited, and no answer (the
+ /// browser's, the look-up's) gave one. The server names the file when it starts (#28).
+ pub fn name_guessed(&self) -> bool {
+ !self.edited && !self.probed()
+ }
+
pub fn size(&self) -> Option<u64> {
self.info
.as_ref()
@@ -670,8 +677,8 @@ impl FileInfo {
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
- self.save_as =
- display_path(&crate::model::category_folder(c, &self.downloads, &self.dirs).join(name));
+ let folder = crate::model::category_folder(c, &self.downloads, &self.dirs);
+ self.save_as = display_path(&mdm_engine::naming::destination(&folder, &name));
}
/// The dialog; Start (or Download Later) waits for a missing folder to be created.
@@ -700,7 +707,7 @@ impl FileInfo {
if let (Ok(pi), false) = (&res, self.edited) {
self.category = Category::of(&pi.file_name);
let dir = crate::model::category_folder(self.category, &self.downloads, &self.dirs);
- self.save_as = display_path(&mdm_engine::naming::unique_path(&dir, &pi.file_name));
+ self.save_as = display_path(&mdm_engine::naming::destination(&dir, &pi.file_name));
}
self.info = Some(res);
}
diff --git a/crates/app/src/model.rs b/crates/app/src/model.rs
index cb629d5b..655411ab 100644
--- a/crates/app/src/model.rs
+++ b/crates/app/src/model.rs
@@ -264,6 +264,11 @@ pub struct Item {
/// The event log: (unix seconds, what happened), oldest first, the last `LOG` entries.
#[serde(default)]
pub log: Vec<(i64, String)>,
+ /// `file_name` is only the address's guess (nobody named it: no browser, no answer, no
+ /// user): the download starts into its folder, under the name the server gives (its
+ /// Content-Disposition), as a browser does (#28). Cleared once the file is made.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub name_from_url: bool,
#[serde(skip)]
pub live: Option<Live>,
/// The engine's last view of this download (segments, connections).
@@ -455,6 +460,7 @@ impl Item {
video: None,
torrent: None,
log: Vec::new(),
+ name_from_url: false,
live: None,
snap: None,
login: None,
@@ -470,13 +476,21 @@ impl Item {
self.downloaded = s.downloaded;
self.size = s.size.or(self.size);
self.resumable = s.resumable.or(self.resumable);
- if let Some(f) = &s.file
- && *f != self.dest
- {
- // The file as saved (a video's real extension, a numbered duplicate).
- self.dest = f.clone();
- if let Some(name) = f.file_name() {
- self.file_name = name.to_string_lossy().into_owned();
+ if let Some(f) = &s.file {
+ // Named now: a later start from scratch keeps this name.
+ let guessed = std::mem::take(&mut self.name_from_url);
+ if *f != self.dest {
+ // The file as saved (a video's real extension, a numbered duplicate, the name
+ // the server gave).
+ self.dest = f.clone();
+ if let Some(name) = f.file_name() {
+ self.file_name = name.to_string_lossy().into_owned();
+ }
+ // The guess's category was the address's: the real name's now (the file stays
+ // in the folder it was started in).
+ if guessed {
+ self.category = Category::of(&self.file_name);
+ }
}
}
let dt = live.sample.0.elapsed().as_secs_f64();
diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rs
index b2d96488..ae37f231 100644
--- a/crates/engine/src/download.rs
+++ b/crates/engine/src/download.rs
@@ -496,7 +496,7 @@ impl AsGet {
self.0.lock().unwrap().contains(url)
}
- /// reqwest's own policy (at most 10 redirects), noting the method each hop leaves with.
+ /// Following up to `MAX_REDIRECTS`, noting the method each hop leaves with.
fn policy(&self) -> reqwest::redirect::Policy {
let seen = self.0.clone();
reqwest::redirect::Policy::custom(move |attempt| {
@@ -510,11 +510,15 @@ impl AsGet {
seen.remove(attempt.url());
}
drop(seen);
- reqwest::redirect::Policy::default().redirect(attempt)
+ reqwest::redirect::Policy::limited(MAX_REDIRECTS).redirect(attempt)
})
}
}
+/// Most HTTP redirects (301, 302, 303, 307, 308) a request follows, as browsers do (20; reqwest
+/// stops at 10): download links often go through a tracker, a mirror picker and a CDN.
+const MAX_REDIRECTS: usize = 20;
+
/// The body a POST download sends to an address reached with or without a redirect to a GET
/// (`as_get`); for a GET, the body's headers go too, as browsers drop them. None: a GET.
fn post_for(opts: &Options, as_get: bool, headers: &mut HeaderMap) -> Option<Bytes> {
@@ -638,8 +642,9 @@ pub struct ProbeInfo {
pub file_name: String,
}
-/// One plain `GET` (or `Options::post`'s POST) to learn the final URL, size and name; the body
-/// is not read.
+/// One plain `GET` (or `Options::post`'s POST) to learn the final URL, size and name, through
+/// the redirects `get` follows (a waiting page's look reads up to `PAGE_PEEK` of it and keeps its
+/// wait); the file's own body is not read.
pub async fn probe(url: Url, headers: HeaderMap, opts: &Options) -> Result<ProbeInfo, Error> {
if crate::ftp::is_ftp(&url) {
let site = crate::ftp::Site::new(&url, &headers, opts)?;
@@ -650,7 +655,7 @@ pub async fn probe(url: Url, headers: HeaderMap, opts: &Options) -> Result<Probe
size: facts.size,
});
}
- let resp = get(
+ let (resp, ..) = get(
&client(opts, &url, &AsGet::default())?,
url,
headers,
@@ -1086,7 +1091,7 @@ fn client(opts: &Options, url: &Url, as_get: &AsGet) -> Result<Client, Error> {
};
let builder = match opts.post {
Some(_) => builder.redirect(as_get.policy()),
- None => builder,
+ None => builder.redirect(reqwest::redirect::Policy::limited(MAX_REDIRECTS)),
};
Ok(builder
.dns_resolver(Arc::new(dns::Resolver::new(&opts.hosts, port)))
@@ -1138,7 +1143,8 @@ async fn run_fresh(
let as_get = AsGet::default();
let client0 = client(&opts, &req.url, &as_get)?;
shared.conn(0, |_| {});
- let (resp, ttfb) = first_get(&client0, &req.url, &req.headers, &opts, shared, cancel).await?;
+ let ((resp, headers), ttfb) =
+ first_get(&client0, &req.url, &req.headers, &opts, shared, cancel).await?;
let preempt_after = (ttfb * PREEMPT_TTFB).max(PREEMPT_MIN);
let size = match resp.status() {
StatusCode::OK => resp.content_length(),
@@ -1166,8 +1172,9 @@ async fn run_fresh(
resp.status(),
size.map_or("unknown".to_owned(), disk::human),
));
- // Credentials stay with the host they were given for (see `scoped_headers`).
- let mut headers = scoped_headers(&req.headers, &req.url, &final_url);
+ // Credentials stay with the host they were given for, with the cookies pages set on the way
+ // (`get`).
+ let mut headers = headers;
// A POST stays one if its redirects kept it (307, 308); it is sent again only once the
// server has answered a range (206): `Accept-Ranges` alone isn't proof, and a form may do
// something each time it is posted (an export, an order).
@@ -1253,7 +1260,7 @@ async fn run_fresh(
Err(Error::NoRanges) => {
*shared.planner.lock().unwrap() = None;
shared.view.lock().unwrap().resumable = Some(false);
- let resp = get(&client0, final_url, headers, post.as_ref(), cancel).await?;
+ let (resp, ..) = get(&client0, final_url, headers, post.as_ref(), cancel).await?;
let body = Body::Http(resp);
single_stream(body, &file, shared, opts.global.as_deref(), cancel).await?
}
@@ -1804,28 +1811,228 @@ async fn save_state(
Ok(())
}
-/// A plain `GET` (no Range), or a POST of `post`, that must answer 200 or 206.
+/// 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 a
+/// `<meta http-equiv="refresh">`, leads on to the file as it does in a browser (`refresh_target`,
+/// `meta_refresh`). Its wait, up to `PAGE_WAIT`, is kept, and the cookies it sets go on to its
+/// own host. A page that leads on only with a script isn't followed: it stays the answer.
+///
+/// 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).
async fn get(
client: &Client,
url: Url,
headers: HeaderMap,
post: Option<&Bytes>,
cancel: &CancellationToken,
-) -> Result<Response, Error> {
- let req = build(client, url, post).headers(headers);
- let resp = cancellable(cancel, async { Ok(req.send().await?) }).await?;
- match resp.status() {
- StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok(resp),
- s if s == StatusCode::TOO_MANY_REQUESTS || s == StatusCode::SERVICE_UNAVAILABLE => {
- Err(Error::Throttled(s, retry_after(resp.headers())))
+) -> Result<(Response, HeaderMap, Duration), Error> {
+ let (mut url, mut headers) = (url, headers);
+ // After a page's redirect, a page read but leading nowhere is asked for again, as is.
+ let mut hops = 0;
+ loop {
+ let req = build(client, url.clone(), post).headers(headers.clone());
+ let asked = std::time::Instant::now();
+ let resp = cancellable(cancel, async { Ok(req.send().await?) }).await?;
+ let took = asked.elapsed();
+ match resp.status() {
+ StatusCode::OK | StatusCode::PARTIAL_CONTENT => {}
+ s if s == StatusCode::TOO_MANY_REQUESTS || s == StatusCode::SERVICE_UNAVAILABLE => {
+ return Err(Error::Throttled(s, retry_after(resp.headers())));
+ }
+ s => return Err(Error::Status(s)),
+ }
+ // Where the HTTP redirects ended: the headers' credentials follow as reqwest's did.
+ let from = resp.url().clone();
+ headers = scoped_headers(&headers, &url, &from);
+ // 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 {
+ return Ok((resp, headers, took));
+ }
+ let cookies = set_cookies(resp.headers());
+ let (wait, next) = match header_text(resp.headers(), header::REFRESH)
+ .and_then(|v| refresh_target(&v, &from))
+ {
+ Some(next) => next,
+ // A web page small enough to look into (larger ones aren't waiting pages).
+ None if is_web_page(resp.headers())
+ && resp.content_length().is_none_or(|n| n <= PAGE_PEEK as u64) =>
+ {
+ let page = read_up_to(resp, PAGE_PEEK, cancel).await?;
+ match meta_refresh(&page, &from) {
+ Some(next) => next,
+ // Just a page: asked for again, as its body went into looking.
+ None => {
+ add_cookies(&mut headers, &cookies);
+ url = from;
+ hops = MAX_PAGE_REDIRECTS;
+ continue;
+ }
+ }
+ }
+ None => return Ok((resp, headers, took)),
+ };
+ if !wait.is_zero() {
+ cancellable(cancel, async {
+ tokio::time::sleep(wait.min(PAGE_WAIT)).await;
+ Ok(())
+ })
+ .await?;
+ }
+ headers = scoped_headers(&headers, &from, &next);
+ // Its own host's, and never from https down to http (as the user's own cookies).
+ if next.host_str() == from.host_str()
+ && !(from.scheme() == "https" && next.scheme() != "https")
+ {
+ add_cookies(&mut headers, &cookies);
+ }
+ url = next;
+ hops += 1;
+ }
+}
+
+/// Most redirects in a row that pages make themselves (`get`).
+const MAX_PAGE_REDIRECTS: usize = 5;
+/// How much of a web page is read to find its redirect.
+const PAGE_PEEK: usize = 256 << 10;
+/// The longest wait a page asks for before it leads on that is kept.
+const PAGE_WAIT: Duration = Duration::from_secs(10);
+
+/// The first `max` bytes of `resp`'s body (all of it when shorter).
+async fn read_up_to(
+ mut resp: Response,
+ max: usize,
+ cancel: &CancellationToken,
+) -> Result<Vec<u8>, Error> {
+ let mut body = Vec::new();
+ while body.len() < max {
+ let chunk = cancellable(cancel, async { Ok(resp.chunk().await?) }).await?;
+ let Some(chunk) = chunk else { break };
+ body.extend_from_slice(&chunk);
+ }
+ body.truncate(max);
+ Ok(body)
+}
+
+/// Where a page leads on to and after how long, from its `Refresh` value or a meta refresh's
+/// `content` (`5; url=next.html`, `0;URL='https://…'`, `3, https://…`), relative to `base`.
+/// None unless it leads to another http(s) address: a page that only reloads itself is the
+/// answer.
+fn refresh_target(value: &str, base: &Url) -> Option<(Duration, Url)> {
+ let (delay, rest) = value.split_once([';', ','])?;
+ let delay = delay
+ .trim()
+ .parse::<f64>()
+ .ok()
+ .filter(|d| d.is_finite() && *d >= 0.0)?;
+ let rest = rest.trim();
+ // `url=` is optional; the address may be quoted.
+ let target = match rest.get(..3) {
+ Some(u) if u.eq_ignore_ascii_case("url") && rest[3..].trim_start().starts_with('=') => {
+ rest[3..].trim_start()[1..].trim()
+ }
+ _ => rest,
+ };
+ let target = target
+ .strip_prefix(['"', '\''])
+ .map_or(target, |t| t.trim_end_matches(['"', '\'']))
+ .replace("&amp;", "&");
+ let next = base.join(target.trim()).ok()?;
+ let mut same = next.clone();
+ same.set_fragment(base.fragment());
+ (matches!(next.scheme(), "http" | "https") && same != *base).then(|| {
+ (
+ Duration::from_secs_f64(delay.min(PAGE_WAIT.as_secs_f64())),
+ next,
+ )
+ })
+}
+
+/// The redirect a page's `<meta http-equiv="refresh" content="…">` makes (`refresh_target`).
+fn meta_refresh(page: &[u8], base: &Url) -> Option<(Duration, Url)> {
+ let page = String::from_utf8_lossy(page);
+ let lower = page.to_ascii_lowercase();
+ let mut at = 0;
+ while let Some(i) = lower[at..].find("<meta") {
+ let start = at + i;
+ let end = lower[start..].find('>').map_or(lower.len(), |e| start + e);
+ let tag = &page[start..end];
+ if attribute(tag, "http-equiv").is_some_and(|v| v.trim().eq_ignore_ascii_case("refresh"))
+ && let Some(next) = attribute(tag, "content").and_then(|c| refresh_target(&c, base))
+ {
+ return Some(next);
}
- s => Err(Error::Status(s)),
+ at = end;
+ }
+ None
+}
+
+/// The value of attribute `name` in the HTML tag `tag` (quoted or not), as written.
+fn attribute(tag: &str, name: &str) -> Option<String> {
+ let lower = tag.to_ascii_lowercase();
+ let mut from = 0;
+ while let Some(i) = lower[from..].find(name) {
+ let at = from + i;
+ from = at + name.len();
+ // A whole attribute name, followed by `=`.
+ let before = lower[..at].chars().next_back();
+ if before.is_some_and(|c| !c.is_whitespace() && c != '<') {
+ continue;
+ }
+ let rest = tag[from..].trim_start();
+ let Some(rest) = rest.strip_prefix('=') else {
+ continue;
+ };
+ let rest = rest.trim_start();
+ return Some(match rest.chars().next() {
+ Some(q @ ('"' | '\'')) => rest[1..].split(q).next().unwrap_or_default().to_owned(),
+ _ => rest
+ .split(|c: char| c.is_whitespace() || c == '>')
+ .next()
+ .unwrap_or_default()
+ .to_owned(),
+ });
+ }
+ None
+}
+
+/// The `name=value` pairs a response's `Set-Cookie` headers set.
+fn set_cookies(h: &HeaderMap) -> Vec<String> {
+ h.get_all(header::SET_COOKIE)
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .filter_map(|v| v.split(';').next())
+ .map(str::trim)
+ .filter(|c| c.contains('='))
+ .map(str::to_owned)
+ .collect()
+}
+
+/// `cookies` added to the request's `Cookie` header, each replacing one of the same name.
+fn add_cookies(headers: &mut HeaderMap, cookies: &[String]) {
+ if cookies.is_empty() {
+ return;
+ }
+ let name = |c: &str| c.split('=').next().unwrap_or_default().trim().to_owned();
+ let new: HashSet<String> = cookies.iter().map(|c| name(c)).collect();
+ let mut all: Vec<String> = header_str(headers, header::COOKIE)
+ .unwrap_or_default()
+ .split(';')
+ .map(str::trim)
+ .filter(|c| !c.is_empty() && !new.contains(&name(c)))
+ .map(str::to_owned)
+ .collect();
+ all.extend(cookies.iter().cloned());
+ if let Ok(v) = HeaderValue::from_str(&all.join("; ")) {
+ headers.insert(header::COOKIE, v);
}
}
/// The first request of a download, retried as a connection is (`retry_wait`) when it fails
/// in a way a later try may not: a server busy at the moment the download starts no longer
-/// fails the whole download. With the answer, how long the try that got it waited for it.
+/// fails the whole download. With the answer (and the headers to go on with, `get`), how long its
+/// last request waited for it: a waiting page's delay isn't the server's time to first byte.
async fn first_get(
client: &Client,
url: &Url,
@@ -1833,8 +2040,8 @@ async fn first_get(
opts: &Options,
shared: &Shared,
cancel: &CancellationToken,
-) -> Result<(Response, Duration), Error> {
- first_try(opts, shared, cancel, || {
+) -> Result<((Response, HeaderMap), Duration), Error> {
+ let ((resp, headers, took), _) = first_try(opts, shared, cancel, || {
get(
client,
url.clone(),
@@ -1843,7 +2050,8 @@ async fn first_get(
cancel,
)
})
- .await
+ .await?;
+ Ok(((resp, headers), took))
}
/// `attempt` retried as `first_get` does; with its result, how long the try that got it took.
@@ -2542,6 +2750,68 @@ async fn cancellable<T>(
mod tests {
use super::*;
+ #[test]
+ fn pages_lead_on_as_browsers_read_them() {
+ let base = Url::parse("https://site.test/download/abc").unwrap();
+ let at = |v: &str| refresh_target(v, &base).map(|(d, u)| (d.as_secs(), u.to_string()));
+ assert_eq!(
+ at("0; url=https://cdn.test/f.zip"),
+ Some((0, "https://cdn.test/f.zip".into()))
+ );
+ assert_eq!(
+ at("5;URL='/get/f.zip'"),
+ Some((5, "https://site.test/get/f.zip".into()))
+ );
+ assert_eq!(
+ at("3, next?a=1&amp;b=2"),
+ Some((3, "https://site.test/download/next?a=1&b=2".into()))
+ );
+ // The wait is capped; a page that reloads itself, or leads off the web, is the answer.
+ assert_eq!(at("600; url=/x").map(|a| a.0), Some(PAGE_WAIT.as_secs()));
+ assert_eq!(at("30"), None);
+ assert_eq!(at("0; url=abc#top"), None);
+ assert_eq!(at("0; url=javascript:alert(1)"), None);
+ assert_eq!(at("soon; url=/x"), None);
+
+ let page = |html: &str| meta_refresh(html.as_bytes(), &base).map(|(_, u)| u.to_string());
+ assert_eq!(
+ page(r#"<html><META HTTP-EQUIV="Refresh" CONTENT="0;URL=/file.zip"></html>"#),
+ Some("https://site.test/file.zip".into())
+ );
+ assert_eq!(
+ page("<meta content='2; url=https://cdn.test/a.bin' http-equiv=refresh>"),
+ Some("https://cdn.test/a.bin".into())
+ );
+ // Other meta tags, and attribute names inside others, don't count.
+ assert_eq!(
+ page(
+ r#"<meta name="description" content="0; url=/x"><meta data-http-equiv="refresh" content="0; url=/y">"#
+ ),
+ None
+ );
+ assert_eq!(page("<p>window.location = '/x'</p>"), None);
+ }
+
+ #[test]
+ fn a_pages_cookies_go_on_with_it() {
+ let mut h = HeaderMap::new();
+ h.insert(header::COOKIE, HeaderValue::from_static("a=1; session=old"));
+ let mut set = HeaderMap::new();
+ set.append(
+ header::SET_COOKIE,
+ HeaderValue::from_static("session=new; Path=/; HttpOnly"),
+ );
+ set.append(
+ header::SET_COOKIE,
+ HeaderValue::from_static("xsrf=t; Secure"),
+ );
+ add_cookies(&mut h, &set_cookies(&set));
+ assert_eq!(
+ header_str(&h, header::COOKIE),
+ Some("a=1; session=new; xsrf=t")
+ );
+ }
+
#[test]
fn flush_step_scales_with_the_file() {
assert_eq!(sync_bytes(24 << 20), 3 << 19);
diff --git a/crates/engine/src/naming.rs b/crates/engine/src/naming.rs
index a638a22e..9b59b66d 100644
--- a/crates/engine/src/naming.rs
+++ b/crates/engine/src/naming.rs
@@ -229,6 +229,15 @@ pub fn fit_name(dir: &Path, name: &str) -> Option<String> {
(room >= MIN_NAME).then(|| clamp_to(name, room.min(MAX_NAME)))
}
+/// Where a new download named `name` goes in `dir`: the name shortened to fit the path limit
+/// (`fit_name`, keeping the extension), then numbered if taken (`unique_path`). A folder too
+/// deep for any name keeps it whole, and the download says the path is too long. A name from a
+/// long address (a token hundreds of characters long, #28) no longer fails the download.
+pub fn destination(dir: &Path, name: &str) -> PathBuf {
+ let name = fit_name(dir, name).unwrap_or_else(|| name.to_owned());
+ unique_path(dir, &name)
+}
+
fn clamp(name: &str) -> String {
clamp_to(name, MAX_NAME)
}
@@ -325,6 +334,19 @@ mod tests {
);
}
+ /// #28: a file host's address ends in a token of hundreds of characters; the download's
+ /// path still fits Windows' limit, extension kept.
+ #[test]
+ fn a_token_named_download_fits_its_folder() {
+ let dir = PathBuf::from(r"C:\Users\someone\Downloads");
+ let token = format!("ag1.{}", "eyJhcyI6MTMzMTY5LCJjIjoiQU41WUMybVpz".repeat(12));
+ let dest = destination(&dir, &sanitize(&token));
+ assert!(path_fits(&dest), "{}", dest.display());
+ assert_eq!(dest.parent(), Some(dir.as_path()));
+ let named = destination(&dir, &format!("{}.zip", "x".repeat(300)));
+ assert!(path_fits(&named) && named.extension().is_some_and(|e| e == "zip"));
+ }
+
#[cfg(windows)]
#[test]
fn a_folder_too_deep_for_any_name_is_refused() {
diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs
index f1355eb1..88326512 100644
--- a/crates/engine/tests/e2e.rs
+++ b/crates/engine/tests/e2e.rs
@@ -668,6 +668,66 @@ fn redirect_path(target: &str) -> String {
format!("/redirect?to={enc}")
}
+/// Every kind of redirect in one chain (#28): 301, 307, a page with a meta refresh (and a wait),
+/// 308, then a page with a `Refresh` header that sets a cookie, and the file; named by its own
+/// address, its wait kept, the cookie on every connection.
+#[tokio::test]
+async fn every_kind_of_redirect_is_followed() {
+ let s = server("").await;
+ let enc = |u: &str| url::form_urlencoded::byte_serialize(u.as_bytes()).collect::<String>();
+ let file = s.url("/gen/8M/the-real-name.bin?seed=31");
+ let header_page = s.url(&format!(
+ "/hop?how=header&cookie={}&to={}",
+ enc("step=2"),
+ enc(&file)
+ ));
+ let to_header_page = s.url(&format!("/redirect?code=308&to={}", enc(&header_page)));
+ let meta_page = s.url(&format!("/hop?how=meta&wait=1&to={}", enc(&to_header_page)));
+ let to_meta_page = s.url(&format!("/redirect?code=307&to={}", enc(&meta_page)));
+ let start = format!("/redirect?code=301&to={}", enc(&to_meta_page));
+
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: s.url(&start).parse().unwrap(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let started = std::time::Instant::now();
+ let out = Download::start(req, fast_opts()).wait().await.unwrap();
+ // The meta page's 1-second wait was kept.
+ assert!(started.elapsed() >= std::time::Duration::from_secs(1));
+ assert_eq!(out.path.file_name().unwrap(), "the-real-name.bin");
+ let mut want = vec![0; 8 << 20];
+ content::fill(31, 0, &mut want);
+ assert!(
+ std::fs::read(&out.path).unwrap() == want,
+ "content mismatch"
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ let log = s.log();
+ // Several connections fetched the file, every one with the page's cookie.
+ assert!(log.len() > 1, "one connection only: {}", log.len());
+ assert!(
+ log.iter().all(|e| e.cookie.as_deref() == Some("step=2")),
+ "the page's cookie went on to the file: {:?}",
+ log.iter().map(|e| &e.cookie).collect::<Vec<_>>()
+ );
+}
+
+/// A web page that leads nowhere is the download itself, asked for again after the look.
+#[tokio::test]
+async fn a_plain_web_page_is_still_downloaded() {
+ let s = server("").await;
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: s.url("/gen/8K/page.html?seed=32").parse().unwrap(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let out = Download::start(req, fast_opts()).wait().await.unwrap();
+ assert_eq!(out.size, 8 << 10);
+}
+
#[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
diff --git a/crates/ipc/src/lib.rs b/crates/ipc/src/lib.rs
index cc57d68b..4c403982 100644
--- a/crates/ipc/src/lib.rs
+++ b/crates/ipc/src/lib.rs
@@ -317,6 +317,7 @@ fn handle(conn: &TcpStream, token: &str, tx: &Sender<Incoming>, wake: &dyn Fn())
// Said so, so the browser's host doesn't take silence for an app that isn't there.
Err(Some(TooLarge)) => {
let _ = (&*conn).write_all(b"too-large\n");
+ linger_close(conn);
return;
}
Err(None) => return,
@@ -360,6 +361,31 @@ fn handle(conn: &TcpStream, token: &str, tx: &Sender<Incoming>, wake: &dyn Fn())
let _ = (&*conn).write_all(reply.as_bytes());
}
+/// Close after an answer given before the request was read to its end: no more writing, then
+/// what the client still sends is read and dropped (up to a limit, for a second at most).
+/// Closing with it unread makes the system reset the connection (macOS at once), and a reset can
+/// lose the answer before the client reads it.
+fn linger_close(conn: &TcpStream) {
+ use std::io::Read;
+ let _ = conn.shutdown(std::net::Shutdown::Write);
+ let _ = conn.set_read_timeout(Some(Duration::from_millis(250)));
+ let start = std::time::Instant::now();
+ let mut drained = 0;
+ let mut chunk = vec![0u8; 64 << 10];
+ while drained < 4 * MAX_REQUEST && start.elapsed() < Duration::from_secs(1) {
+ match (&*conn).read(&mut chunk) {
+ Ok(0) => break,
+ Ok(n) => drained += n,
+ Err(e)
+ if matches!(
+ e.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
+ ) => {}
+ Err(_) => break,
+ }
+ }
+}
+
/// An HTTP request line (`POST / HTTP/1.1`) instead of our JSON.
fn looks_like_http(line: &str) -> bool {
let line = line.trim_end_matches('\r');
@@ -396,7 +422,9 @@ fn read_request(conn: &std::net::TcpStream) -> Result<String, Option<TooLarge>>
conn.set_read_timeout(Some(Duration::from_millis(250)))
.map_err(|_| None)?;
let mut buf = Vec::new();
- let mut chunk = [0u8; 4096];
+ // Large reads: a request up to the limit (2 MB) comes in well within the deadline even on a
+ // busy machine (4 KB reads ran past it on a CI Mac).
+ let mut chunk = vec![0u8; 64 << 10];
loop {
if buf.len() > MAX_REQUEST {
return Err(Some(TooLarge));
diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rs
index 97c41eb6..0ad3b0c9 100644
--- a/crates/labserver/src/server.rs
+++ b/crates/labserver/src/server.rs
@@ -5,8 +5,11 @@
//! `content`); the file params shape its headers (`cd`, `cdstar`, `inline`)
//! - `POST /form/{size}[/{name}]?need=FIELD=VALUE[&see_other=1]&<as /gen>` — the same file, only
//! for a form post that carries `FIELD=VALUE`
-//! - `GET /redirect?to=URL[&ttl_ms=N]` — 302 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][&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 /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`)
//! - `GET /hls/*`, `/dash/*` — adaptive streams (`streams`)
//! - `GET /_log` — the request log as JSON; `DELETE /_log` clears it
@@ -25,7 +28,7 @@ use axum::body::{Body, HttpBody};
use axum::extract::{ConnectInfo, Path, RawQuery, Request, State};
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
use axum::middleware::Next;
-use axum::response::{IntoResponse, Response};
+use axum::response::{Html, IntoResponse, Response};
use axum::routing::{any, get};
use axum::{Json, Router};
use bytes::Bytes;
@@ -226,6 +229,7 @@ impl LabServer {
.route("/form/{size}", any(form))
.route("/form/{size}/{*name}", any(form))
.route("/redirect", get(redirect))
+ .route("/hop", get(hop))
.route("/_log", get(get_log).delete(clear_log))
.merge(simple)
.with_state(shared.clone());
@@ -294,7 +298,8 @@ POST /form/{size}[/{name}]?need=FIELD=VALUE&see_other=1&<as /gen>
the file, only for a POST whose form (urlencoded, multipart or text/plain) has FIELD=VALUE
(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> instead
-GET /redirect?to=URL[&ttl_ms=N] 302 to URL (not logged); ttl_ms: a signed link expiring after N ms
+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 /hop?to=URL&how=meta|header[&wait=S][&cookie=N=V] a page that sends the browser on to URL (meta refresh or Refresh header)
PAGES for the browser extension's tests (tools/extension/e2e.mjs); styles and scripts are files
GET /page?<any of>
@@ -368,7 +373,8 @@ async fn log_simple(
resp
}
-/// `/redirect?to=URL[&ttl_ms=N]`: 302 to `URL`; with `ttl_ms`, to a signed link that expires.
+/// `/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.
async fn redirect(RawQuery(q): RawQuery) -> Response {
let mut m = q
.and_then(|q| serde_urlencoded::from_str::<HashMap<String, String>>(&q).ok())
@@ -380,7 +386,44 @@ async fn redirect(RawQuery(q): RawQuery) -> Response {
let sep = if to.contains('?') { '&' } else { '?' };
to = format!("{to}{sep}expires={}", unix_ms() + ttl);
}
- (StatusCode::FOUND, [(header::LOCATION, to)]).into_response()
+ let code = m
+ .get("code")
+ .and_then(|c| c.parse::<u16>().ok())
+ .and_then(|c| StatusCode::from_u16(c).ok())
+ .filter(StatusCode::is_redirection)
+ .unwrap_or(StatusCode::FOUND);
+ (code, [(header::LOCATION, to)]).into_response()
+}
+
+/// `/hop?to=URL&how=meta|header[&wait=S][&cookie=NAME=VALUE]`: a web page (200) that sends the
+/// browser on to `URL` itself, as download sites' "your download starts in a moment" pages do:
+/// with a `<meta http-equiv="refresh">` in it, or a `Refresh` header; `cookie` is set on the way.
+async fn hop(RawQuery(q): RawQuery) -> Response {
+ let m = q
+ .and_then(|q| serde_urlencoded::from_str::<HashMap<String, String>>(&q).ok())
+ .unwrap_or_default();
+ let Some(to) = m.get("to") else {
+ return StatusCode::BAD_REQUEST.into_response();
+ };
+ let wait = m.get("wait").map_or("0", String::as_str);
+ let content = format!("{wait}; url={to}");
+ let mut resp = match m.get("how").map(String::as_str) {
+ Some("header") => (
+ [(header::REFRESH, content)],
+ Html("<p>Your download starts in a moment.</p>".to_owned()),
+ )
+ .into_response(),
+ _ => Html(format!(
+ "<!doctype html><title>Download</title><meta http-equiv=\"refresh\" \
+ content=\"{}\"><p>Your download starts in a moment.</p>",
+ content.replace('&', "&amp;").replace('"', "&quot;")
+ ))
+ .into_response(),
+ };
+ if let Some(cookie) = m.get("cookie").and_then(|c| c.parse().ok()) {
+ resp.headers_mut().insert(header::SET_COOKIE, cookie);
+ }
+ resp
}
fn unix_ms() -> u64 {
diff --git a/crates/nmhost/tests/host.rs b/crates/nmhost/tests/host.rs
index c26b873d..5ae5c8af 100644
--- a/crates/nmhost/tests/host.rs
+++ b/crates/nmhost/tests/host.rs
@@ -63,8 +63,14 @@ fn run(
let mut stdin = child.stdin.take().unwrap();
for m in messages {
let body = m.to_string().into_bytes();
- stdin.write_all(&(body.len() as u32).to_le_bytes()).unwrap();
- stdin.write_all(&body).unwrap();
+ // A host that refuses its caller exits at once: what's left to send meets a closed
+ // pipe, which is its answer, not a failure of the test.
+ let sent = stdin
+ .write_all(&(body.len() as u32).to_le_bytes())
+ .and_then(|()| stdin.write_all(&body));
+ if sent.is_err() {
+ break;
+ }
}
drop(stdin);
let mut out = Vec::new();