1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-12-04 18:56:44 +01:00

fix: classify HTML pages and reuse probe downloads (#45)

Classify pages when a HEAD response omits Content-Type by probing GET headers. Reuse that GET response for file captures so single-use download URLs are requested only once.
This commit is contained in:
TheGeneralist 2026-10-14 17:26:47 +02:00 • committed by GitHub
parent 19718cee22
commit f900d7e0ef
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 183 additions and 35 deletions

View file

@ -1277,10 +1277,11 @@ pub fn perform_capture(
// For generic http/https URLs, probe Content-Type to decide whether to
// treat the URL as a raw file download or an HTML page for SingleFile.
let mut probed_file_response = None;
if source == Source::Url {
match downloader::http::probe_url_kind(locator, &cookies) {
Ok(downloader::http::UrlKind::Html) => source = Source::WebPage,
Ok(downloader::http::UrlKind::File) => {}
match downloader::http::probe_url(locator, &cookies) {
Ok(probe) if probe.kind == downloader::http::UrlKind::Html => source = Source::WebPage,
Ok(probe) => probed_file_response = probe.file_response,
Err(e) => {
// Probe failed (e.g. Cloudflare JS challenge, 403, network
// issue). Fall back to treating the URL as an HTML page so
@ -1651,7 +1652,12 @@ pub fn perform_capture(
// Source: generic HTTP/S file URL
if source == Source::Url {
match downloader::http::download(locator, store_path, &timestamp, &cookies) {
let download = if let Some(response) = probed_file_response {
downloader::http::download_response(response, locator, store_path, &timestamp)
} else {
downloader::http::download(locator, store_path, &timestamp, &cookies)
};
match download {
Ok((hash, file_extension, title_hint)) => {
let temp_file = store_path
.join("temp")

View file

@ -5,19 +5,31 @@ use crate::downloader::cookies::cookies_to_header;
use crate::hash::hash_file;
/// Whether a URL resolves to an HTML document or a downloadable file.
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UrlKind {
Html,
File,
}
/// A GET used to classify a file can also supply its body to the downloader.
/// Keeping that response matters for URLs that allow only one GET.
pub(crate) struct UrlProbe {
pub kind: UrlKind,
pub file_response: Option<reqwest::blocking::Response>,
}
/// Probes `url` with a HEAD request and inspects the `Content-Type` header.
/// Falls back to a GET request (body not read) if the server returns 405.
/// Falls back to a GET request (body not read) if the server returns 405 or
/// omits the header on HEAD. Some sites provide a type only for GET.
///
/// Returns `Err` if the probe fails (network error, non-2xx/405 status).
/// Redirects (3xx) are followed automatically by reqwest; only the final
/// response status is checked.
pub fn probe_url_kind(url: &str, cookies: &HashMap<String, String>) -> Result<UrlKind> {
Ok(probe_url(url, cookies)?.kind)
}
pub(crate) fn probe_url(url: &str, cookies: &HashMap<String, String>) -> Result<UrlProbe> {
let client = reqwest::blocking::Client::builder()
.redirect(reqwest::redirect::Policy::limited(10))
.user_agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 archivr/0.1")
@ -35,43 +47,54 @@ pub fn probe_url_kind(url: &str, cookies: &HashMap<String, String>) -> Result<Ur
req.send().with_context(|| format!("failed to probe {url}"))?
};
if head.status() == reqwest::StatusCode::METHOD_NOT_ALLOWED {
// Server rejected HEAD — do a GET but only inspect headers.
let get = {
let mut req = client.get(url);
if !cookie_header.is_empty() {
req = req.header(reqwest::header::COOKIE, &cookie_header);
}
req.send().with_context(|| format!("failed to probe {url}"))?
};
if !get.status().is_success() {
bail!("HTTP {} probing {url}", get.status());
}
let ct = get
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
return Ok(if content_type_is_html(ct) {
UrlKind::Html
} else {
UrlKind::File
});
}
if !head.status().is_success() {
if head.status() != reqwest::StatusCode::METHOD_NOT_ALLOWED && !head.status().is_success() {
bail!("HTTP {} probing {url}", head.status());
}
let ct = head
let head_content_type = head
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
Ok(if content_type_is_html(ct) {
UrlKind::Html
if head.status().is_success() && !head_content_type.trim().is_empty() {
return Ok(UrlProbe {
kind: if content_type_is_html(head_content_type) {
UrlKind::Html
} else {
UrlKind::File
},
file_response: None,
});
}
// HEAD without a Content-Type is ambiguous: LessWrong, for example,
// returns no type for HEAD and text/html for GET. Inspect GET headers
// before choosing the raw-file downloader.
let get = {
let mut req = client.get(url);
if !cookie_header.is_empty() {
req = req.header(reqwest::header::COOKIE, &cookie_header);
}
req.send().with_context(|| format!("failed to probe {url}"))?
};
if !get.status().is_success() {
bail!("HTTP {} probing {url}", get.status());
}
let get_content_type = get
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
Ok(if content_type_is_html(get_content_type) {
UrlProbe {
kind: UrlKind::Html,
file_response: None,
}
} else {
UrlKind::File
UrlProbe {
kind: UrlKind::File,
file_response: Some(get),
}
})
}
@ -99,6 +122,15 @@ pub fn download(url: &str, store_path: &Path, timestamp: &str, cookies: &HashMap
req.send().with_context(|| format!("failed to fetch {url}"))?
};
download_response(response, url, store_path, timestamp)
}
pub(crate) fn download_response(
response: reqwest::blocking::Response,
url: &str,
store_path: &Path,
timestamp: &str,
) -> Result<(String, String, Option<String>)> {
if !response.status().is_success() {
bail!("HTTP {} fetching {url}", response.status());
}
@ -413,4 +445,114 @@ mod tests {
"unexpected error message: {msg}"
);
}
#[test]
fn probe_uses_get_type_when_head_omits_it() {
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::time::{Duration, Instant};
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
listener.set_nonblocking(true).unwrap();
let server = std::thread::spawn(move || {
for (method, content_type) in [
("HEAD", ""),
("GET", "Content-Type: text/html; charset=utf-8\r\n"),
] {
let deadline = Instant::now() + Duration::from_secs(5);
let mut stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(e)
if e.kind() == std::io::ErrorKind::WouldBlock
&& Instant::now() < deadline =>
{
std::thread::sleep(Duration::from_millis(10));
}
Err(e) => panic!("expected {method} request: {e}"),
}
};
let mut request_line = String::new();
BufReader::new(&stream).read_line(&mut request_line).unwrap();
assert!(
request_line.starts_with(method),
"unexpected request: {request_line}"
);
write!(
stream,
"HTTP/1.1 200 OK\r\n{content_type}Content-Length: 0\r\nConnection: close\r\n\r\n"
)
.unwrap();
}
});
let kind = probe_url_kind(
&format!("http://{addr}/w/the-map-is-not-the-territory"),
&HashMap::new(),
);
server.join().unwrap();
assert_eq!(kind.unwrap(), UrlKind::Html);
}
#[test]
fn capture_reuses_probe_get_for_single_use_file() {
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::sync::{Arc, atomic::{AtomicBool, AtomicUsize, Ordering}};
use std::time::{Duration, Instant};
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
listener.set_nonblocking(true).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let get_count = Arc::new(AtomicUsize::new(0));
let server_stop = Arc::clone(&stop);
let server_get_count = Arc::clone(&get_count);
let server = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(10);
while !server_stop.load(Ordering::SeqCst) && Instant::now() < deadline {
let mut stream = match listener.accept() {
Ok((stream, _)) => stream,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(10));
continue;
}
Err(e) => panic!("accept failed: {e}"),
};
let mut request_line = String::new();
BufReader::new(&stream).read_line(&mut request_line).unwrap();
if request_line.starts_with("HEAD ") {
write!(stream, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap();
} else if request_line.starts_with("GET ") {
if server_get_count.fetch_add(1, Ordering::SeqCst) == 0 {
write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/pdf\r\nContent-Length: 9\r\nConnection: close\r\n\r\n%PDF-1.7\n").unwrap();
} else {
write!(stream, "HTTP/1.1 410 Gone\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap();
}
} else {
panic!("unexpected request: {request_line}");
}
}
});
let temp = tempfile::tempdir().unwrap();
let paths = crate::archive::initialize_archive(
temp.path(),
&temp.path().join("store"),
"single-use-file",
false,
).unwrap();
let result = crate::capture::perform_capture(
&paths,
&format!("http://{addr}/one-time.pdf"),
None,
None,
&crate::capture::CaptureConfig::default(),
);
stop.store(true, Ordering::SeqCst);
server.join().unwrap();
assert_eq!(result.unwrap().status, "completed");
assert_eq!(get_count.load(Ordering::SeqCst), 1);
}
}