Medlar/crates/core/src/http/mod.rs

550 lines
21 KiB
Rust

//! Downloading over HTTP and HTTPS. How the client is set up and why: D-017, D-018.
mod download;
mod fetch;
mod monitor;
pub(crate) mod name;
mod parts;
mod piece;
mod probe;
#[cfg(test)]
mod fuzz;
pub use download::{Options, Shared, download};
pub(crate) use download::is_page;
pub(crate) use fetch::{bytes_at, same_body, small};
pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes};
pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot};
pub use name::{prefer as prefer_name, safe as safe_name};
pub(crate) use piece::piece;
pub use probe::{Probe, probe};
use crate::model::ErrorKind;
use crate::sftp::HostKeys;
use crate::site::{Access, same_site};
use crate::tls::Trust;
use crate::transport::{Remote, Way};
use crate::{disk, redact, store, stream};
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
pub(crate) use reqwest::Response;
use reqwest::{RequestBuilder, StatusCode, redirect};
use std::path::PathBuf;
use std::sync::{Arc, Once};
use std::time::Duration;
use tokio::sync::watch;
use url::Url;
/// Why a download stopped. `error::Failure` has the words for the user.
#[derive(Debug)]
pub enum Error {
/// Asked to stop.
Stopped,
/// Not a link this module can open.
Link,
/// No connection, no answer in time, or a broken one. Never holds the link.
Net(reqwest::Error),
/// Nothing came for `ClientOptions::idle_timeout`.
Idle,
/// The proxy can't be reached or refuses. None: its setting makes no sense.
Proxy(Option<reqwest::Error>),
/// A connection that isn't HTTP failed. `why` is the text, if it isn't the usual one.
Conn { kind: ErrorKind, why: Option<&'static str> },
/// TLS can't be set up here.
Tls(rustls::Error),
Status { code: u16, retry_after: Option<Duration> },
/// The file on the server is not the one the parts came from.
Changed,
/// A web page came in place of the file.
Page,
/// A range was asked for and the whole file came.
RangeIgnored,
/// Finished bytes are on disk and the server can't continue from them.
NoResume,
/// The server packed the file, though it was asked not to.
Encoded(String),
/// The server's own numbers contradict each other.
BadReply(String),
/// The connection ended early.
Cut { got: u64, expected: Option<u64> },
/// Finished bytes are recorded, but their file is gone.
Missing,
/// The whole file isn't what its checksum says.
Checksum,
Disk(disk::Error),
Store(store::Error),
}
impl Error {
pub(crate) fn conn(kind: ErrorKind) -> Error {
Error::Conn { kind, why: None }
}
pub(crate) fn because(kind: ErrorKind, why: &'static str) -> Error {
Error::Conn { kind, why: Some(why) }
}
}
pub type Result<T> = std::result::Result<T, Error>;
impl From<rustls::Error> for Error {
fn from(e: rustls::Error) -> Error {
Error::Tls(e)
}
}
impl From<disk::Error> for Error {
fn from(e: disk::Error) -> Error {
Error::Disk(e)
}
}
impl From<store::Error> for Error {
fn from(e: store::Error) -> Error {
Error::Store(e)
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Error {
Error::Net(e.without_url())
}
}
/// Turns true when the work should stop.
pub type Stop = watch::Receiver<bool>;
#[derive(Debug, Clone)]
pub struct ClientOptions {
pub connect_timeout: Duration,
/// Between two pieces of data.
pub idle_timeout: Duration,
/// DER certificates to trust instead of the system's (tests).
pub only_certs: Vec<Vec<u8>>,
/// Where the keys of SSH servers are kept: `Paths::known_hosts`. None forgets them at the end.
pub known_hosts: Option<PathBuf>,
}
impl Default for ClientOptions {
fn default() -> Self {
ClientOptions { connect_timeout: Duration::from_secs(20), idle_timeout: Duration::from_secs(30), only_certs: vec![], known_hosts: None }
}
}
/// Doesn't wait forever for an answer or the next piece of it.
#[derive(Debug, Clone)]
pub struct Client {
inner: reqwest::Client,
connect: Duration,
idle: Duration,
trust: Arc<Trust>,
}
impl Client {
pub(crate) fn get(&self, url: Url) -> RequestBuilder {
self.inner.get(url)
}
pub(crate) fn connect_timeout(&self) -> Duration {
self.connect
}
pub(crate) fn idle_timeout(&self) -> Duration {
self.idle
}
pub(crate) fn trust(&self) -> &Arc<Trust> {
&self.trust
}
/// The time counts while it is waited for only: limits may hold back what came before for longer. reqwest's own timeout goes
/// on meanwhile.
pub(crate) async fn wait<T, E: Into<Error>>(&self, what: impl Future<Output = std::result::Result<T, E>>) -> Result<T> {
match tokio::time::timeout(self.idle, what).await {
Ok(result) => result.map_err(Into::into),
Err(_) => Err(Error::Idle),
}
}
}
pub fn client(options: &ClientOptions) -> Result<Client> {
client_with(options, &trust(options)?, None)
}
/// Reads the system's certificates.
pub(crate) fn trust(options: &ClientOptions) -> Result<Arc<Trust>> {
let host_keys = HostKeys::new(options.known_hosts.clone());
Ok(Arc::new(Trust::new(Arc::new(rustls::crypto::ring::default_provider()), &options.only_certs, host_keys)?))
}
pub(crate) fn client_with(options: &ClientOptions, trust: &Arc<Trust>, proxy: Option<Url>) -> Result<Client> {
static TLS: Once = Once::new();
// Fails only when one is installed already, which is fine.
TLS.call_once(|| drop(rustls::crypto::ring::default_provider().install_default()));
let mut builder = reqwest::Client::builder()
.user_agent(concat!("Medlar/", env!("CARGO_PKG_VERSION")))
.http1_only()
// Each hop has its own headers and its own way.
.redirect(redirect::Policy::none())
.referer(false)
.retry(reqwest::retry::never())
.no_proxy()
// Reused at once or not at all: idle ones count against what a host stands.
.pool_idle_timeout(Duration::from_millis(500))
.connect_timeout(options.connect_timeout)
.tls_backend_preconfigured(trust.config(Arc::new(rustls::crypto::ring::default_provider()))?);
if let Some(proxy) = proxy {
builder = builder.proxy(reqwest::Proxy::all(proxy)?);
}
Ok(Client { inner: builder.build()?, connect: options.connect_timeout, idle: options.idle_timeout, trust: trust.clone() })
}
/// A link and the headers that go with it.
#[derive(Debug, Clone)]
pub struct Source {
pub url: Url,
pub headers: HeaderMap,
access: Option<Arc<Access>>,
/// For a link that isn't HTTP.
remote: Option<Arc<Remote>>,
}
/// Redirects followed.
const HOPS: usize = 10;
impl Source {
pub fn new(url: &str) -> Result<Source> {
let url = Url::parse(url).map_err(|_| Error::Link)?;
let remote = Remote::of(&url).map(Arc::new);
if !(remote.is_some() || matches!(url.scheme(), "http" | "https") || stream::recorded(&url)) || url.host_str().is_none_or(str::is_empty) {
return Err(Error::Link);
}
Ok(Source { url, headers: HeaderMap::new(), access: None, remote })
}
/// Adds headers, skipping what isn't valid and what the engine sets itself.
pub fn with_headers(mut self, headers: &[(String, String)]) -> Source {
for (name, value) in valid(headers) {
self.headers.append(name, value);
}
self
}
pub(crate) fn with_access(self, access: Access) -> Source {
Source { access: Some(Arc::new(access)), ..self }
}
/// The user's cap on connections to this site.
pub(crate) fn max_connections(&self) -> Option<u32> {
self.access.as_ref()?.rules(&self.url).max_connections
}
/// The user's limit for all that comes from this site.
pub(crate) fn speed_limit(&self) -> Option<u64> {
self.access.as_ref()?.rules(&self.url).speed_limit
}
/// The same source at the link its redirects led to. What was given for one site stays with it.
pub fn at(&self, url: &Url) -> Source {
let mut headers = self.headers.clone();
if !same_site(&self.url, url) {
let harmless = [header::USER_AGENT, header::ACCEPT, header::ACCEPT_LANGUAGE, header::REFERER];
headers = headers.into_iter().filter_map(|(name, value)| Some((name.filter(|n| harmless.contains(n))?, value))).collect();
}
Source { url: url.clone(), headers, access: self.access.clone(), remote: self.remote.clone() }
}
/// Another link to the same file. What was given for one site stays with it.
pub fn mirror(&self, url: &str) -> Result<Source> {
let url = Source::new(url)?.url;
Ok(Source { remote: Remote::of(&url).map(Arc::new), ..self.at(&url) })
}
pub(crate) fn remote(&self) -> Option<&Remote> {
self.remote.as_deref()
}
/// For a link that isn't HTTP.
pub(crate) async fn way(&self, client: &Client) -> Result<Way> {
match &self.access {
Some(access) => access.way(&self.url).await,
None => Ok(Way { client: client.clone(), proxy: None, login: None, key: None }),
}
}
async fn get(&self, client: &Client, range: Option<String>, if_range: Option<&HeaderValue>, stop: &mut Stop) -> Result<Response> {
tokio::select! {
_ = stopped(stop) => Err(Error::Stopped),
response = self.follow(client, range.as_deref(), if_range) => response,
}
}
async fn follow(&self, client: &Client, range: Option<&str>, if_range: Option<&HeaderValue>) -> Result<Response> {
if let Some(remote) = &self.remote {
return remote.respond(client, self, range).await;
}
if stream::recorded(&self.url) {
return Err(Error::Link);
}
let mut here = self.clone();
for _ in 0..=HOPS {
let request = |client: &Client, headers: &HeaderMap| -> RequestBuilder {
let mut request = client.get(here.url.clone()).headers(headers.clone()).header(header::ACCEPT_ENCODING, "identity");
if let Some(range) = range {
request = request.header(header::RANGE, range);
if let Some(validator) = if_range {
request = request.header(header::IF_RANGE, validator);
}
}
request
};
let response = match &here.access {
Some(access) => access.send(&here.url, &here.headers, request).await?,
None => client.wait(request(client, &here.headers).send()).await?,
};
match redirect(&response)? {
Some(next) => here = here.at(&next),
None => return Ok(response),
}
}
Err(Error::Link)
}
}
/// Headers without those that aren't valid and those the engine sets itself.
pub(crate) fn valid(headers: &[(String, String)]) -> impl Iterator<Item = (HeaderName, HeaderValue)> {
headers.iter().filter_map(|(name, value)| {
let (name, mut value) = (HeaderName::try_from(name).ok()?, HeaderValue::try_from(value).ok()?);
value.set_sensitive(redact::is_secret_header(name.as_str()));
let own = [header::RANGE, header::IF_RANGE, header::ACCEPT_ENCODING, header::HOST, header::CONNECTION, header::PROXY_AUTHORIZATION];
(!own.contains(&name)).then_some((name, value))
})
}
/// Where the server sends us, if it does.
fn redirect(response: &Response) -> Result<Option<Url>> {
let moved = matches!(response.status().as_u16(), 301 | 302 | 303 | 307 | 308);
let Some(to) = response.headers().get(header::LOCATION).filter(|_| moved) else { return Ok(None) };
let to = std::str::from_utf8(to.as_bytes()).ok().and_then(|to| response.url().join(to).ok());
let mut url = to.filter(|u| matches!(u.scheme(), "http" | "https") && u.has_host()).ok_or(Error::Link)?;
// A login in there is not the user's.
let _ = (url.set_username(""), url.set_password(None));
Ok(Some(url))
}
/// Resolves when asked to stop, never when nobody can ask any more.
pub(crate) async fn stopped(stop: &mut Stop) {
if stop.wait_for(|s| *s).await.is_err() {
std::future::pending().await
}
}
/// `bytes a-b/total`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ContentRange {
first: u64,
last: u64,
total: Option<u64>,
}
impl ContentRange {
fn of(headers: &HeaderMap) -> Option<ContentRange> {
let (range, total) = split_range(headers)?;
let (first, last) = range.split_once('-')?;
let (first, last) = (first.trim().parse().ok()?, last.trim().parse().ok()?);
let total = match total {
"*" => None,
n => Some(n.parse().ok()?),
};
(first <= last && total.is_none_or(|t| last < t)).then_some(ContentRange { first, last, total })
}
fn len(self) -> u64 {
self.last - self.first + 1
}
}
/// The total in `bytes */total`, which comes with 416.
fn unsatisfied_total(headers: &HeaderMap) -> Option<u64> {
split_range(headers).filter(|(range, _)| *range == "*")?.1.parse().ok()
}
fn split_range(headers: &HeaderMap) -> Option<(&str, &str)> {
let value = headers.get(header::CONTENT_RANGE)?.to_str().ok()?.trim();
let (range, total) = value.strip_prefix("bytes")?.trim().split_once('/')?;
Some((range.trim(), total.trim()))
}
fn content_length(headers: &HeaderMap) -> Option<u64> {
headers.get(header::CONTENT_LENGTH)?.to_str().ok()?.trim().parse().ok()
}
fn status_error(response: &Response) -> Error {
Error::Status { code: response.status().as_u16(), retry_after: retry_after(response.headers()) }
}
fn retry_after(headers: &HeaderMap) -> Option<Duration> {
let value = headers.get(header::RETRY_AFTER)?.to_str().ok()?.trim();
if let Ok(seconds) = value.parse() {
return Some(Duration::from_secs(seconds));
}
let at = chrono::DateTime::parse_from_rfc2822(value).ok()?;
Some((at.to_utc() - chrono::Utc::now()).to_std().unwrap_or_default())
}
/// Refuses a packed body. A `.gz` file announced as "gzip" is the file itself, a common server mistake.
fn check_encoding(headers: &HeaderMap, url: &Url) -> Result<()> {
let Some(value) = headers.get(header::CONTENT_ENCODING) else { return Ok(()) };
let encoding = value.to_str().unwrap_or("?").trim().to_ascii_lowercase();
let packed_file = || {
let path = url.path().to_ascii_lowercase();
path.ends_with(".gz")
|| path.ends_with(".tgz")
|| name::mime(headers).is_some_and(|m| matches!(m.as_str(), "application/gzip" | "application/x-gzip"))
};
match encoding.as_str() {
"" | "identity" => Ok(()),
"gzip" | "x-gzip" if packed_file() => Ok(()),
_ => Err(Error::Encoded(encoding)),
}
}
/// A web page, where `name` promises another kind of file.
fn page_instead(mime: Option<&str>, name: &str) -> bool {
let Some(ext) = name::split(name).1 else { return false };
page(mime) && name::is_file_type(ext) && !ext.eq_ignore_ascii_case("html")
}
fn page(mime: Option<&str>) -> bool {
matches!(mime, Some("text/html" | "application/xhtml+xml"))
}
/// What tells one version of a file from another.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Validators {
pub size: Option<u64>,
pub etag: Option<String>,
pub last_modified: Option<String>,
}
impl Validators {
fn of(headers: &HeaderMap, size: Option<u64>) -> Validators {
let text = |name| headers.get(name).and_then(|v| v.to_str().ok()).map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
Validators { size, etag: text(header::ETAG), last_modified: text(header::LAST_MODIFIED) }
}
/// False when anything both sides know differs.
pub fn same_file(&self, other: &Validators) -> bool {
fn agree<T: PartialEq>(a: Option<T>, b: Option<T>) -> bool {
a.is_none() || b.is_none() || a == b
}
// A proxy that packs replies turns the tag into a weak one.
fn strong(tag: &Option<String>) -> Option<&str> {
tag.as_deref().map(|t| t.strip_prefix("W/").unwrap_or(t))
}
agree(self.size, other.size)
&& agree(strong(&self.etag), strong(&other.etag))
&& agree(self.last_modified.as_ref(), other.last_modified.as_ref())
}
/// Of the same size, so maybe the same file from another server of a farm: only the bytes can tell. Servers like nginx
/// make the tag from size and date (`"5f-1982ea51dc7"`); tags that differ in the size part are another file.
pub fn maybe_same(&self, other: &Validators) -> bool {
fn size_part(tag: &Option<String>) -> Option<&str> {
let tag = tag.as_deref()?;
let (size, date) = tag.strip_prefix("W/").unwrap_or(tag).strip_prefix('"')?.strip_suffix('"')?.split_once('-')?;
let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
(hex(size) && hex(date)).then_some(size)
}
let sizes = size_part(&self.etag).zip(size_part(&other.etag)).is_none_or(|(a, b)| a.eq_ignore_ascii_case(b));
self.size.is_some() && self.size == other.size && sizes
}
/// The value for `If-Range`, which must not be a weak tag.
fn if_range(&self) -> Option<HeaderValue> {
let strong = self.etag.as_ref().filter(|t| !t.starts_with("W/"));
HeaderValue::try_from(strong.or(self.last_modified.as_ref())?).ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn headers(name: HeaderName, value: &str) -> HeaderMap {
HeaderMap::from_iter([(name, HeaderValue::try_from(value).unwrap())])
}
#[test]
fn content_ranges() {
let of = |v| ContentRange::of(&headers(header::CONTENT_RANGE, v));
assert_eq!(of("bytes 0-0/10"), Some(ContentRange { first: 0, last: 0, total: Some(10) }));
assert_eq!(of("bytes 5-9/*").unwrap().len(), 5);
for bad in ["bytes 5-4/10", "bytes 0-10/10", "bytes */10", "items 0-1/2", "bytes 0-1", "bytes -1-1/2", "0-1/2"] {
assert_eq!(of(bad), None, "{bad}");
}
assert_eq!(unsatisfied_total(&headers(header::CONTENT_RANGE, "bytes */10")), Some(10));
assert_eq!(unsatisfied_total(&headers(header::CONTENT_RANGE, "bytes 0-1/10")), None);
}
#[test]
fn retry_after_forms() {
assert_eq!(retry_after(&headers(header::RETRY_AFTER, "7")), Some(Duration::from_secs(7)));
assert_eq!(retry_after(&headers(header::RETRY_AFTER, "Sun, 06 Nov 1994 08:49:37 GMT")), Some(Duration::ZERO));
assert_eq!(retry_after(&headers(header::RETRY_AFTER, "soon")), None);
}
#[test]
fn secrets_stay_with_their_site() {
let given = [("Cookie", "a=b"), ("Authorization", "Basic x"), ("Referer", "https://p/"), ("Range", "bytes=1-2"), ("Bad name", "x")];
let given = given.map(|(k, v)| (k.to_string(), v.to_string()));
let source = Source::new("https://h/f").unwrap().with_headers(&given);
assert_eq!(source.headers.len(), 3);
assert_eq!(source.at(&Url::parse("https://h/other").unwrap()).headers.len(), 3);
for other in ["https://cdn/f", "http://h/f", "https://h:444/f"] {
let moved = source.at(&Url::parse(other).unwrap()).headers;
assert_eq!(moved.len(), 1, "{other}");
assert!(moved.contains_key(header::REFERER));
}
for bad in ["gopher://h/f", "sftp:///f", "file:///etc/passwd", "no link", "http:///"] {
assert!(matches!(Source::new(bad), Err(Error::Link)), "{bad}");
}
}
#[test]
fn pages_in_place_of_files() {
let html = Some("text/html");
assert!(page_instead(html, "a.ZIP") && page_instead(html, "a.tar.gz") && page_instead(html, "x.iso"));
for (mime, name) in [(html, "a.html"), (html, "a.php"), (html, "file"), (html, "v1.2"), (Some("application/zip"), "a.zip"), (None, "a.zip")] {
assert!(!page_instead(mime, name), "{name}");
}
}
#[test]
fn versions() {
let v = |size, etag: Option<&str>, lm: Option<&str>| Validators {
size,
etag: etag.map(String::from),
last_modified: lm.map(String::from),
};
let a = v(Some(1), Some("\"x\""), Some("d1"));
assert!(a.same_file(&v(None, Some("W/\"x\""), None)));
assert!(!a.same_file(&v(Some(2), None, None)));
assert!(!a.same_file(&v(None, Some("\"y\""), None)));
assert!(!a.same_file(&v(None, None, Some("d2"))));
assert_eq!(a.if_range().unwrap(), "\"x\"");
assert_eq!(v(None, Some("W/\"x\""), Some("d1")).if_range().unwrap(), "d1");
assert_eq!(v(None, Some("W/\"x\""), None).if_range(), None);
}
#[test]
fn farm_versions() {
let v = |size, etag: &str, lm: &str| Validators { size, etag: Some(etag.into()), last_modified: Some(lm.into()) };
let a = v(Some(9), "W/\"bd6dcd82-1982ea51dc7\"", "Mon, 21 Jul 2025 20:20:29 GMT");
let b = v(Some(9), "W/\"bd6dcd82-16f743377f5\"", "Sun, 05 Jan 2020 05:35:27 GMT");
assert!(!a.same_file(&b) && a.maybe_same(&b) && b.maybe_same(&a));
assert!(!a.maybe_same(&v(Some(8), "W/\"bd6dcd82-1\"", "x")), "another size");
assert!(!a.maybe_same(&v(Some(9), "W/\"bd6dcd83-1982ea51dc7\"", "x")), "another size in the tag");
assert!(a.maybe_same(&v(Some(9), "\"opaque\"", "x")), "only bytes can tell");
assert!(!v(None, "\"a-1\"", "x").maybe_same(&v(None, "\"a-2\"", "x")), "no size");
}
}