Skip to content

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

One-time links: the download continues from Download File Info's answer (#28) (#52)

Ahmed Nefzaoui27430a01564e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a2844a03..123406f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -111,6 +111,11 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **Links that work only once** (or hosts that allow one download at a time) failed with "403
+ Forbidden" after Download File Info had looked them up
+ ([#28](https://github.com/anefzaoui/misterdownloadmanager/issues/28)): the window's look and the
+ download each asked the server. The download now continues from the answer the window got,
+ and asks again only if that connection has closed meanwhile.
- 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
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index dd21ba0b..1e7a833c 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -259,6 +259,9 @@ pub struct App {
file_info: Option<FileInfo>,
/// Addresses (and their browser context) waiting for Download File Info to close.
file_info_waiting: std::collections::VecDeque<(dialogs::NewUrl, ipc::Command)>,
+ /// Download File Info's open answers, for the download each was given to (by id) to start
+ /// from (#28: a one-time link refuses a second request).
+ kept_answers: std::collections::HashMap<u64, mdm_engine::KeptAnswer>,
/// Help menu windows.
about: Option<crate::help::About>,
updates: Option<crate::help::Updates>,
@@ -658,6 +661,7 @@ impl App {
update_checked_this_run: None,
file_info: None,
file_info_waiting: Default::default(),
+ kept_answers: Default::default(),
progress: Vec::new(),
complete: Vec::new(),
settings,
@@ -975,7 +979,7 @@ impl App {
// ---- actions ---------------------------------------------------------------------------
- fn add(&mut self, fi: &FileInfo, start: Start) {
+ fn add(&mut self, fi: &mut FileInfo, start: Start) {
// Only a folder other than the category's becomes its new one (an unchanged folder
// stays "the default", following Downloads).
if let Some((cat, dir)) = fi.remembered()
@@ -1000,6 +1004,10 @@ impl App {
self.name_guessed(id, fi.name_guessed());
self.selection.set(id);
if matches!(start, Start::Now) {
+ // Later: the answer is closed (its download starts some other time).
+ if let Some(k) = fi.take_kept() {
+ self.kept_answers.insert(id, k);
+ }
self.start(id, true);
} else {
// "Download Later": the main download queue (IDM's default), or the one picked.
@@ -1034,6 +1042,9 @@ impl App {
},
);
fi.early = Some(id);
+ if let Some(k) = fi.take_kept() {
+ self.kept_answers.insert(id, k);
+ }
self.start(id, false);
}
@@ -1465,6 +1476,8 @@ impl App {
return;
};
let RequestParts { headers, mut opts } = self.request_parts(&url, login.as_ref(), &context);
+ // Download File Info's open answer for it, if it has one (#28); used once.
+ let kept = self.kept_answers.remove(&id);
// The file's own remembered limit, else the Speed Limiter's.
opts.speed_limit = own_limit.or(self.settings.speed_limit());
opts.checksum = checksum;
@@ -1496,13 +1509,14 @@ impl App {
Some(dir) if item.name_from_url => Destination::Dir(dir.to_owned()),
_ => Destination::File(item.dest.clone()),
};
- Download::start(
+ Download::start_with(
Request {
url: item.url.clone(),
headers,
dest,
},
opts,
+ kept,
)
};
item.note(if item.downloaded > 0 {
@@ -5214,7 +5228,7 @@ impl App {
}
Outcome::Done(start) => match fi.early {
Some(id) => self.adopt_early(&fi, id, start),
- None => self.add(&fi, start),
+ None => self.add(&mut fi, start),
},
}
}
diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rs
index 6796f327..5523194c 100644
--- a/crates/app/src/dialogs.rs
+++ b/crates/app/src/dialogs.rs
@@ -492,8 +492,10 @@ pub struct FileInfo {
/// requests carry (app::RequestParts).
rt: tokio::runtime::Handle,
request: crate::app::RequestParts,
- probe: Arc<Mutex<Option<Result<ProbeInfo, String>>>>,
+ probe: Arc<Mutex<Option<Probed>>>,
info: Option<Result<ProbeInfo, String>>,
+ /// The look's open answer, for the download to read instead of asking again (#28).
+ kept: Option<mdm_engine::KeptAnswer>,
edited: bool,
downloads: PathBuf,
/// Options → Save to folders per category (label, folder).
@@ -572,6 +574,7 @@ impl FileInfo {
remember: false,
probe,
info,
+ kept: None,
edited: false,
downloads,
dirs,
@@ -619,6 +622,8 @@ impl FileInfo {
self.request.headers.remove(reqwest::header::CONTENT_TYPE);
self.probe = start_probe(&self.rt, ctx, &url, &self.request);
self.info = None;
+ // The old address's answer is closed.
+ self.kept = None;
self.url = url;
}
_ => self.url_bad = true,
@@ -647,6 +652,12 @@ impl FileInfo {
})
}
+ /// The look's open answer, for the download of this address to start from (#28); taken
+ /// once.
+ pub fn take_kept(&mut self) -> Option<mdm_engine::KeptAnswer> {
+ self.kept.take()
+ }
+
/// The address was looked up and answered (name and size known): the moment IDM starts an
/// early download.
pub fn probed(&self) -> bool {
@@ -704,6 +715,10 @@ impl FileInfo {
if self.info.is_none()
&& let Some(res) = self.probe.lock().unwrap().take()
{
+ let res = res.map(|(pi, kept)| {
+ self.kept = kept;
+ pi
+ });
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);
@@ -1015,17 +1030,20 @@ impl FileInfo {
/// Look `url` up in the background (name, size) as the download will ask it (`request`), the
/// answer landing in the slot returned.
+/// A look's result: what it learned, and its open answer when the download can read it.
+type Probed = Result<(ProbeInfo, Option<mdm_engine::KeptAnswer>), String>;
+
fn start_probe(
rt: &tokio::runtime::Handle,
ctx: &egui::Context,
url: &Url,
request: &crate::app::RequestParts,
-) -> Arc<Mutex<Option<Result<ProbeInfo, String>>>> {
+) -> Arc<Mutex<Option<Probed>>> {
let probe = Arc::new(Mutex::new(None));
let (slot, url, ctx) = (probe.clone(), url.clone(), ctx.clone());
let (headers, opts) = (request.headers.clone(), request.opts.clone());
rt.spawn(async move {
- let res = mdm_engine::probe(url, headers, &opts)
+ let res = mdm_engine::probe_kept(url, headers, &opts)
.await
.map_err(|e| e.to_string());
*slot.lock().unwrap() = Some(res);
diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rs
index ae37f231..4c7435ba 100644
--- a/crates/engine/src/download.rs
+++ b/crates/engine/src/download.rs
@@ -646,35 +646,91 @@ pub struct ProbeInfo {
/// 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> {
+ probe_kept(url, headers, opts).await.map(|(info, _)| info)
+}
+
+/// The open answer of a look (`probe_kept`), for the download that follows it to read (#28): a
+/// one-time link, or a host that allows one download at a time, refuses the download asking
+/// again. Dropping it closes the connection.
+pub struct KeptAnswer {
+ /// The address asked: only a download of the same address takes it.
+ url: Url,
+ client: Client,
+ as_get: AsGet,
+ resp: Response,
+ headers: HeaderMap,
+ took: Duration,
+ at: std::time::Instant,
+}
+
+impl std::fmt::Debug for KeptAnswer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("KeptAnswer")
+ .field("url", &self.url.as_str())
+ .field("status", &self.resp.status())
+ .finish_non_exhaustive()
+ }
+}
+
+/// How long a kept answer is worth taking: a server ends an idle connection after a while,
+/// and the download then asks again (as when it isn't kept).
+const KEEP_ANSWER_FOR: Duration = Duration::from_secs(15 * 60);
+
+/// `probe`, keeping its answer open when its body is the file from byte 0 (200, or 206 from
+/// 0), for `Download::start_with`. Not for FTP, whose look is a separate command.
+pub async fn probe_kept(
+ url: Url,
+ headers: HeaderMap,
+ opts: &Options,
+) -> Result<(ProbeInfo, Option<KeptAnswer>), Error> {
if crate::ftp::is_ftp(&url) {
let site = crate::ftp::Site::new(&url, &headers, opts)?;
let facts = site.check().await?;
- return Ok(ProbeInfo {
- file_name: naming::file_name(None, &url),
- final_url: url,
- size: facts.size,
- });
+ return Ok((
+ ProbeInfo {
+ file_name: naming::file_name(None, &url),
+ final_url: url,
+ size: facts.size,
+ },
+ None,
+ ));
}
- let (resp, ..) = get(
- &client(opts, &url, &AsGet::default())?,
- url,
+ let as_get = AsGet::default();
+ let client = client(opts, &url, &as_get)?;
+ let (resp, headers, took) = get(
+ &client,
+ url.clone(),
headers,
opts.post.as_ref(),
&CancellationToken::new(),
)
.await?;
let final_url = resp.url().clone();
- let size = match resp.status() {
- StatusCode::PARTIAL_CONTENT => parse_content_range(resp.headers())?.2,
- _ => resp.content_length(),
+ let (size, from_zero) = match resp.status() {
+ StatusCode::PARTIAL_CONTENT => {
+ let (start, _, total) = parse_content_range(resp.headers())?;
+ (total, start == 0)
+ }
+ StatusCode::OK => (resp.content_length(), true),
+ _ => (resp.content_length(), false),
};
let cd = header_text(resp.headers(), header::CONTENT_DISPOSITION);
let file_name = naming::file_name(cd.as_deref(), &final_url);
- Ok(ProbeInfo {
+ let info = ProbeInfo {
final_url,
size,
file_name,
- })
+ };
+ let kept = from_zero.then(|| KeptAnswer {
+ url,
+ client,
+ as_get,
+ resp,
+ headers,
+ took,
+ at: std::time::Instant::now(),
+ });
+ Ok((info, kept))
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -693,13 +749,19 @@ pub struct Download {
impl Download {
/// Start downloading in the background. Must be called inside a Tokio runtime.
pub fn start(req: Request, opts: Options) -> Download {
+ Download::start_with(req, opts, None)
+ }
+
+ /// `start`, connection 1 reading `kept` (a look's open answer, `probe_kept`) instead of
+ /// asking again, when it is the same address's and recent (`KEEP_ANSWER_FOR`).
+ pub fn start_with(req: Request, opts: Options, kept: Option<KeptAnswer>) -> Download {
Download::spawn(req.url.clone(), move |shared, cancel| {
let sh = shared.clone();
let body = async move {
if crate::ftp::is_ftp(&req.url) {
run_fresh_ftp(req, opts, sh, cancel).await
} else {
- run_fresh(req, opts, sh, cancel).await
+ run_fresh(req, opts, sh, cancel, kept).await
}
};
run(body, shared)
@@ -1135,16 +1197,29 @@ async fn run_fresh(
opts: Options,
shared: Arc<Shared>,
cancel: CancellationToken,
+ kept: Option<KeptAnswer>,
) -> Result<Outcome, Error> {
shared.limiter.set(opts.speed_limit);
let (shared, cancel) = (&shared, &cancel);
- // Probe on connection 0: a plain GET (or the form's POST) whose body becomes the segment
- // starting at 0.
- let as_get = AsGet::default();
- let client0 = client(&opts, &req.url, &as_get)?;
shared.conn(0, |_| {});
- let ((resp, headers), ttfb) =
- first_get(&client0, &req.url, &req.headers, &opts, shared, cancel).await?;
+ // 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);
+ let (as_get, client0, (resp, headers), ttfb) = match kept {
+ Some(k) => {
+ shared.event(
+ "Connection 1: continuing from the answer the file's information window got",
+ );
+ (k.as_get, k.client, (k.resp, k.headers), k.took)
+ }
+ None => {
+ let as_get = AsGet::default();
+ let client0 = client(&opts, &req.url, &as_get)?;
+ let (answer, ttfb) =
+ first_get(&client0, &req.url, &req.headers, &opts, shared, cancel).await?;
+ (as_get, client0, answer, ttfb)
+ }
+ };
let preempt_after = (ttfb * PREEMPT_TTFB).max(PREEMPT_MIN);
let size = match resp.status() {
StatusCode::OK => resp.content_length(),
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 7ac88c24..b3a1f793 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -14,6 +14,6 @@ pub mod state;
pub mod verify;
pub use download::{
- Destination, Download, Error, Event, FileHook, NetKind, Options, Outcome, ProbeInfo, Proxy,
- Request, Snapshot, fetch, probe, supported,
+ Destination, Download, Error, Event, FileHook, KeptAnswer, NetKind, Options, Outcome,
+ ProbeInfo, Proxy, Request, Snapshot, fetch, probe, probe_kept, supported,
};
diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs
index 88326512..0889cd58 100644
--- a/crates/engine/tests/e2e.rs
+++ b/crates/engine/tests/e2e.rs
@@ -1069,3 +1069,52 @@ async fn a_pac_script_routes_through_its_proxy() {
"content mismatch"
);
}
+
+/// #28: a one-time link (the second request for it is refused). The look Download File Info
+/// makes is kept and the download reads it, with one connection or several (the others are
+/// refused and connection 1 goes on alone); without it the download is refused, as reported.
+#[tokio::test]
+async fn a_one_time_link_is_read_from_the_kept_answer() {
+ let s = server("").await;
+ for (n, connections) in [(1u64, 1u32), (2, 8)] {
+ let url: url::Url = s
+ .url(&format!("/gen/2M/once{n}.zip?once=1&seed={n}"))
+ .parse()
+ .unwrap();
+ let opts = Options {
+ max_connections: connections,
+ ..fast_opts()
+ };
+ let (info, kept) = mdm_engine::probe_kept(url.clone(), Default::default(), &opts)
+ .await
+ .unwrap();
+ assert_eq!(info.size, Some(2 << 20));
+ assert!(kept.is_some(), "a 200 from byte 0 is kept");
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: url.clone(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let out = Download::start_with(req, opts.clone(), kept)
+ .wait()
+ .await
+ .unwrap_or_else(|e| panic!("{connections} connection(s): {e}"));
+ let data = std::fs::read(&out.path).unwrap();
+ let mut want = vec![0; data.len()];
+ content::fill(n, 0, &mut want);
+ assert!(data == want && data.len() == 2 << 20, "content");
+ }
+ // Asked again (the look's answer not kept): refused.
+ let url: url::Url = s.url("/gen/1M/once9.zip?once=1&seed=9").parse().unwrap();
+ mdm_engine::probe(url.clone(), Default::default(), &fast_opts())
+ .await
+ .unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url,
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ assert!(Download::start(req, fast_opts()).wait().await.is_err());
+}