use std::borrow::Cow;
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use futures_io::{AsyncRead, AsyncWrite};
use hyper::body::{Body as _, Bytes, Frame, Incoming, SizeHint};
use hyper::header::{HeaderName, HeaderValue};
use hyper::http::uri::Scheme;
use hyper::{Method, Request, Response, StatusCode, Uri, Version};
use ostrya_rt as rt;
use std::pin::Pin;
#[cfg(feature = "tokio")]
use std::task::ready;
use std::task::{Context, Poll};
use crate::error::{Error, Result};
pub(crate) mod gate;
mod io;
mod tls;
use gate::{Gate, Permit};
use io::{FuturesIo, RtExecutor, RtTimer, WriteVectored};
use tls::{ClientConfigs, client_config};
pub use tls::{ClientIdentity, TlsOptions, TrustRoots};
const USER_AGENT: &str = concat!("ostrya/", env!("CARGO_PKG_VERSION"));
const IDENTITY: &str = "identity";
const CHUNKED: &str = "chunked";
const PROXY_VARIABLES: [&str; 7] = [
"http_proxy",
"https_proxy",
"HTTPS_PROXY",
"all_proxy",
"ALL_PROXY",
"no_proxy",
"NO_PROXY",
];
const PROXY_SCHEME: &str = "http://";
const REDIRECTS: [StatusCode; 5] = [
StatusCode::MOVED_PERMANENTLY,
StatusCode::FOUND,
StatusCode::SEE_OTHER,
StatusCode::TEMPORARY_REDIRECT,
StatusCode::PERMANENT_REDIRECT,
];
const AMBIGUOUS_AUTHORIZATION: &str =
"basic-auth credentials and an authorization header both set Authorization: pass one of them";
const HOST_COMES_FROM_THE_URL: &str = "the host header is set from the url the request is sent to";
const CONNECTION_HEADERS: [&str; 9] = [
"connection",
"content-length",
"expect",
"keep-alive",
"proxy-connection",
"te",
"trailer",
"transfer-encoding",
"upgrade",
];
const DRAIN_LIMIT: u64 = 64 * 1024;
const H2_STREAM_WINDOW: u32 = 2 * 1024 * 1024;
const H2_MAX_WINDOW: u32 = i32::MAX as u32;
const H2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15);
const H2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub enum Priority {
Low,
#[default]
Normal,
High,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Protocol {
Http11,
Http2,
}
#[derive(Clone, Eq, PartialEq)]
pub struct BasicAuth {
pub user: String,
pub password: String,
}
impl std::fmt::Debug for BasicAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BasicAuth")
.field("user", &self.user)
.field("password", &"<redacted>")
.finish()
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Validators {
pub etag: Option<String>,
pub last_modified: Option<String>,
}
impl Validators {
pub fn is_empty(&self) -> bool {
self.etag.is_none() && self.last_modified.is_none()
}
}
#[derive(Clone, Default)]
pub enum Proxy {
None,
#[default]
Environment,
Variables(Vec<(String, String)>),
Url(String),
}
impl std::fmt::Debug for Proxy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Proxy::None => f.write_str("None"),
Proxy::Environment => f.write_str("Environment"),
Proxy::Variables(variables) => {
let held = variables
.iter()
.map(|(name, value)| (name, without_userinfo(value)));
f.debug_tuple("Variables")
.field(&held.collect::<Vec<_>>())
.finish()
}
Proxy::Url(url) => f.debug_tuple("Url").field(&without_userinfo(url)).finish(),
}
}
}
#[derive(Clone, Debug)]
pub struct FetcherOptions {
pub mirrors: Vec<String>,
pub headers: Vec<(String, String)>,
pub basic_auth: Option<BasicAuth>,
pub tls: TlsOptions,
pub proxy: Proxy,
pub http2: bool,
pub max_retries: u32,
pub max_redirects: u32,
pub max_outstanding: usize,
pub connect_timeout: Duration,
pub progress_timeout: Duration,
pub fetch_timeout: Option<Duration>,
}
impl Default for FetcherOptions {
fn default() -> Self {
FetcherOptions {
mirrors: Vec::new(),
headers: Vec::new(),
basic_auth: None,
tls: TlsOptions::default(),
proxy: Proxy::default(),
http2: true,
max_retries: 5,
max_redirects: 10,
max_outstanding: 8,
connect_timeout: Duration::from_secs(30),
progress_timeout: Duration::from_secs(60),
fetch_timeout: Some(Duration::from_secs(300)),
}
}
}
impl FetcherOptions {
pub fn new(url: impl Into<String>) -> FetcherOptions {
FetcherOptions {
mirrors: vec![url.into()],
..FetcherOptions::default()
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Target<'a> {
Path(&'a str),
Url(&'a str),
}
impl Target<'_> {
fn as_str(&self) -> &str {
match self {
Target::Path(path) => path,
Target::Url(url) => url,
}
}
}
#[derive(Clone, Debug)]
pub struct FetchRequest<'a> {
pub target: Target<'a>,
pub priority: Priority,
pub validators: Option<&'a Validators>,
pub max_size: Option<u64>,
pub headers: &'a [(String, String)],
pub basic_auth: Option<&'a BasicAuth>,
pub allow_cleartext_credentials: bool,
}
impl<'a> FetchRequest<'a> {
pub fn path(path: &'a str) -> FetchRequest<'a> {
FetchRequest::for_target(Target::Path(path))
}
pub fn url(url: &'a str) -> FetchRequest<'a> {
FetchRequest::for_target(Target::Url(url))
}
fn for_target(target: Target<'a>) -> FetchRequest<'a> {
FetchRequest {
target,
priority: Priority::default(),
validators: None,
max_size: None,
headers: &[],
basic_auth: None,
allow_cleartext_credentials: false,
}
}
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Fetched {
Body(Body),
NotModified,
}
#[derive(Clone, Debug)]
struct Mirror {
origin: Origin,
authority: HeaderValue,
prefix: String,
base: String,
}
impl Mirror {
fn destination(&self, path: &str) -> Destination {
Destination {
origin: self.origin.clone(),
authority: self.authority.clone(),
url: format!(
"{}{}/{}",
self.prefix,
self.base,
path.trim_start_matches('/')
),
path_at: self.prefix.len(),
}
}
}
#[derive(Clone, Debug)]
struct Destination {
origin: Origin,
authority: HeaderValue,
url: String,
path_at: usize,
}
impl Destination {
fn url(&self) -> &str {
&self.url
}
fn target(&self) -> &str {
&self.url[self.path_at..]
}
fn origin_url(&self) -> &str {
&self.url[..self.path_at]
}
}
#[derive(Debug)]
enum Route<'a> {
Mirrors(&'a str),
One(Destination),
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct Origin {
tls: bool,
host: String,
port: u16,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct PoolKey {
origin: Origin,
identity: bool,
proxied: bool,
}
#[derive(Debug)]
struct ProxyEndpoint {
endpoint: Origin,
credential: Option<HeaderValue>,
named: String,
}
#[derive(Debug)]
struct Exemption {
host: String,
port: Option<u16>,
}
impl Exemption {
fn matches(&self, origin: &Origin) -> bool {
if self.port.is_some_and(|port| port != origin.port) {
return false;
}
let host = origin.host.as_bytes();
let entry = self.host.as_bytes();
if host.eq_ignore_ascii_case(entry) {
return true;
}
host.len() > entry.len()
&& host[host.len() - entry.len() - 1] == b'.'
&& host[host.len() - entry.len()..].eq_ignore_ascii_case(entry)
}
}
#[derive(Debug, Default)]
struct Proxies {
http: Option<Arc<ProxyEndpoint>>,
https: Option<Arc<ProxyEndpoint>>,
exempt_all: bool,
exempt: Vec<Exemption>,
}
impl Proxies {
fn via(&self, origin: &Origin) -> Via<'_> {
let proxy = if origin.tls { &self.https } else { &self.http };
let Some(proxy) = proxy.as_deref() else {
return Via::Direct;
};
if self.exempt_all || self.exempt.iter().any(|entry| entry.matches(origin)) {
return Via::Direct;
}
if origin.tls {
Via::Tunnel(proxy)
} else {
Via::Absolute(proxy)
}
}
}
#[derive(Clone, Copy, Debug)]
enum Via<'a> {
Direct,
Absolute(&'a ProxyEndpoint),
Tunnel(&'a ProxyEndpoint),
}
struct NoBody;
impl hyper::body::Body for NoBody {
type Data = Bytes;
type Error = std::convert::Infallible;
fn poll_frame(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<std::result::Result<Frame<Bytes>, Self::Error>>> {
Poll::Ready(None)
}
fn is_end_stream(&self) -> bool {
true
}
fn size_hint(&self) -> SizeHint {
SizeHint::with_exact(0)
}
}
type H1Sender = hyper::client::conn::http1::SendRequest<NoBody>;
type H2Sender = hyper::client::conn::http2::SendRequest<NoBody>;
enum Sender {
H1(H1Sender),
H2(H2Sender),
}
#[derive(Default)]
struct PoolEntry {
h2: Option<H2Sender>,
h1: Vec<H1Sender>,
}
struct Inner {
mirrors: Vec<Mirror>,
headers: Vec<(HeaderName, HeaderValue)>,
tls: ClientConfigs,
has_trust_anchors: bool,
client_identity: bool,
proxies: Proxies,
max_retries: u32,
max_redirects: u32,
connect_timeout: Duration,
progress_timeout: Duration,
fetch_timeout: Option<Duration>,
gate: Arc<Gate>,
h2_connection_window: u32,
pool: Mutex<HashMap<PoolKey, PoolEntry>>,
}
fn h2_connection_window(max_outstanding: usize) -> u32 {
u32::try_from(max_outstanding)
.unwrap_or(u32::MAX)
.saturating_mul(H2_STREAM_WINDOW)
.min(H2_MAX_WINDOW)
}
enum Failure {
Retry(Error),
Fatal(Error),
}
#[derive(Clone)]
pub struct Fetcher {
inner: Arc<Inner>,
}
impl std::fmt::Debug for Fetcher {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Fetcher")
.field("mirrors", &self.inner.mirrors)
.finish_non_exhaustive()
}
}
impl Fetcher {
pub async fn new(options: FetcherOptions) -> Result<Fetcher> {
let mirrors = options
.mirrors
.iter()
.map(|url| parse_mirror(url))
.collect::<Result<Vec<_>>>()?;
let cleartext = options
.mirrors
.iter()
.zip(&mirrors)
.find(|(_, mirror)| !mirror.origin.tls)
.map(|(url, _)| url.as_str());
if options.basic_auth.is_some()
&& let Some(url) = cleartext
{
return Err(Error::Fetch(format!(
"basic-auth credentials would reach the http mirror {url} in the clear: \
use https mirrors or drop the credentials"
)));
}
let mut headers = vec![
(
hyper::header::USER_AGENT,
HeaderValue::from_static(USER_AGENT),
),
(
hyper::header::ACCEPT_ENCODING,
HeaderValue::from_static(IDENTITY),
),
];
let mut base = headers.len();
for (name, value) in &options.headers {
let name = HeaderName::try_from(name.as_str())
.map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
if name == hyper::header::HOST {
return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
}
if is_connection_header(&name) {
return Err(connection_header_refused(&name));
}
if name == hyper::header::AUTHORIZATION && options.basic_auth.is_some() {
return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
}
if is_credential(&name)
&& let Some(url) = cleartext
{
return Err(Error::Fetch(format!(
"the {name} header carries credentials, which the http mirror {url} \
would receive in the clear: use https mirrors or drop the header"
)));
}
let value = HeaderValue::try_from(value.as_str())
.map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
if let Some(at) = headers[..base].iter().position(|(held, _)| *held == name) {
headers.remove(at);
base -= 1;
}
headers.push((name, value));
}
if let Some(auth) = &options.basic_auth {
headers.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
}
let proxies = resolve_proxy(&options.proxy)?;
let max_outstanding = options.max_outstanding.max(1);
let https = mirrors.is_empty() || mirrors.iter().any(|mirror| mirror.origin.tls);
let tls = client_config(&options.tls, options.http2, https).await?;
Ok(Fetcher {
inner: Arc::new(Inner {
mirrors,
headers,
has_trust_anchors: tls.has_trust_anchors,
client_identity: options.tls.client_identity.is_some(),
proxies,
tls,
max_retries: options.max_retries,
max_redirects: options.max_redirects,
connect_timeout: options.connect_timeout,
progress_timeout: options.progress_timeout,
fetch_timeout: options.fetch_timeout,
gate: Arc::new(Gate::new(max_outstanding)),
h2_connection_window: h2_connection_window(max_outstanding),
pool: Mutex::new(HashMap::new()),
}),
})
}
pub async fn fetch(&self, request: FetchRequest<'_>) -> Result<Fetched> {
let route = self.route(request.target)?;
let headers = merge_headers(&self.inner.headers, request.headers, request.basic_auth)?;
if !request.allow_cleartext_credentials {
self.check_cleartext(&route, &headers)?;
}
self.check_trust_anchors(&route)?;
let permit = self.inner.gate.acquire(request.priority).await;
let rounds = self.rounds(&request, &route, &headers, permit);
let Some(limit) = self.inner.fetch_timeout else {
return rounds.await;
};
match within(limit, rounds).await {
Some(result) => result,
None => Err(Error::Fetch(format!(
"fetch of {} timed out after {limit:?}",
request.target.as_str()
))),
}
}
fn route<'a>(&self, target: Target<'a>) -> Result<Route<'a>> {
match target {
Target::Url(url) => Ok(Route::One(parse_url(url)?)),
Target::Path(path) => {
check_path(path)?;
if self.inner.mirrors.is_empty() {
return Err(Error::Fetch(format!(
"fetch of the path {path} has nowhere to go: no mirror is configured"
)));
}
Ok(Route::Mirrors(path))
}
}
}
fn check_cleartext(
&self,
route: &Route<'_>,
headers: &[(HeaderName, HeaderValue)],
) -> Result<()> {
if !headers.iter().any(|(name, _)| is_credential(name)) {
return Ok(());
}
let Some(origin) = self.matching_origin(route, |origin| !origin.tls) else {
return Ok(());
};
Err(Error::Fetch(format!(
"the request carries credentials, which the cleartext origin {origin} would receive \
in the clear: fetch over https, drop the credentials, or set \
FetchRequest::allow_cleartext_credentials"
)))
}
fn check_trust_anchors(&self, route: &Route<'_>) -> Result<()> {
if self.inner.has_trust_anchors {
return Ok(());
}
let Some(origin) = self.matching_origin(route, |origin| origin.tls) else {
return Ok(());
};
Err(no_trust_anchors(origin))
}
fn matching_origin<'a>(
&'a self,
route: &'a Route<'_>,
wanted: fn(&Origin) -> bool,
) -> Option<&'a str> {
match route {
Route::Mirrors(_) => self
.inner
.mirrors
.iter()
.find(|mirror| wanted(&mirror.origin))
.map(|mirror| mirror.prefix.as_str()),
Route::One(destination) => {
wanted(&destination.origin).then(|| destination.origin_url())
}
}
}
async fn rounds(
&self,
request: &FetchRequest<'_>,
route: &Route<'_>,
headers: &[(HeaderName, HeaderValue)],
permit: Permit,
) -> Result<Fetched> {
let destination_count = match route {
Route::Mirrors(_) => self.inner.mirrors.len(),
Route::One(_) => 1,
};
let mut settled = vec![false; destination_count];
let mut reported: Option<Error> = None;
let mut definitive = false;
let mut round = 0;
loop {
let mut retryable = false;
for (position, settled) in settled.iter_mut().enumerate() {
if *settled {
continue;
}
let destination = match route {
Route::Mirrors(path) => {
Cow::Owned(self.inner.mirrors[position].destination(path))
}
Route::One(destination) => Cow::Borrowed(destination),
};
let failure = match self.attempt(&destination, request, headers).await {
Ok(Attempted::Body(mut body)) => {
body.permit = Some(permit);
return Ok(Fetched::Body(body));
}
Ok(Attempted::NotModified) => return Ok(Fetched::NotModified),
Err(failure) => failure,
};
match failure {
Failure::Retry(e) => {
retryable = true;
if reported.is_none() {
reported = Some(e);
}
}
Failure::Fatal(e) => {
*settled = true;
if !definitive {
reported = Some(e);
definitive = true;
}
}
}
}
if !retryable || round >= self.inner.max_retries {
return Err(reported.expect("a failed round holds a failure"));
}
round += 1;
rt::Timer::after(backoff(round)).await;
}
}
async fn attempt(
&self,
destination: &Destination,
request: &FetchRequest<'_>,
headers: &[(HeaderName, HeaderValue)],
) -> std::result::Result<Attempted, Failure> {
let named = &destination.origin;
let mut hop = Cow::Borrowed(destination);
let mut headers = Cow::Borrowed(headers);
let mut followed = 0u32;
let progress_timeout = self.inner.progress_timeout;
let drain_until = Instant::now() + progress_timeout;
loop {
let via = self.inner.proxies.via(&hop.origin);
let key = PoolKey {
origin: match via {
Via::Absolute(proxy) => proxy.endpoint.clone(),
Via::Direct | Via::Tunnel(_) => hop.origin.clone(),
},
identity: self.presents_identity(&hop.origin, named),
proxied: matches!(via, Via::Absolute(_)),
};
let url = hop.url();
let (response, protocol, reuse) = self.send(&hop, &key, via, request, &headers).await?;
let status = response.status();
if status == StatusCode::NOT_MODIFIED {
if let Some(sender) = reuse {
self.inner.put_h1(&key, sender);
}
return Ok(Attempted::NotModified);
}
if is_redirect(status) && self.inner.max_redirects > 0 {
let location = response
.headers()
.get(hyper::header::LOCATION)
.and_then(|value| resolve_location(url, value));
let Some(location) = location else {
let failure = classify(status, url);
self.discard(&key, response, reuse, drain_until).await;
return Err(failure);
};
if followed >= self.inner.max_redirects {
self.discard(&key, response, reuse, drain_until).await;
return Err(Failure::Fatal(Error::RedirectLimit {
url: url.to_string(),
hops: followed,
}));
}
let next = redirect_destination(&hop, &location);
self.discard(&key, response, reuse, drain_until).await;
let next = next.map_err(Failure::Fatal)?;
if next.origin.tls && !self.inner.has_trust_anchors {
return Err(Failure::Fatal(no_trust_anchors(next.origin_url())));
}
if next.origin != *named && headers.iter().any(|(name, _)| is_credential(name)) {
let scoped = headers
.iter()
.filter(|(name, _)| !is_credential(name))
.cloned()
.collect::<Vec<_>>();
headers = Cow::Owned(scoped);
}
hop = Cow::Owned(next);
followed += 1;
continue;
}
if status != StatusCode::OK {
let failure = classify(status, url);
self.discard(&key, response, reuse, drain_until).await;
return Err(failure);
}
if let Some(encoding) = declared_coding(response.headers()) {
let url = url.to_string();
self.discard(&key, response, reuse, drain_until).await;
return Err(Failure::Fatal(Error::ContentEncoded { url, encoding }));
}
let validators = read_validators(response.headers());
let content_length = content_length(response.headers());
if let (Some(limit), Some(length)) = (request.max_size, content_length)
&& length > limit
{
self.discard(&key, response, reuse, drain_until).await;
return Err(Failure::Fatal(Error::FetchTooLarge { limit }));
}
let protocol = match response.version() {
Version::HTTP_2 => Protocol::Http2,
_ => protocol,
};
return Ok(Attempted::Body(Body {
incoming: response.into_body(),
chunk: Bytes::new(),
received: 0,
max_size: request.max_size,
validators,
content_length,
protocol,
inner: self.inner.clone(),
key,
reuse,
permit: None,
done: false,
failed: None,
deadline: rt::Deadline::new(progress_timeout),
waiting: false,
}));
}
}
async fn send(
&self,
hop: &Destination,
key: &PoolKey,
via: Via<'_>,
request: &FetchRequest<'_>,
headers: &[(HeaderName, HeaderValue)],
) -> std::result::Result<(Response<Incoming>, Protocol, Option<H1Sender>), Failure> {
let url = hop.url();
let origin = &key.origin;
let connect_timeout = self.inner.connect_timeout;
let progress_timeout = self.inner.progress_timeout;
let sender = match self.inner.take_conn(key) {
Some(sender) => sender,
None => {
let opened = within(connect_timeout, Box::pin(self.connect(key, via))).await;
match opened {
Some(result) => result?,
None => {
return Err(Failure::Retry(Error::Fetch(match via {
Via::Direct => format!(
"connect to {}:{} timed out after {connect_timeout:?}",
origin.host, origin.port
),
Via::Absolute(proxy) | Via::Tunnel(proxy) => format!(
"connect to the proxy {} timed out after {connect_timeout:?}",
proxy.named
),
})));
}
}
}
};
match sender {
Sender::H1(mut sender) => {
let http_request = self
.build_request(hop, request, headers, Protocol::Http11, via)
.map_err(Failure::Fatal)?;
let sent = within(progress_timeout, async {
sender.ready().await?;
sender.send_request(http_request).await
})
.await;
let response = match sent {
Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
None => return Err(Failure::Retry(stalled(url, progress_timeout))),
};
Ok((response, Protocol::Http11, Some(sender)))
}
Sender::H2(mut sender) => {
let http_request = self
.build_request(hop, request, headers, Protocol::Http2, via)
.map_err(Failure::Fatal)?;
let sent = within(progress_timeout, async {
sender.ready().await?;
sender.send_request(http_request).await
})
.await;
let response = match sent {
Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
None => return Err(Failure::Retry(stalled(url, progress_timeout))),
};
Ok((response, Protocol::Http2, None))
}
}
}
fn presents_identity(&self, hop: &Origin, named: &Origin) -> bool {
self.inner.client_identity && hop.tls && hop == named
}
async fn discard(
&self,
key: &PoolKey,
response: Response<Incoming>,
reuse: Option<H1Sender>,
drain_until: Instant,
) {
let Some(sender) = reuse else { return };
if content_length(response.headers()).is_none_or(|length| length > DRAIN_LIMIT) {
return;
}
let budget = drain_until.saturating_duration_since(Instant::now());
if budget.is_zero() {
return;
}
let mut body = response.into_body();
let drained = within(budget, async {
loop {
let frame = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
match frame {
Some(Ok(_)) => continue,
Some(Err(_)) => return false,
None => return true,
}
}
})
.await;
if drained == Some(true) {
self.inner.put_h1(key, sender);
}
}
fn build_request(
&self,
destination: &Destination,
request: &FetchRequest<'_>,
headers: &[(HeaderName, HeaderValue)],
protocol: Protocol,
via: Via<'_>,
) -> Result<Request<NoBody>> {
let absolute = protocol == Protocol::Http2 || matches!(via, Via::Absolute(_));
let url = if absolute {
destination.url()
} else {
destination.target()
};
let uri =
Uri::try_from(url).map_err(|e| Error::Fetch(format!("invalid url {url}: {e}")))?;
let mut builder = Request::builder().method(Method::GET).uri(uri);
if protocol == Protocol::Http11 {
builder = builder.header(hyper::header::HOST, &destination.authority);
}
for (name, value) in headers {
builder = builder.header(name, value);
}
if let Via::Absolute(proxy) = via
&& let Some(credential) = &proxy.credential
&& !headers
.iter()
.any(|(name, _)| *name == hyper::header::PROXY_AUTHORIZATION)
{
builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
}
if let Some(validators) = request.validators {
if let Some(etag) = &validators.etag {
builder = builder.header(hyper::header::IF_NONE_MATCH, etag);
}
if let Some(last_modified) = &validators.last_modified {
builder = builder.header(hyper::header::IF_MODIFIED_SINCE, last_modified);
}
}
builder
.body(NoBody)
.map_err(|e| Error::Fetch(format!("invalid request for {url}: {e}")))
}
async fn connect(&self, key: &PoolKey, via: Via<'_>) -> std::result::Result<Sender, Failure> {
let origin = &key.origin;
let endpoint = match via {
Via::Tunnel(proxy) => &proxy.endpoint,
Via::Direct | Via::Absolute(_) => origin,
};
let tcp = rt::TcpStream::connect(&endpoint.host, endpoint.port)
.await
.map_err(|e| {
Failure::Retry(Error::Fetch(match via {
Via::Direct => {
format!("connect to {}:{} failed: {e}", endpoint.host, endpoint.port)
}
Via::Absolute(proxy) | Via::Tunnel(proxy) => {
format!("connect to the proxy {} failed: {e}", proxy.named)
}
}))
})?;
if !origin.tls {
return self
.handshake_h1(key, FuturesIo::new(tcp))
.await
.map_err(Failure::Retry);
}
let tcp = match via {
Via::Tunnel(proxy) => self.tunnel(proxy, origin, tcp).await?,
Via::Direct | Via::Absolute(_) => tcp,
};
let server_name =
rustls::pki_types::ServerName::try_from(origin.host.clone()).map_err(|e| {
Failure::Retry(Error::Fetch(format!(
"invalid server name {}: {e}",
origin.host
)))
})?;
let config = if key.identity {
&self.inner.tls.with_identity
} else {
&self.inner.tls.without_identity
};
let stream = futures_rustls::TlsConnector::from(config.clone())
.connect(server_name, tcp)
.await
.map_err(|e| {
Failure::Retry(Error::Fetch(format!(
"tls handshake with {} failed: {e}",
origin.host
)))
})?;
let h2 = stream.get_ref().1.alpn_protocol() == Some(b"h2");
let io = FuturesIo::new(stream);
if h2 {
self.handshake_h2(key, io).await.map_err(Failure::Retry)
} else {
self.handshake_h1(key, io).await.map_err(Failure::Retry)
}
}
async fn tunnel(
&self,
proxy: &ProxyEndpoint,
origin: &Origin,
tcp: rt::TcpStream,
) -> std::result::Result<rt::TcpStream, Failure> {
let refused = |what: String| Failure::Retry(Error::Fetch(what));
let authority = connect_authority(origin);
let host = HeaderValue::try_from(&authority).map_err(|_| {
Failure::Fatal(Error::Fetch(format!(
"the proxy {} cannot be asked to reach {authority}, which is not a usable host",
proxy.named
)))
})?;
let mut builder = Request::builder()
.method(Method::CONNECT)
.uri(&authority)
.header(hyper::header::HOST, host);
if let Some(credential) = &proxy.credential {
builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
}
let request = builder.body(NoBody).map_err(|e| {
refused(format!(
"the connect request to the proxy {} for {authority} is invalid: {e}",
proxy.named
))
})?;
let (mut sender, connection) = hyper::client::conn::http1::handshake(FuturesIo::new(tcp))
.await
.map_err(|e| {
refused(format!(
"http/1.1 handshake with the proxy {} failed: {e}",
proxy.named
))
})?;
drop(rt::spawn(async move {
let _ = connection.with_upgrades().await;
}));
let response = async {
sender.ready().await?;
sender.send_request(request).await
}
.await
.map_err(|e| {
refused(format!(
"connect to {authority} through the proxy {} failed: {e}",
proxy.named
))
})?;
let status = response.status();
if !status.is_success() {
let message = format!(
"the proxy {} answered the connect to {authority} with {}",
proxy.named,
status.as_u16()
);
return Err(match status {
StatusCode::PROXY_AUTHENTICATION_REQUIRED => Failure::Fatal(Error::Fetch(message)),
_ => Failure::Retry(Error::Fetch(message)),
});
}
let upgraded = hyper::upgrade::on(response).await.map_err(|e| {
refused(format!(
"the proxy {} accepted the connect to {authority} without tunneling it: {e}",
proxy.named
))
})?;
let parts = upgraded
.downcast::<FuturesIo<rt::TcpStream>>()
.map_err(|_| {
refused(format!(
"the tunnel through the proxy {} to {authority} is not the socket it was \
opened over",
proxy.named
))
})?;
if !parts.read_buf.is_empty() {
return Err(refused(format!(
"the proxy {} sent {} bytes after the connect to {authority}, which nothing may \
follow",
proxy.named,
parts.read_buf.len()
)));
}
Ok(parts.io.into_inner())
}
async fn handshake_h1<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
where
S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
{
let (sender, connection) =
hyper::client::conn::http1::handshake(io)
.await
.map_err(|e| {
Error::Fetch(format!(
"http/1.1 handshake with {} failed: {e}",
key.origin.host
))
})?;
drop(rt::spawn(async move {
let _ = connection.await;
}));
Ok(Sender::H1(sender))
}
async fn handshake_h2<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
where
S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
{
let (sender, connection) = hyper::client::conn::http2::Builder::new(RtExecutor)
.timer(RtTimer)
.initial_stream_window_size(H2_STREAM_WINDOW)
.initial_connection_window_size(self.inner.h2_connection_window)
.keep_alive_interval(H2_KEEP_ALIVE_INTERVAL)
.keep_alive_timeout(H2_KEEP_ALIVE_TIMEOUT)
.handshake(io)
.await
.map_err(|e| {
Error::Fetch(format!(
"http/2 handshake with {} failed: {e}",
key.origin.host
))
})?;
drop(rt::spawn(async move {
let _ = connection.await;
}));
self.inner.put_h2(key, sender.clone());
Ok(Sender::H2(sender))
}
}
impl Inner {
fn take_conn(&self, key: &PoolKey) -> Option<Sender> {
let mut pool = self.pool.lock().expect("fetcher pool mutex");
let entry = pool.get_mut(key)?;
if let Some(h2) = &entry.h2 {
if h2.is_closed() {
entry.h2 = None;
} else {
return Some(Sender::H2(h2.clone()));
}
}
while let Some(h1) = entry.h1.pop() {
if !h1.is_closed() {
return Some(Sender::H1(h1));
}
}
None
}
fn put_h1(&self, key: &PoolKey, sender: H1Sender) {
if sender.is_closed() {
return;
}
let mut pool = self.pool.lock().expect("fetcher pool mutex");
if let Some(entry) = pool.get_mut(key) {
entry.h1.push(sender);
return;
}
pool.entry(key.clone()).or_default().h1.push(sender);
}
fn put_h2(&self, key: &PoolKey, sender: H2Sender) {
let mut pool = self.pool.lock().expect("fetcher pool mutex");
if let Some(entry) = pool.get_mut(key) {
match &entry.h2 {
Some(pooled) if !pooled.is_closed() => {}
_ => entry.h2 = Some(sender),
}
return;
}
pool.entry(key.clone()).or_default().h2 = Some(sender);
}
}
#[allow(clippy::large_enum_variant)]
enum Attempted {
Body(Body),
NotModified,
}
struct Failed {
kind: std::io::ErrorKind,
message: String,
}
impl Failed {
fn error(&self) -> std::io::Error {
std::io::Error::new(self.kind, self.message.clone())
}
}
pub struct Body {
incoming: Incoming,
chunk: Bytes,
received: u64,
max_size: Option<u64>,
validators: Validators,
content_length: Option<u64>,
protocol: Protocol,
inner: Arc<Inner>,
key: PoolKey,
reuse: Option<H1Sender>,
permit: Option<Permit>,
done: bool,
failed: Option<Failed>,
deadline: rt::Deadline,
waiting: bool,
}
impl std::fmt::Debug for Body {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Body")
.field("protocol", &self.protocol)
.field("content_length", &self.content_length)
.field("received", &self.received)
.finish_non_exhaustive()
}
}
impl Body {
pub fn validators(&self) -> &Validators {
&self.validators
}
pub fn content_length(&self) -> Option<u64> {
self.content_length
}
pub fn protocol(&self) -> Protocol {
self.protocol
}
pub fn received(&self) -> u64 {
self.received
}
fn fail(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
let failed = Failed { kind, message };
let error = failed.error();
self.failed = Some(failed);
error
}
}
impl AsyncRead for Body {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
let me = self.get_mut();
if let Some(failed) = &me.failed {
return Poll::Ready(Err(failed.error()));
}
loop {
if !me.chunk.is_empty() {
let n = me.chunk.len().min(buf.len());
buf[..n].copy_from_slice(&me.chunk[..n]);
me.chunk = me.chunk.slice(n..);
return Poll::Ready(Ok(n));
}
if me.done {
return Poll::Ready(Ok(0));
}
let frame = match Pin::new(&mut me.incoming).poll_frame(cx) {
Poll::Ready(frame) => frame,
Poll::Pending => {
if !me.waiting {
me.deadline.restart();
me.waiting = true;
}
return match me.deadline.poll_expired(cx) {
Poll::Ready(()) => {
let window = me.deadline.window();
Poll::Ready(Err(me.fail(
std::io::ErrorKind::TimedOut,
format!("fetched body delivered nothing for {window:?}"),
)))
}
Poll::Pending => Poll::Pending,
};
}
};
match frame {
Some(Ok(frame)) => {
me.waiting = false;
if let Ok(data) = frame.into_data() {
me.received += data.len() as u64;
if let Some(limit) = me.max_size
&& me.received > limit
{
return Poll::Ready(Err(me.fail(
std::io::ErrorKind::FileTooLarge,
format!("fetched body exceeds the {limit}-byte cap"),
)));
}
me.chunk = data;
}
}
Some(Err(e)) => {
let message = match std::error::Error::source(&e) {
Some(cause) => format!("{e}: {cause}"),
None => e.to_string(),
};
return Poll::Ready(Err(me.fail(std::io::ErrorKind::Other, message)));
}
None => {
me.done = true;
if let Some(sender) = me.reuse.take() {
me.inner.put_h1(&me.key, sender);
}
me.permit = None;
return Poll::Ready(Ok(0));
}
}
}
}
}
#[cfg(feature = "tokio")]
impl rt::tokio_io::AsyncRead for Body {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut rt::tokio_io::ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
let unfilled = buf.initialize_unfilled();
let n = ready!(AsyncRead::poll_read(self, cx, unfilled))?;
buf.advance(n);
Poll::Ready(Ok(()))
}
}
fn is_credential(name: &HeaderName) -> bool {
*name == hyper::header::AUTHORIZATION
|| *name == hyper::header::PROXY_AUTHORIZATION
|| *name == hyper::header::COOKIE
}
fn is_connection_header(name: &HeaderName) -> bool {
CONNECTION_HEADERS.contains(&name.as_str())
}
fn connection_header_refused(name: &HeaderName) -> Error {
Error::Fetch(format!(
"the {name} header is set by the connection layer, which frames the request and \
holds its connection: drop the header"
))
}
fn check_path(path: &str) -> Result<()> {
if let Some(at) = path.find(['?', '#']) {
let found = &path[at..=at];
return Err(Error::Fetch(format!(
"fetch path {path} carries {found}: a path holds no query and no fragment"
)));
}
Ok(())
}
fn merge_headers<'a>(
fetcher: &'a [(HeaderName, HeaderValue)],
extra: &[(String, String)],
basic_auth: Option<&BasicAuth>,
) -> Result<Cow<'a, [(HeaderName, HeaderValue)]>> {
if extra.is_empty() && basic_auth.is_none() {
return Ok(Cow::Borrowed(fetcher));
}
let mut added = Vec::with_capacity(extra.len() + usize::from(basic_auth.is_some()));
for (name, value) in extra {
let name = HeaderName::try_from(name.as_str())
.map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
if name == hyper::header::HOST {
return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
}
if is_connection_header(&name) {
return Err(connection_header_refused(&name));
}
if name == hyper::header::AUTHORIZATION && basic_auth.is_some() {
return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
}
let value = HeaderValue::try_from(value.as_str())
.map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
added.push((name, value));
}
if let Some(auth) = basic_auth {
added.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
}
let mut headers = Vec::with_capacity(fetcher.len() + added.len());
headers.extend(
fetcher
.iter()
.filter(|(name, _)| !added.iter().any(|(replaced, _)| replaced == name))
.cloned(),
);
headers.extend(added);
Ok(Cow::Owned(headers))
}
fn resolve_proxy(proxy: &Proxy) -> Result<Proxies> {
match proxy {
Proxy::None => Ok(Proxies::default()),
Proxy::Environment => resolve_variables(&environment()),
Proxy::Variables(variables) => resolve_variables(variables),
Proxy::Url(url) => {
let endpoint = Arc::new(parse_proxy(url)?);
Ok(Proxies {
http: Some(endpoint.clone()),
https: Some(endpoint),
exempt_all: false,
exempt: Vec::new(),
})
}
}
}
fn environment() -> Vec<(String, String)> {
PROXY_VARIABLES
.iter()
.filter_map(|name| {
let value = std::env::var(name).ok()?;
(!value.is_empty()).then(|| ((*name).to_owned(), value))
})
.collect()
}
fn resolve_variables(variables: &[(String, String)]) -> Result<Proxies> {
let all = variable(variables, "all_proxy", Some("ALL_PROXY"));
let http = variable(variables, "http_proxy", None);
let https = variable(variables, "https_proxy", Some("HTTPS_PROXY"));
let mut endpoints: Vec<(&str, Arc<ProxyEndpoint>)> = Vec::new();
for url in [all, http, https].into_iter().flatten() {
if !endpoints.iter().any(|(named, _)| *named == url) {
endpoints.push((url, Arc::new(parse_proxy(url)?)));
}
}
let parsed = |url: Option<&str>| {
url.and_then(|url| endpoints.iter().find(|(named, _)| *named == url))
.map(|(_, endpoint)| endpoint.clone())
};
let (http, https) = (parsed(http.or(all)), parsed(https.or(all)));
let mut exempt_all = false;
let mut exempt = Vec::new();
for entry in variable(variables, "no_proxy", Some("NO_PROXY"))
.unwrap_or_default()
.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
{
if entry == "*" {
exempt_all = true;
continue;
}
exempt.extend(parse_exemption(entry));
}
Ok(Proxies {
http,
https,
exempt_all,
exempt,
})
}
fn variable<'a>(
variables: &'a [(String, String)],
lower: &str,
upper: Option<&str>,
) -> Option<&'a str> {
let held = |name: &str| {
variables
.iter()
.find(|(held, value)| held == name && !value.is_empty())
.map(|(_, value)| value.as_str())
};
held(lower).or_else(|| upper.and_then(held))
}
fn parse_exemption(entry: &str) -> Option<Exemption> {
let (host, port) = match entry
.strip_prefix('[')
.and_then(|rest| rest.split_once(']'))
{
Some((inside, rest)) => (inside, rest.strip_prefix(':')),
None => match entry.split_once(':') {
Some((host, port)) if !port.contains(':') => (host, Some(port)),
_ => (entry, None),
},
};
let named = |host: &str| host.strip_prefix('.').unwrap_or(host).to_ascii_lowercase();
let (host, port) = match port.map(str::parse::<u16>) {
Some(Ok(port)) => (named(host), Some(port)),
Some(Err(_)) => (named(entry), None),
None => (named(host), None),
};
(!host.is_empty()).then_some(Exemption { host, port })
}
fn parse_proxy(url: &str) -> Result<ProxyEndpoint> {
let refused = |what: &str| {
Error::Unsupported(format!(
"proxy url {}: {what}",
without_userinfo(url.trim())
))
};
let url = url.trim();
if !url
.get(..PROXY_SCHEME.len())
.is_some_and(|scheme| scheme.eq_ignore_ascii_case(PROXY_SCHEME))
{
return Err(refused("a proxy is reached over http://host[:port] alone"));
}
if url.contains('#') {
return Err(refused("a proxy url carries no fragment"));
}
let uri = Uri::try_from(url).map_err(|e| refused(&format!("invalid url: {e}")))?;
if let Some(query) = uri.query() {
return Err(refused(&format!(
"a proxy url carries no query string, and this one carries ?{query}"
)));
}
if !matches!(uri.path(), "" | "/") {
return Err(refused(&format!(
"a proxy url carries no path, and this one carries {}",
uri.path()
)));
}
let literal = uri.host().ok_or_else(|| refused("the url has no host"))?;
let authority = uri
.authority()
.expect("a url holding a host holds an authority")
.as_str();
let credential = match authority.rsplit_once('@') {
Some((userinfo, _)) => Some(proxy_credential(userinfo).ok_or_else(|| {
refused(
"the userinfo is not a percent-encoded user name and password the proxy can be \
sent",
)
})?),
None => None,
};
let host = literal
.strip_prefix('[')
.and_then(|inner| inner.strip_suffix(']'))
.unwrap_or(literal)
.to_ascii_lowercase();
let port_text = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host)
.strip_prefix(literal)
.and_then(|rest| rest.strip_prefix(':'));
let port = match (uri.port_u16(), port_text) {
(Some(port), _) => port,
(None, None) => 80,
(None, Some(text)) => {
return Err(refused(&format!(
"the port {text:?} is not a number from 0 to 65535"
)));
}
};
let named = if port == 80 {
format!("{PROXY_SCHEME}{literal}")
} else {
format!("{PROXY_SCHEME}{literal}:{port}")
};
Ok(ProxyEndpoint {
endpoint: Origin {
tls: false,
host,
port,
},
credential,
named,
})
}
fn proxy_credential(userinfo: &str) -> Option<HeaderValue> {
let (user, password) = userinfo.split_once(':').unwrap_or((userinfo, ""));
let field = |text: &str| String::from_utf8(percent_decode(text)?).ok();
basic_auth_value(&BasicAuth {
user: field(user)?,
password: field(password)?,
})
.ok()
}
fn percent_decode(field: &str) -> Option<Vec<u8>> {
let bytes = field.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut at = 0;
while at < bytes.len() {
if bytes[at] != b'%' {
decoded.push(bytes[at]);
at += 1;
continue;
}
let escape = bytes.get(at + 1..at + 3)?;
if !escape.iter().all(u8::is_ascii_hexdigit) {
return None;
}
let text = std::str::from_utf8(escape).ok()?;
decoded.push(u8::from_str_radix(text, 16).ok()?);
at += 3;
}
Some(decoded)
}
fn connect_authority(origin: &Origin) -> String {
if origin.host.contains(':') {
format!("[{}]:{}", origin.host, origin.port)
} else {
format!("{}:{}", origin.host, origin.port)
}
}
fn basic_auth_value(auth: &BasicAuth) -> Result<HeaderValue> {
let encoded =
ostrya_core::base64::encode(format!("{}:{}", auth.user, auth.password).as_bytes());
HeaderValue::try_from(format!("Basic {encoded}"))
.map_err(|_| Error::Fetch("invalid basic-auth credentials".into()))
}
fn parse_authority(url: &str, credentials: &str) -> Result<(Uri, Origin, String)> {
let scheme = url
.split_once("://")
.map(|(scheme, _)| scheme)
.ok_or_else(|| {
Error::Fetch(format!(
"url {} is not an absolute http or https url",
without_userinfo(url)
))
})?;
let tls = match scheme {
_ if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
_ if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
other => {
return Err(Error::Unsupported(format!(
"fetch url scheme {other}: only http and https are fetched"
)));
}
};
let scheme = if tls { "https" } else { "http" };
let uri = Uri::try_from(url)
.map_err(|e| Error::Fetch(format!("invalid url {}: {e}", without_userinfo(url))))?;
let literal = uri
.host()
.ok_or_else(|| Error::Fetch(format!("url {} has no host", without_userinfo(url))))?;
if uri
.authority()
.is_some_and(|authority| authority.as_str().contains('@'))
{
return Err(Error::Fetch(format!(
"the {scheme} url for {literal} carries userinfo, which the fetcher does not send: \
pass credentials as {credentials}"
)));
}
let host = literal
.strip_prefix('[')
.and_then(|inner| inner.strip_suffix(']'))
.unwrap_or(literal)
.to_ascii_lowercase();
let port_text = uri
.authority()
.and_then(|authority| authority.as_str().strip_prefix(literal))
.and_then(|rest| rest.strip_prefix(':'));
let default_port = if tls { 443 } else { 80 };
let port = match (uri.port_u16(), port_text) {
(Some(port), _) => port,
(None, None) => default_port,
(None, Some(text)) => {
return Err(Error::Fetch(format!(
"url {} names the port {text:?}, which is not a number from 0 to 65535",
without_userinfo(url)
)));
}
};
let authority = if port == default_port {
literal.to_string()
} else {
format!("{literal}:{port}")
};
Ok((uri, Origin { tls, host, port }, authority))
}
fn without_userinfo(url: &str) -> Cow<'_, str> {
let start = url.find("://").map_or(0, |at| at + 3);
match url[start..].rfind('@') {
Some(at) => Cow::Owned(format!("{}{}", &url[..start], &url[start + at + 1..])),
None => Cow::Borrowed(url),
}
}
fn host_header(url: &str, authority: &str) -> Result<HeaderValue> {
HeaderValue::try_from(authority)
.map_err(|_| Error::Fetch(format!("url {url} has an unusable host")))
}
fn parse_mirror(url: &str) -> Result<Mirror> {
let (uri, origin, authority) = parse_authority(url, "FetcherOptions::basic_auth")?;
if let Some(query) = uri.query() {
return Err(Error::Fetch(format!(
"mirror url {url} carries the query string ?{query}, which the fetcher does not send"
)));
}
let scheme = if origin.tls { "https" } else { "http" };
Ok(Mirror {
authority: host_header(url, &authority)?,
prefix: format!("{scheme}://{authority}"),
base: uri.path().trim_end_matches('/').to_string(),
origin,
})
}
fn parse_url(url: &str) -> Result<Destination> {
if url.contains('#') {
return Err(Error::Fetch(format!(
"fetch url {} carries a fragment, which no request sends",
without_userinfo(url)
)));
}
let (uri, origin, authority) = parse_authority(url, "FetchRequest::basic_auth")?;
let scheme = if origin.tls { "https" } else { "http" };
let path_and_query = uri.path_and_query().map_or("/", |pq| pq.as_str());
let mut text =
String::with_capacity(scheme.len() + 3 + authority.len() + 1 + path_and_query.len());
text.push_str(scheme);
text.push_str("://");
text.push_str(&authority);
let path_at = text.len();
if !path_and_query.starts_with('/') {
text.push('/');
}
text.push_str(path_and_query);
Ok(Destination {
authority: host_header(url, &authority)?,
url: text,
path_at,
origin,
})
}
fn content_length(headers: &hyper::HeaderMap) -> Option<u64> {
headers
.get(hyper::header::CONTENT_LENGTH)?
.to_str()
.ok()?
.parse()
.ok()
}
fn declared_coding(headers: &hyper::HeaderMap) -> Option<String> {
coding(headers, hyper::header::CONTENT_ENCODING, &[IDENTITY]).or_else(|| {
coding(
headers,
hyper::header::TRANSFER_ENCODING,
&[IDENTITY, CHUNKED],
)
})
}
fn coding(headers: &hyper::HeaderMap, name: HeaderName, undone: &[&str]) -> Option<String> {
let declared = || {
headers
.get_all(&name)
.iter()
.map(|value| String::from_utf8_lossy(value.as_bytes()))
.filter(|value| value.split(',').any(|token| !token.trim().is_empty()))
};
if !declared().any(|value| value.split(',').any(|token| names_a_coding(token, undone))) {
return None;
}
Some(declared().collect::<Vec<_>>().join(", "))
}
fn names_a_coding(token: &str, undone: &[&str]) -> bool {
let token = token.trim();
!token.is_empty() && !undone.iter().any(|name| token.eq_ignore_ascii_case(name))
}
fn read_validators(headers: &hyper::HeaderMap) -> Validators {
let text = |name: HeaderName| {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
};
Validators {
etag: text(hyper::header::ETAG),
last_modified: text(hyper::header::LAST_MODIFIED),
}
}
fn is_redirect(status: StatusCode) -> bool {
REDIRECTS.contains(&status)
}
fn resolve_location(from: &str, location: &HeaderValue) -> Option<String> {
let location = location.to_str().ok()?;
if location.is_empty() {
return None;
}
let mut resolved = url::Url::parse(from).ok()?.join(location).ok()?;
resolved.set_fragment(None);
Some(resolved.into())
}
fn redirect_destination(from: &Destination, to: &str) -> Result<Destination> {
let refused = |what: &str| {
Error::Fetch(format!(
"{} redirects to {}, {what}",
from.url(),
without_userinfo(to)
))
};
let tls = match to.split_once("://").map(|(scheme, _)| scheme) {
Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
_ => return Err(refused("which is not an absolute http or https url")),
};
if from.origin.tls && !tls {
return Err(refused(
"which is cleartext: a request made over tls is not followed onto http",
));
}
parse_url(to)
}
fn no_trust_anchors(origin: &str) -> Error {
Error::Fetch(format!(
"the certificate of the tls origin {origin} has nothing to verify against: the \
fetcher holds no trust anchors, so set TlsOptions::roots"
))
}
fn classify(status: StatusCode, url: &str) -> Failure {
let error = Error::HttpStatus {
status: status.as_u16(),
url: url.to_string(),
};
if status.is_server_error()
|| status == StatusCode::REQUEST_TIMEOUT
|| status == StatusCode::TOO_MANY_REQUESTS
{
Failure::Retry(error)
} else {
Failure::Fatal(error)
}
}
fn transport(url: &str, error: hyper::Error) -> Error {
Error::Fetch(format!("{url}: {error}"))
}
fn stalled(url: &str, limit: Duration) -> Error {
Error::Fetch(format!("{url}: no response after {limit:?}"))
}
async fn within<F: Future>(limit: Duration, future: F) -> Option<F::Output> {
let mut future = core::pin::pin!(future);
futures_lite::future::or(async { Some(future.as_mut().await) }, async {
rt::Timer::after(limit).await;
None
})
.await
}
fn backoff(round: u32) -> Duration {
let ms = 250u64 << (round - 1).min(3);
Duration::from_millis(ms)
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Fetcher>();
assert_send_sync::<Body>();
assert_send_sync::<Fetched>();
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_connection_window_covers_every_admitted_stream() {
assert_eq!(h2_connection_window(1), H2_STREAM_WINDOW);
assert_eq!(h2_connection_window(8), 8 * H2_STREAM_WINDOW);
assert_eq!(h2_connection_window(usize::MAX), H2_MAX_WINDOW);
}
#[test]
fn mirror_urls_join_base_and_path() {
let mirror = parse_mirror("https://example.com/repo/").unwrap();
assert_eq!(
mirror.destination("objects/ab/cd.filez").url(),
"https://example.com/repo/objects/ab/cd.filez"
);
assert_eq!(mirror.origin.port, 443);
assert!(mirror.origin.tls);
let root = parse_mirror("http://example.com").unwrap();
assert_eq!(
root.destination("summary").url(),
"http://example.com/summary"
);
assert_eq!(root.origin.port, 80);
assert!(!root.origin.tls);
let ported = parse_mirror("http://127.0.0.1:8080/r").unwrap();
let config = ported.destination("/config");
assert_eq!(config.url(), "http://127.0.0.1:8080/r/config");
assert_eq!(config.target(), "/r/config");
assert_eq!(ported.authority, "127.0.0.1:8080");
assert_eq!(root.authority, "example.com");
}
#[test]
fn an_ipv6_literal_keeps_its_brackets_only_in_the_authority() {
let ported = parse_mirror("http://[::1]:8080/r").unwrap();
assert_eq!(ported.origin.host, "::1");
assert_eq!(ported.origin.port, 8080);
assert_eq!(ported.authority, "[::1]:8080");
assert_eq!(
ported.destination("summary").url(),
"http://[::1]:8080/r/summary"
);
let tls = parse_mirror("https://[2001:db8::1]/repo").unwrap();
assert_eq!(tls.origin.host, "2001:db8::1");
assert_eq!(tls.origin.port, 443);
assert_eq!(tls.authority, "[2001:db8::1]");
assert_eq!(
tls.destination("summary").url(),
"https://[2001:db8::1]/repo/summary"
);
rustls::pki_types::ServerName::try_from(tls.origin.host.clone()).unwrap();
}
#[test]
fn mirror_urls_are_validated() {
let err = parse_mirror("file:///srv/repo").unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let err = parse_mirror("/srv/repo").unwrap_err();
assert!(err.to_string().contains("not an absolute"), "{err}");
let err = parse_mirror("http://").unwrap_err();
assert!(err.to_string().contains("invalid url"), "{err}");
let err = parse_mirror("https://host/repo?X-Amz-Signature=deadbeef").unwrap_err();
assert!(err.to_string().contains("query string"), "{err}");
let err = parse_mirror("https://user:pass@host/repo").unwrap_err();
assert!(err.to_string().contains("userinfo"), "{err}");
let err = parse_mirror("http://user@host/repo").unwrap_err();
assert!(err.to_string().contains("userinfo"), "{err}");
}
#[test]
fn options_are_validated_at_construction() {
rt::block_on(async {
let mut options = direct_options("http://example.com");
options.headers = vec![("not a header".into(), "v".into())];
let err = Fetcher::new(options).await.unwrap_err();
assert!(err.to_string().contains("invalid header name"), "{err}");
let mut options = direct_options("http://example.com");
options.headers = vec![("host".into(), "elsewhere".into())];
let err = Fetcher::new(options).await.unwrap_err();
assert!(err.to_string().contains("host header"), "{err}");
let mut options = tls_options("https://example.com");
options.headers = vec![("authorization".into(), "Basic aaa".into())];
options.basic_auth = Some(BasicAuth {
user: "u".into(),
password: "p".into(),
});
let err = Fetcher::new(options).await.unwrap_err();
assert!(err.to_string().contains("pass one of them"), "{err}");
});
}
#[test]
fn a_path_target_needs_a_mirror() {
rt::block_on(async {
let fetcher = Fetcher::new(mirrorless_options()).await.unwrap();
let err = fetcher.route(Target::Path("summary")).unwrap_err();
assert!(err.to_string().contains("no mirror is configured"), "{err}");
let route = fetcher
.route(Target::Url("https://example.com/summary"))
.unwrap();
let Route::One(destination) = route else {
panic!("a url target names one destination");
};
assert_eq!(destination.url(), "https://example.com/summary");
});
}
#[test]
fn a_query_or_a_fragment_in_a_path_is_rejected() {
for path in ["refs/heads/a?b=c", "refs/heads/a#frag"] {
let Err(err) = check_path(path) else {
panic!("{path} was accepted as a request path");
};
assert!(
err.to_string().contains("no query and no fragment"),
"{path}: {err}"
);
}
check_path("refs/heads/a").unwrap();
}
#[test]
fn a_request_target_appends_the_path_to_the_base() {
rt::block_on(async {
let fetcher = Fetcher::new(direct_options("http://example.com/r"))
.await
.unwrap();
let mirror = &fetcher.inner.mirrors[0];
let destination = mirror.destination("refs/heads/a");
let request = fetcher
.build_request(
&destination,
&FetchRequest::path("refs/heads/a"),
&fetcher.inner.headers,
Protocol::Http11,
Via::Direct,
)
.unwrap();
assert_eq!(request.uri(), "/r/refs/heads/a");
});
}
#[test]
fn a_location_resolves_against_the_response_that_carried_it() {
let resolved = |value: &str| {
resolve_location(
"https://example.com/repo/objects/summary?x=1",
&HeaderValue::try_from(value).unwrap(),
)
};
for (value, hop) in [
("http://other.example/p", "http://other.example/p"),
(
"https://other.example:8443/p?q=2",
"https://other.example:8443/p?q=2",
),
("/other/path", "https://example.com/other/path"),
("sibling", "https://example.com/repo/objects/sibling"),
("//host.example/path", "https://host.example/path"),
("/other/path#frag", "https://example.com/other/path"),
("http://other.example/p#frag", "http://other.example/p"),
("file:///srv/repo", "file:///srv/repo"),
] {
assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
}
assert_eq!(resolved("http://"), None);
assert_eq!(resolved(""), None);
assert_eq!(
resolved("#frag").as_deref(),
Some("https://example.com/repo/objects/summary?x=1")
);
for (value, hop) in [
("/deep/../root", "https://example.com/root"),
("/./p", "https://example.com/p"),
("/a\\b", "https://example.com/a/b"),
("/pa\tth", "https://example.com/path"),
("/p?q='x'", "https://example.com/p?q=%27x%27"),
("http://2130706433/p", "http://127.0.0.1/p"),
] {
assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
}
}
#[test]
fn a_redirect_hop_is_validated_against_the_url_that_redirected() {
let secure = parse_url("https://example.com/repo/summary").unwrap();
let cleartext = parse_url("http://example.com/repo/summary").unwrap();
let hop = redirect_destination(&secure, "https://other.example/p?q=1").unwrap();
assert_eq!(hop.url(), "https://other.example/p?q=1");
assert_eq!(hop.origin.host, "other.example");
let hop = redirect_destination(&secure, "https://example.com/elsewhere").unwrap();
assert_eq!(hop.origin, secure.origin);
let hop = redirect_destination(&cleartext, "https://example.com/elsewhere").unwrap();
assert!(hop.origin.tls);
redirect_destination(&cleartext, "http://other.example/p").unwrap();
let err = redirect_destination(&secure, "http://other.example/p").unwrap_err();
let message = err.to_string();
assert!(
message.contains("https://example.com/repo/summary"),
"{message}"
);
assert!(message.contains("http://other.example/p"), "{message}");
assert!(message.contains("cleartext"), "{message}");
let err = redirect_destination(&secure, "file:///srv/repo").unwrap_err();
let message = err.to_string();
assert!(
message.contains("https://example.com/repo/summary"),
"{message}"
);
assert!(message.contains("file:///srv/repo"), "{message}");
assert!(
message.contains("not an absolute http or https url"),
"{message}"
);
let err =
redirect_destination(&secure, "https://alice:sup3rs3cret@other.example/p").unwrap_err();
let message = err.to_string();
assert!(message.contains("userinfo"), "{message}");
assert!(!message.contains("sup3rs3cret"), "{message}");
}
#[test]
fn the_followed_statuses_are_the_five_redirects() {
for status in [301u16, 302, 303, 307, 308] {
assert!(
is_redirect(StatusCode::from_u16(status).unwrap()),
"{status}"
);
}
for status in [200u16, 300, 304, 305, 306, 400, 404, 500] {
assert!(
!is_redirect(StatusCode::from_u16(status).unwrap()),
"{status}"
);
}
}
#[test]
fn retryable_statuses_are_classified() {
for status in [500u16, 502, 503, 408, 429] {
let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
assert!(matches!(failure, Failure::Retry(_)), "{status}");
}
for status in [400u16, 401, 403, 404, 410] {
let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
assert!(matches!(failure, Failure::Fatal(_)), "{status}");
}
}
#[test]
fn backoff_doubles_and_stops_at_two_seconds() {
assert_eq!(backoff(1), Duration::from_millis(250));
assert_eq!(backoff(2), Duration::from_millis(500));
assert_eq!(backoff(3), Duration::from_secs(1));
assert_eq!(backoff(4), Duration::from_secs(2));
assert_eq!(backoff(9), Duration::from_secs(2));
}
#[test]
fn basic_auth_and_extra_headers_reach_the_header_list() {
let mut options = tls_options("https://example.com");
options.basic_auth = Some(BasicAuth {
user: "u".into(),
password: "p".into(),
});
options.headers = vec![("x-trace".into(), "abc".into())];
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
let headers = &fetcher.inner.headers;
let value = |name: HeaderName| {
headers
.iter()
.find(|(n, _)| *n == name)
.map(|(_, v)| v.to_str().unwrap().to_string())
};
assert_eq!(
value(hyper::header::USER_AGENT).as_deref(),
Some(USER_AGENT)
);
assert_eq!(
value(HeaderName::from_static("x-trace")).as_deref(),
Some("abc")
);
assert_eq!(
value(hyper::header::AUTHORIZATION).as_deref(),
Some("Basic dTpw")
);
}
fn mirrorless_options() -> FetcherOptions {
FetcherOptions {
mirrors: Vec::new(),
..tls_options("unused")
}
}
fn direct_options(url: impl Into<String>) -> FetcherOptions {
FetcherOptions {
proxy: Proxy::None,
..FetcherOptions::new(url)
}
}
fn tls_options(url: &str) -> FetcherOptions {
FetcherOptions {
tls: TlsOptions {
roots: TrustRoots::Pem(
include_bytes!("../../../tests/fixtures/tls/ca.pem").to_vec(),
),
..TlsOptions::default()
},
..direct_options(url)
}
}
#[test]
fn credentials_alongside_a_cleartext_mirror_are_refused() {
let auth = || {
Some(BasicAuth {
user: "u".into(),
password: "p".into(),
})
};
for mirrors in [
vec!["http://cleartext.example/repo".to_owned()],
vec![
"https://secure.example/repo".to_owned(),
"http://cleartext.example/repo".to_owned(),
],
] {
let options = FetcherOptions {
mirrors,
basic_auth: auth(),
..tls_options("unused")
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains("basic-auth credentials"), "{message}");
assert!(
message.contains("http://cleartext.example/repo"),
"{message}"
);
}
for name in ["authorization", "proxy-authorization", "cookie"] {
let options = FetcherOptions {
headers: vec![(name.to_owned(), "secret".to_owned())],
..direct_options("http://cleartext.example/repo")
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains(name), "{message}");
assert!(message.contains("carries credentials"), "{message}");
}
let options = FetcherOptions {
headers: vec![("x-trace".to_owned(), "abc".to_owned())],
..direct_options("http://cleartext.example/repo")
};
rt::block_on(Fetcher::new(options)).unwrap();
let options = FetcherOptions {
mirrors: vec![
"https://one.example/repo".to_owned(),
"https://two.example/repo".to_owned(),
],
basic_auth: auth(),
headers: vec![("cookie".to_owned(), "session=1".to_owned())],
..tls_options("unused")
};
rt::block_on(Fetcher::new(options)).unwrap();
}
#[test]
fn url_targets_are_parsed_and_validated() {
let rows = [
(
"https://example.com/repo/summary?sig=a%2Fb&x=1",
"https://example.com/repo/summary?sig=a%2Fb&x=1",
"/repo/summary?sig=a%2Fb&x=1",
"example.com",
"https://example.com",
),
("http://h", "http://h/", "/", "h", "http://h"),
("http://h/", "http://h/", "/", "h", "http://h"),
("http://h/p?", "http://h/p?", "/p?", "h", "http://h"),
(
"http://h/p?a=%2F&b=1",
"http://h/p?a=%2F&b=1",
"/p?a=%2F&b=1",
"h",
"http://h",
),
("https://h:443/p", "https://h/p", "/p", "h", "https://h"),
("HTTP://h/p", "http://h/p", "/p", "h", "http://h"),
(
"http://[2001:db8::1]:8080/r/config",
"http://[2001:db8::1]:8080/r/config",
"/r/config",
"[2001:db8::1]:8080",
"http://[2001:db8::1]:8080",
),
];
for (url, absolute, target, authority, origin) in rows {
let dest = parse_url(url).unwrap();
assert_eq!(dest.url(), absolute, "{url}");
assert_eq!(dest.target(), target, "{url}");
assert_eq!(dest.authority, authority, "{url}");
assert_eq!(dest.origin_url(), origin, "{url}");
}
let dest = parse_url("https://example.com/repo/summary?sig=a%2Fb&x=1").unwrap();
assert_eq!(dest.origin.port, 443);
assert!(dest.origin.tls);
let root = parse_url("http://example.com").unwrap();
assert_eq!(root.origin.port, 80);
assert!(!root.origin.tls);
let ported = parse_url("http://[::1]:8080/r/config").unwrap();
assert_eq!(ported.origin.host, "::1");
assert_eq!(ported.origin.port, 8080);
let err = parse_url("https://alice:sup3rs3cret@example.com/p").unwrap_err();
let message = err.to_string();
assert!(message.contains("userinfo"), "{message}");
assert!(message.contains("https url for example.com"), "{message}");
assert!(message.contains("FetchRequest::basic_auth"), "{message}");
assert!(!message.contains("sup3rs3cret"), "{message}");
let err = parse_url("https://example.com/p#frag").unwrap_err();
assert!(err.to_string().contains("fragment"), "{err}");
let err = parse_url("file:///srv/repo").unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let err = parse_url("/srv/repo").unwrap_err();
assert!(err.to_string().contains("not an absolute"), "{err}");
}
#[test]
fn a_password_reaches_no_message() {
for url in [
"https://alice:sup3rs3cret@example.com/p",
"https://alice:sup3rs3cret@example.com/p#frag",
"http://alice:sup3rs3cret@example.com/ p",
"http://alice:sup3rs3cret@",
"alice:sup3rs3cret@example.com/p",
] {
let err = parse_url(url).unwrap_err();
let message = err.to_string();
assert!(!message.contains("sup3rs3cret"), "{url}: {message}");
}
for password in ["pa#ss", "pa?ss", "p/ss"] {
let url = format!("https://alice:{password}@example.com/p");
let message = parse_url(&url).unwrap_err().to_string();
assert!(!message.contains(password), "{password}: {message}");
}
}
#[test]
fn a_port_the_url_parser_cannot_read_is_refused() {
for (url, text) in [
("http://h:99999/x", "99999"),
("http://h:65536/x", "65536"),
("http://h:abc/x", "abc"),
("http://h:/x", ""),
] {
let err = parse_url(url).unwrap_err();
let message = err.to_string();
assert!(message.contains(url), "{url}: {message}");
assert!(message.contains(text), "{url}: {message}");
assert!(message.contains("not a number"), "{url}: {message}");
assert!(parse_mirror(url).is_err(), "{url}");
}
let default = parse_url("http://h/x").unwrap();
assert_eq!(default.origin.port, 80);
assert_eq!(default.url(), "http://h/x");
let ported = parse_url("http://h:8080/x").unwrap();
assert_eq!(ported.origin.port, 8080);
assert_eq!(ported.url(), "http://h:8080/x");
}
#[test]
fn a_host_in_another_case_is_one_origin() {
let upper = parse_url("http://LOCALHOST:8080/x").unwrap();
let lower = parse_url("http://localhost:8080/x").unwrap();
assert_eq!(upper.origin, lower.origin);
assert_eq!(upper.origin.host, "localhost");
assert_eq!(upper.authority, "LOCALHOST:8080");
assert_eq!(upper.url(), "http://LOCALHOST:8080/x");
}
#[test]
fn basic_auth_debug_holds_no_password() {
let auth = BasicAuth {
user: "alice".into(),
password: "sup3rs3cret".into(),
};
let rendered = format!("{auth:?}");
assert!(rendered.contains("alice"), "{rendered}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
let request = FetchRequest {
basic_auth: Some(&auth),
..FetchRequest::path("summary")
};
let rendered = format!("{request:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
let options = FetcherOptions {
basic_auth: Some(auth),
..direct_options("https://example.com")
};
let rendered = format!("{options:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
}
fn origin_of(url: &str) -> Origin {
parse_url(url).unwrap().origin
}
fn via_of(proxies: &Proxies, url: &str) -> Option<(String, bool)> {
match proxies.via(&origin_of(url)) {
Via::Direct => None,
Via::Absolute(proxy) => Some((proxy.named.clone(), false)),
Via::Tunnel(proxy) => Some((proxy.named.clone(), true)),
}
}
fn variables(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect()
}
#[test]
fn a_proxy_url_names_an_http_endpoint() {
for (url, host, port, named) in [
(
"http://proxy.example",
"proxy.example",
80,
"http://proxy.example",
),
(
"http://proxy.example:3128",
"proxy.example",
3128,
"http://proxy.example:3128",
),
(
"http://proxy.example/",
"proxy.example",
80,
"http://proxy.example",
),
(
"HTTP://Proxy.Example:3128",
"proxy.example",
3128,
"http://Proxy.Example:3128",
),
(
" http://proxy.example:3128 ",
"proxy.example",
3128,
"http://proxy.example:3128",
),
("http://[::1]:3128", "::1", 3128, "http://[::1]:3128"),
(
"http://alice:s3cret@proxy.example:3128",
"proxy.example",
3128,
"http://proxy.example:3128",
),
] {
let proxy = parse_proxy(url).unwrap_or_else(|e| panic!("{url}: {e}"));
assert_eq!(proxy.endpoint.host, host, "{url}");
assert_eq!(proxy.endpoint.port, port, "{url}");
assert!(!proxy.endpoint.tls, "{url}");
assert_eq!(proxy.named, named, "{url}");
}
let credential = |url: &str| {
parse_proxy(url)
.unwrap()
.credential
.map(|value| value.to_str().unwrap().to_owned())
};
assert_eq!(credential("http://proxy.example"), None);
assert_eq!(
credential("http://alice:s3cret@proxy.example").as_deref(),
Some("Basic YWxpY2U6czNjcmV0")
);
assert_eq!(
credential("http://al%3Ace:p%40ss@proxy.example").as_deref(),
Some("Basic YWw6Y2U6cEBzcw==")
);
assert_eq!(
credential("http://alice@proxy.example").as_deref(),
Some("Basic YWxpY2U6")
);
for (url, says) in [
("socks5://proxy.example:1080", "http://host[:port] alone"),
("https://proxy.example:3128", "http://host[:port] alone"),
("proxy.example:3128", "http://host[:port] alone"),
("http://proxy.example/squid", "carries no path"),
("http://proxy.example/?upstream=1", "carries no query"),
("http://proxy.example/#frag", "carries no fragment"),
("http://", "invalid url"),
("http://proxy.example:99999", "not a number"),
("http://proxy.example:abc", "not a number"),
("http://alice:p%zz@proxy.example", "percent-encoded"),
("http://alice:p%4@proxy.example", "percent-encoded"),
] {
let err = parse_proxy(url).unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{url}: {err}");
let message = err.to_string();
assert!(message.contains(says), "{url}: {message}");
}
}
#[test]
fn the_proxy_variables_are_read_per_scheme() {
let cleartext = "http://origin.example/summary";
let tls = "https://origin.example/summary";
let absolute = |named: &str| Some((named.to_owned(), false));
let tunnel = |named: &str| Some((named.to_owned(), true));
let proxies = resolve_variables(&variables(&[
("http_proxy", "http://plain.example:3128"),
("https_proxy", "http://secure.example:3128"),
]))
.unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://plain.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies =
resolve_variables(&variables(&[("http_proxy", "http://plain.example:3128")])).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://plain.example:3128")
);
assert_eq!(via_of(&proxies, tls), None);
let proxies =
resolve_variables(&variables(&[("https_proxy", "http://secure.example:3128")]))
.unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies =
resolve_variables(&variables(&[("all_proxy", "http://any.example:3128")])).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
let proxies = resolve_variables(&variables(&[
("all_proxy", "http://any.example:3128"),
("https_proxy", "http://secure.example:3128"),
]))
.unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies = resolve_variables(&variables(&[
("HTTP_PROXY", "http://cgi.example:3128"),
("HTTPS_PROXY", "http://secure.example:3128"),
]))
.unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies =
resolve_variables(&variables(&[("ALL_PROXY", "http://any.example:3128")])).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
let proxies = resolve_variables(&variables(&[
("https_proxy", "http://lower.example:3128"),
("HTTPS_PROXY", "http://upper.example:3128"),
]))
.unwrap();
assert_eq!(via_of(&proxies, tls), tunnel("http://lower.example:3128"));
let proxies = resolve_variables(&variables(&[
("https_proxy", ""),
("HTTPS_PROXY", "http://upper.example:3128"),
]))
.unwrap();
assert_eq!(via_of(&proxies, tls), tunnel("http://upper.example:3128"));
let proxies = resolve_variables(&variables(&[("http_proxy", "")])).unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
for name in ["http_proxy", "https_proxy", "all_proxy"] {
let err = resolve_variables(&variables(&[(name, "socks5://proxy.example:1080")]))
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{name}: {err}");
}
let err = resolve_variables(&variables(&[
("all_proxy", "socks5://proxy.example:1080"),
("http_proxy", "http://plain.example:3128"),
("https_proxy", "http://secure.example:3128"),
]))
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let proxies = resolve_variables(&[]).unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
assert_eq!(via_of(&proxies, tls), None);
let proxies = resolve_proxy(&Proxy::None).unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
let proxies = resolve_proxy(&Proxy::Url("http://any.example:3128".into())).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
}
#[test]
fn no_proxy_exempts_by_host_text_and_port() {
let proxied = |no_proxy: &str, url: &str| {
let proxies = resolve_variables(&variables(&[
("all_proxy", "http://any.example:3128"),
("no_proxy", no_proxy),
]))
.unwrap();
via_of(&proxies, url).is_some()
};
assert!(!proxied("origin.example", "http://origin.example/p"));
assert!(proxied("origin.example", "http://other.example/p"));
for entry in ["example.com", ".example.com"] {
assert!(!proxied(entry, "http://a.example.com/p"));
assert!(!proxied(entry, "http://deep.a.example.com/p"));
assert!(!proxied(entry, "http://example.com/p"));
assert!(proxied(entry, "http://notexample.com/p"));
}
assert!(!proxied(" a.example , b.example ", "http://b.example/p"));
assert!(!proxied("a.example,,b.example", "http://a.example/p"));
assert!(proxied(",", "http://a.example/p"));
assert!(proxied("", "http://a.example/p"));
assert!(!proxied("ORIGIN.example", "http://origin.EXAMPLE/p"));
assert!(!proxied(
"origin.example:8080",
"http://origin.example:8080/p"
));
assert!(proxied(
"origin.example:8080",
"http://origin.example:8081/p"
));
assert!(proxied("origin.example:8080", "http://origin.example/p"));
assert!(!proxied("origin.example:443", "https://origin.example/p"));
assert!(!proxied("origin.example", "http://origin.example:8080/p"));
for url in ["http://a.example/p", "https://b.example:8443/p"] {
assert!(!proxied("*", url));
assert!(!proxied("a.example,*", url));
}
assert!(!proxied("127.0.0.1", "http://127.0.0.1:8080/p"));
assert!(proxied("localhost", "http://127.0.0.1:8080/p"));
assert!(proxied("127.0.0.1", "http://localhost:8080/p"));
for entry in ["::1", "[::1]", "[::1]:8080"] {
assert!(!proxied(entry, "http://[::1]:8080/p"), "{entry}");
}
assert!(proxied("[::1]:8081", "http://[::1]:8080/p"));
assert!(proxied("127.0.0.0/8", "http://127.0.0.1:8080/p"));
assert!(proxied("origin.example:abc", "http://origin.example/p"));
for entry in [".", ":8080", ".:8080"] {
assert!(proxied(entry, "http://a.example./p"), "{entry}");
assert!(proxied(entry, "http://a.example:8080/p"), "{entry}");
}
assert!(proxied("..example.com", "http://a.example.com/p"));
assert!(proxied("*.example.com", "http://a.example.com/p"));
assert!(proxied("*.example.com", "http://example.com/p"));
}
#[test]
fn a_proxy_password_reaches_no_message() {
let url = |tail: &str| format!("http://alice:sup3rs3cret@proxy.example:3128{tail}");
for proxy in [
Proxy::Url(url("")),
Proxy::Variables(vec![("https_proxy".to_owned(), url(""))]),
] {
let rendered = format!("{proxy:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
assert!(rendered.contains("proxy.example:3128"), "{rendered}");
let options = FetcherOptions {
proxy,
..direct_options("https://example.com")
};
let rendered = format!("{options:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
}
for tail in ["/squid", "/?upstream=1", "/#frag", ":99999"] {
let err = parse_proxy(&url(tail)).unwrap_err();
let message = err.to_string();
assert!(!message.contains("sup3rs3cret"), "{tail}: {message}");
}
let err = parse_proxy("socks5://alice:sup3rs3cret@proxy.example:1080").unwrap_err();
assert!(!err.to_string().contains("sup3rs3cret"), "{err}");
for password in ["pa#ss", "pa?ss", "p/ss"] {
let url = format!("http://alice:{password}@proxy.example:3128/squid");
let rendered = format!("{:?}", Proxy::Url(url.clone()));
assert!(!rendered.contains(password), "{password}: {rendered}");
assert!(
rendered.contains("proxy.example:3128"),
"{password}: {rendered}"
);
let message = parse_proxy(&url).unwrap_err().to_string();
assert!(!message.contains(password), "{password}: {message}");
assert!(
message.contains("proxy.example:3128"),
"{password}: {message}"
);
}
rt::block_on(async {
let err = Fetcher::new(FetcherOptions {
proxy: Proxy::Url(url("/squid")),
..direct_options("http://origin.example/repo")
})
.await
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let message = err.to_string();
assert!(!message.contains("sup3rs3cret"), "{message}");
assert!(message.contains("proxy.example:3128"), "{message}");
});
}
#[test]
fn a_connect_names_the_target_with_its_port() {
for (url, authority) in [
("https://origin.example/p", "origin.example:443"),
("https://origin.example:8443/p", "origin.example:8443"),
("http://origin.example/p", "origin.example:80"),
("https://[2001:db8::1]/p", "[2001:db8::1]:443"),
("https://[::1]:8443/p", "[::1]:8443"),
] {
assert_eq!(connect_authority(&origin_of(url)), authority, "{url}");
}
}
#[test]
fn a_proxied_cleartext_request_carries_the_absolute_form() {
rt::block_on(async {
let fetcher = Fetcher::new(FetcherOptions {
proxy: Proxy::Url("http://alice:s3cret@proxy.example:3128".into()),
..tls_options("http://origin.example/r")
})
.await
.unwrap();
let destination = fetcher.inner.mirrors[0].destination("refs/heads/a");
let request = FetchRequest::path("refs/heads/a");
let built = |via: Via<'_>, headers: &[(HeaderName, HeaderValue)]| {
fetcher
.build_request(&destination, &request, headers, Protocol::Http11, via)
.unwrap()
};
let proxy_credential = |request: &Request<NoBody>| {
request
.headers()
.get(hyper::header::PROXY_AUTHORIZATION)
.map(|value| value.to_str().unwrap().to_owned())
};
let Via::Absolute(proxy) = fetcher.inner.proxies.via(&destination.origin) else {
panic!("a cleartext origin behind a proxy travels in absolute form");
};
let via = Via::Absolute(proxy);
let absolute = built(via, &fetcher.inner.headers);
assert_eq!(absolute.uri(), "http://origin.example/r/refs/heads/a");
assert_eq!(
absolute.headers().get(hyper::header::HOST).unwrap(),
"origin.example"
);
assert_eq!(
proxy_credential(&absolute).as_deref(),
Some("Basic YWxpY2U6czNjcmV0")
);
let mut headers = fetcher.inner.headers.clone();
headers.push((
hyper::header::PROXY_AUTHORIZATION,
HeaderValue::from_static("Basic Y2FsbGVy"),
));
let caller = built(via, &headers);
assert_eq!(
caller
.headers()
.get_all(hyper::header::PROXY_AUTHORIZATION)
.iter()
.count(),
1
);
assert_eq!(proxy_credential(&caller).as_deref(), Some("Basic Y2FsbGVy"));
for via in [Via::Direct, Via::Tunnel(proxy)] {
let direct = built(via, &fetcher.inner.headers);
assert_eq!(direct.uri(), "/r/refs/heads/a");
assert_eq!(proxy_credential(&direct), None);
}
});
}
#[test]
fn a_connection_header_is_refused_at_both_layers() {
let fetcher_headers = vec![(
HeaderName::from_static("x-trace"),
HeaderValue::from_static("abc"),
)];
for name in CONNECTION_HEADERS {
let options = FetcherOptions {
headers: vec![(name.to_owned(), "10".to_owned())],
..direct_options("http://example.com")
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains(name), "{name}: {message}");
assert!(message.contains("connection layer"), "{name}: {message}");
let request = vec![(name.to_owned(), "10".to_owned())];
let err = merge_headers(&fetcher_headers, &request, None).unwrap_err();
let message = err.to_string();
assert!(message.contains(name), "{name}: {message}");
assert!(message.contains("connection layer"), "{name}: {message}");
}
let request = vec![("Content-Length".to_owned(), "10".to_owned())];
let err = merge_headers(&fetcher_headers, &request, None).unwrap_err();
assert!(err.to_string().contains("content-length"), "{err}");
}
#[test]
fn request_headers_merge_over_the_fetchers() {
let header = |name: &'static str, value: &'static str| {
(
HeaderName::from_static(name),
HeaderValue::from_static(value),
)
};
let fetcher = vec![
header("x-trace", "fetcher"),
header("x-only", "yes"),
header("authorization", "Basic ZmV0Y2hlcg=="),
];
let sent = |headers: &[(HeaderName, HeaderValue)]| {
headers
.iter()
.map(|(name, value)| (name.as_str().to_owned(), value.to_str().unwrap().to_owned()))
.collect::<Vec<_>>()
};
let borrowed = merge_headers(&fetcher, &[], None).unwrap();
assert!(matches!(borrowed, Cow::Borrowed(_)));
assert_eq!(sent(&borrowed), sent(&fetcher));
let extra = vec![
("X-Trace".to_owned(), "request".to_owned()),
("x-trace".to_owned(), "second".to_owned()),
];
let merged = merge_headers(&fetcher, &extra, None).unwrap();
assert_eq!(
sent(&merged),
[
("x-only".to_owned(), "yes".to_owned()),
("authorization".to_owned(), "Basic ZmV0Y2hlcg==".to_owned()),
("x-trace".to_owned(), "request".to_owned()),
("x-trace".to_owned(), "second".to_owned()),
]
);
let auth = BasicAuth {
user: "u".into(),
password: "p".into(),
};
let merged = merge_headers(&fetcher, &[], Some(&auth)).unwrap();
assert_eq!(
sent(&merged),
[
("x-trace".to_owned(), "fetcher".to_owned()),
("x-only".to_owned(), "yes".to_owned()),
("authorization".to_owned(), "Basic dTpw".to_owned()),
]
);
let both = vec![("authorization".to_owned(), "Basic aaa".to_owned())];
let err = merge_headers(&fetcher, &both, Some(&auth)).unwrap_err();
assert!(err.to_string().contains("pass one of them"), "{err}");
let host = vec![("host".to_owned(), "elsewhere".to_owned())];
let err = merge_headers(&fetcher, &host, None).unwrap_err();
assert!(err.to_string().contains("host header"), "{err}");
let invalid = vec![("not a header".to_owned(), "v".to_owned())];
let err = merge_headers(&fetcher, &invalid, None).unwrap_err();
assert!(err.to_string().contains("invalid header name"), "{err}");
}
#[test]
fn a_declared_content_coding_is_read_off_the_response() {
let map = |values: &[&str]| {
let mut headers = hyper::HeaderMap::new();
for value in values {
headers.append(
hyper::header::CONTENT_ENCODING,
HeaderValue::try_from(*value).unwrap(),
);
}
headers
};
for values in [
vec![],
vec![""],
vec![","],
vec!["identity"],
vec!["IDENTITY"],
vec![" identity "],
vec!["identity", "identity"],
] {
assert_eq!(declared_coding(&map(&values)), None, "{values:?}");
}
for (values, named) in [
(vec!["gzip"], "gzip"),
(vec!["GZip"], "GZip"),
(vec!["identity, gzip"], "identity, gzip"),
(vec!["gzip, identity"], "gzip, identity"),
(vec!["identity", "gzip"], "identity, gzip"),
(vec!["gzip", "br"], "gzip, br"),
(vec!["", "gzip"], "gzip"),
(vec!["gzip", ""], "gzip"),
(vec!["gzip", "", "br"], "gzip, br"),
(vec!["gzip", ",", "br"], "gzip, br"),
] {
assert_eq!(
declared_coding(&map(&values)).as_deref(),
Some(named),
"{values:?}"
);
}
}
#[test]
fn a_fetcher_header_replaces_the_entry_the_fetcher_sets() {
let sent = |fetcher: &Fetcher, name: HeaderName| {
fetcher
.inner
.headers
.iter()
.filter(|(held, _)| *held == name)
.map(|(_, value)| value.to_str().unwrap().to_owned())
.collect::<Vec<_>>()
};
let fetcher = rt::block_on(Fetcher::new(direct_options("http://example.com"))).unwrap();
assert_eq!(
sent(&fetcher, hyper::header::ACCEPT_ENCODING),
[IDENTITY.to_owned()]
);
for name in ["accept-encoding", "user-agent"] {
let options = FetcherOptions {
headers: vec![(name.to_owned(), "caller".to_owned())],
..direct_options("http://example.com")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
let header = HeaderName::from_static(name);
assert_eq!(sent(&fetcher, header), ["caller".to_owned()], "{name}");
}
let options = FetcherOptions {
headers: vec![
("accept-encoding".to_owned(), "one".to_owned()),
("Accept-Encoding".to_owned(), "two".to_owned()),
],
..direct_options("http://example.com")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
assert_eq!(
sent(&fetcher, hyper::header::ACCEPT_ENCODING),
["one".to_owned(), "two".to_owned()]
);
let options = FetcherOptions {
headers: vec![
("x-trace".to_owned(), "one".to_owned()),
("x-trace".to_owned(), "two".to_owned()),
],
..direct_options("http://example.com")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
assert_eq!(
sent(&fetcher, HeaderName::from_static("x-trace")),
["one".to_owned(), "two".to_owned()]
);
}
#[test]
fn a_credential_refuses_a_cleartext_destination() {
let credential = vec![(hyper::header::COOKIE, HeaderValue::from_static("session=1"))];
let plain = vec![(
HeaderName::from_static("x-trace"),
HeaderValue::from_static("abc"),
)];
let options = FetcherOptions {
mirrors: vec![
"https://secure.example/repo".to_owned(),
"http://cleartext.example/repo".to_owned(),
],
..tls_options("unused")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
let mirrors = fetcher.route(Target::Path("summary")).unwrap();
let err = fetcher.check_cleartext(&mirrors, &credential).unwrap_err();
assert!(
err.to_string().contains("http://cleartext.example"),
"{err}"
);
fetcher.check_cleartext(&mirrors, &plain).unwrap();
let cleartext = fetcher
.route(Target::Url("http://cleartext.example/p"))
.unwrap();
let err = fetcher
.check_cleartext(&cleartext, &credential)
.unwrap_err();
assert!(
err.to_string().contains("http://cleartext.example"),
"{err}"
);
fetcher.check_cleartext(&cleartext, &plain).unwrap();
let secure = fetcher
.route(Target::Url("https://secure.example/p"))
.unwrap();
fetcher.check_cleartext(&secure, &credential).unwrap();
}
#[test]
fn a_tls_destination_needs_a_trust_anchor() {
rt::block_on(async {
let mut fetcher = Fetcher::new(direct_options("http://cleartext.example/repo"))
.await
.unwrap();
Arc::get_mut(&mut fetcher.inner)
.expect("the one handle on this fetcher")
.has_trust_anchors = false;
let refused = within(
Duration::from_secs(1),
fetcher.fetch(FetchRequest::url("https://127.0.0.1:1/summary")),
)
.await;
let err = refused
.expect("the refusal takes no attempt")
.expect_err("a tls url is refused without anchors");
let message = err.to_string();
assert!(message.contains("https://127.0.0.1:1"), "{message}");
assert!(message.contains("no trust anchors"), "{message}");
let cleartext = fetcher
.route(Target::Url("http://cleartext.example/summary"))
.unwrap();
fetcher.check_trust_anchors(&cleartext).unwrap();
let mirrors = fetcher.route(Target::Path("summary")).unwrap();
fetcher.check_trust_anchors(&mirrors).unwrap();
});
}
#[test]
fn a_redirect_to_a_tls_origin_needs_a_trust_anchor() {
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
use std::sync::atomic::{AtomicUsize, Ordering};
rt::block_on(async {
let tls_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
.await
.unwrap();
let tls_port = tls_peer.local_addr().unwrap().port();
let connections = Arc::new(AtomicUsize::new(0));
let counted = connections.clone();
drop(rt::spawn(async move {
while let Ok((stream, _peer)) = tls_peer.accept().await {
counted.fetch_add(1, Ordering::SeqCst);
drop(stream);
}
}));
let cleartext_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
.await
.unwrap();
let cleartext_port = cleartext_peer.local_addr().unwrap().port();
let requests = Arc::new(AtomicUsize::new(0));
let counted = requests.clone();
drop(rt::spawn(async move {
while let Ok((mut stream, _peer)) = cleartext_peer.accept().await {
let mut request = [0u8; 1024];
let _ = stream.read(&mut request).await;
counted.fetch_add(1, Ordering::SeqCst);
let answer = format!(
"HTTP/1.1 302 Found\r\nLocation: https://127.0.0.1:{tls_port}/hopped\r\n\
Content-Length: 0\r\n\r\n"
);
let _ = stream.write_all(answer.as_bytes()).await;
let _ = stream.flush().await;
}
}));
let mut fetcher =
Fetcher::new(direct_options(format!("http://127.0.0.1:{cleartext_port}")))
.await
.unwrap();
Arc::get_mut(&mut fetcher.inner)
.expect("the one handle on this fetcher")
.has_trust_anchors = false;
let refused = within(
Duration::from_secs(2),
fetcher.fetch(FetchRequest::path("summary")),
)
.await;
let err = refused
.expect("the refusal ends the attempt")
.expect_err("a tls hop is refused without anchors");
let message = err.to_string();
assert!(
message.contains(&format!("https://127.0.0.1:{tls_port}")),
"{message}"
);
assert!(message.contains("no trust anchors"), "{message}");
assert_eq!(requests.load(Ordering::SeqCst), 1);
assert_eq!(connections.load(Ordering::SeqCst), 0);
});
}
}