use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::Duration;
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::client_config;
pub use tls::{ClientIdentity, TlsOptions, TrustRoots};
const USER_AGENT: &str = concat!("ostrya/", env!("CARGO_PKG_VERSION"));
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, Debug, Eq, PartialEq)]
pub struct BasicAuth {
pub user: String,
pub password: String,
}
#[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, Debug)]
pub struct FetcherOptions {
pub mirrors: Vec<String>,
pub headers: Vec<(String, String)>,
pub basic_auth: Option<BasicAuth>,
pub tls: TlsOptions,
pub http2: bool,
pub max_retries: 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(),
http2: true,
max_retries: 5,
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, Debug)]
pub struct FetchRequest<'a> {
pub path: &'a str,
pub priority: Priority,
pub validators: Option<&'a Validators>,
pub max_size: Option<u64>,
}
impl<'a> FetchRequest<'a> {
pub fn new(path: &'a str) -> FetchRequest<'a> {
FetchRequest {
path,
priority: Priority::default(),
validators: None,
max_size: None,
}
}
}
#[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 url(&self, path: &str) -> String {
format!("{}{}", self.prefix, self.target(path))
}
fn target(&self, path: &str) -> String {
format!("{}/{}", self.base, path.trim_start_matches('/'))
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct Origin {
tls: bool,
host: String,
port: u16,
}
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: Arc<rustls::ClientConfig>,
max_retries: u32,
connect_timeout: Duration,
progress_timeout: Duration,
fetch_timeout: Option<Duration>,
gate: Arc<Gate>,
h2_connection_window: u32,
pool: Mutex<HashMap<Origin, 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> {
if options.mirrors.is_empty() {
return Err(Error::Fetch("no mirror url configured".into()));
}
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),
)];
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(
"the host header is set from the mirror url".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}")))?;
headers.push((name, value));
}
if let Some(auth) = &options.basic_auth {
let encoded =
ostrya_core::base64::encode(format!("{}:{}", auth.user, auth.password).as_bytes());
let value = HeaderValue::try_from(format!("Basic {encoded}"))
.map_err(|_| Error::Fetch("invalid basic-auth credentials".into()))?;
headers.push((hyper::header::AUTHORIZATION, value));
}
let max_outstanding = options.max_outstanding.max(1);
let https = mirrors.iter().any(|mirror| mirror.origin.tls);
Ok(Fetcher {
inner: Arc::new(Inner {
mirrors,
headers,
tls: client_config(&options.tls, options.http2, https).await?,
max_retries: options.max_retries,
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> {
check_path(request.path)?;
let permit = self.inner.gate.acquire(request.priority).await;
let Some(limit) = self.inner.fetch_timeout else {
return self.rounds(&request, permit).await;
};
let fetched = within(limit, self.rounds(&request, permit)).await;
match fetched {
Some(result) => result,
None => Err(Error::Fetch(format!(
"fetch of {} timed out after {limit:?}",
request.path
))),
}
}
async fn rounds(&self, request: &FetchRequest<'_>, permit: Permit) -> Result<Fetched> {
let mut settled = vec![false; self.inner.mirrors.len()];
let mut reported: Option<Error> = None;
let mut definitive = false;
let mut round = 0;
loop {
let mut retryable = false;
for (mirror, settled) in self.inner.mirrors.iter().zip(&mut settled) {
if *settled {
continue;
}
let failure = match self.attempt(mirror, request).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,
mirror: &Mirror,
request: &FetchRequest<'_>,
) -> std::result::Result<Attempted, Failure> {
let url = mirror.url(request.path);
let connect_timeout = self.inner.connect_timeout;
let progress_timeout = self.inner.progress_timeout;
let sender = match self.inner.take_conn(&mirror.origin) {
Some(sender) => sender,
None => {
let opened = within(connect_timeout, Box::pin(self.connect(&mirror.origin))).await;
match opened {
Some(result) => result.map_err(Failure::Retry)?,
None => {
return Err(Failure::Retry(Error::Fetch(format!(
"connect to {}:{} timed out after {connect_timeout:?}",
mirror.origin.host, mirror.origin.port
))));
}
}
}
};
let (response, protocol, reuse) = match sender {
Sender::H1(mut sender) => {
let http_request = self
.build_request(mirror, request, Protocol::Http11)
.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))),
};
(response, Protocol::Http11, Some(sender))
}
Sender::H2(mut sender) => {
let http_request = self
.build_request(mirror, request, Protocol::Http2)
.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))),
};
(response, Protocol::Http2, None)
}
};
let status = response.status();
if status == StatusCode::NOT_MODIFIED {
if let Some(sender) = reuse {
self.inner.put_h1(&mirror.origin, sender);
}
return Ok(Attempted::NotModified);
}
if status != StatusCode::OK {
let failure = classify(status, &url);
self.discard(&mirror.origin, response, reuse).await;
return Err(failure);
}
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(&mirror.origin, response, reuse).await;
return Err(Failure::Fatal(Error::FetchTooLarge { limit }));
}
let protocol = match response.version() {
Version::HTTP_2 => Protocol::Http2,
_ => protocol,
};
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(),
origin: mirror.origin.clone(),
reuse,
permit: None,
done: false,
failed: None,
deadline: rt::Deadline::new(progress_timeout),
waiting: false,
}))
}
async fn discard(
&self,
origin: &Origin,
response: Response<Incoming>,
reuse: Option<H1Sender>,
) {
let Some(sender) = reuse else { return };
if content_length(response.headers()).is_none_or(|length| length > DRAIN_LIMIT) {
return;
}
let mut body = response.into_body();
let drained = within(self.inner.progress_timeout, 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(origin, sender);
}
}
fn build_request(
&self,
mirror: &Mirror,
request: &FetchRequest<'_>,
protocol: Protocol,
) -> Result<Request<NoBody>> {
let url = match protocol {
Protocol::Http11 => mirror.target(request.path),
Protocol::Http2 => mirror.url(request.path),
};
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, &mirror.authority);
}
for (name, value) in &self.inner.headers {
builder = builder.header(name, value);
}
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, origin: &Origin) -> Result<Sender> {
let tcp = rt::TcpStream::connect(&origin.host, origin.port)
.await
.map_err(|e| {
Error::Fetch(format!(
"connect to {}:{} failed: {e}",
origin.host, origin.port
))
})?;
if !origin.tls {
return self.handshake_h1(origin, FuturesIo::new(tcp)).await;
}
let server_name = rustls::pki_types::ServerName::try_from(origin.host.clone())
.map_err(|e| Error::Fetch(format!("invalid server name {}: {e}", origin.host)))?;
let stream = futures_rustls::TlsConnector::from(self.inner.tls.clone())
.connect(server_name, tcp)
.await
.map_err(|e| 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(origin, io).await
} else {
self.handshake_h1(origin, io).await
}
}
async fn handshake_h1<S>(&self, origin: &Origin, 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}",
origin.host
))
})?;
drop(rt::spawn(async move {
let _ = connection.await;
}));
Ok(Sender::H1(sender))
}
async fn handshake_h2<S>(&self, origin: &Origin, 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}", origin.host))
})?;
drop(rt::spawn(async move {
let _ = connection.await;
}));
self.inner.put_h2(origin, sender.clone());
Ok(Sender::H2(sender))
}
}
impl Inner {
fn take_conn(&self, origin: &Origin) -> Option<Sender> {
let mut pool = self.pool.lock().expect("fetcher pool mutex");
let entry = pool.get_mut(origin)?;
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, origin: &Origin, sender: H1Sender) {
if sender.is_closed() {
return;
}
let mut pool = self.pool.lock().expect("fetcher pool mutex");
pool.entry(origin.clone()).or_default().h1.push(sender);
}
fn put_h2(&self, origin: &Origin, sender: H2Sender) {
let mut pool = self.pool.lock().expect("fetcher pool mutex");
let entry = pool.entry(origin.clone()).or_default();
match &entry.h2 {
Some(pooled) if !pooled.is_closed() => {}
_ => entry.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>,
origin: Origin,
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.origin, 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 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 parse_mirror(url: &str) -> Result<Mirror> {
let scheme = url
.split_once("://")
.map(|(scheme, _)| scheme)
.ok_or_else(|| Error::Fetch(format!("url {url} is not an absolute http or https 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 uri = Uri::try_from(url).map_err(|e| Error::Fetch(format!("invalid url {url}: {e}")))?;
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"
)));
}
if uri
.authority()
.is_some_and(|authority| authority.as_str().contains('@'))
{
return Err(Error::Fetch(format!(
"mirror url {url} carries userinfo, which the fetcher does not send: \
pass credentials as FetcherOptions::basic_auth"
)));
}
let literal = uri
.host()
.ok_or_else(|| Error::Fetch(format!("url {url} has no host")))?;
let host = literal
.strip_prefix('[')
.and_then(|inner| inner.strip_suffix(']'))
.unwrap_or(literal)
.to_string();
let default_port = if tls { 443 } else { 80 };
let port = uri.port_u16().unwrap_or(default_port);
let scheme = if tls { "https" } else { "http" };
let authority = if port == default_port {
literal.to_string()
} else {
format!("{literal}:{port}")
};
Ok(Mirror {
origin: Origin { tls, host, port },
authority: HeaderValue::try_from(&authority)
.map_err(|_| Error::Fetch(format!("url {url} has an unusable host")))?,
prefix: format!("{scheme}://{authority}"),
base: uri.path().trim_end_matches('/').to_string(),
})
}
fn content_length(headers: &hyper::HeaderMap) -> Option<u64> {
headers
.get(hyper::header::CONTENT_LENGTH)?
.to_str()
.ok()?
.parse()
.ok()
}
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 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> {
futures_lite::future::or(async { Some(future.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.url("objects/ab/cd.filez"),
"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.url("summary"), "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();
assert_eq!(ported.url("/config"), "http://127.0.0.1:8080/r/config");
assert_eq!(ported.target("/config"), "/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.url("summary"), "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.url("summary"), "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 err = Fetcher::new(FetcherOptions::default()).await.unwrap_err();
assert!(err.to_string().contains("no mirror"), "{err}");
let mut options = FetcherOptions::new("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 = FetcherOptions::new("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}");
});
}
#[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(FetcherOptions::new("http://example.com/r"))
.await
.unwrap();
let mirror = &fetcher.inner.mirrors[0];
let request = fetcher
.build_request(mirror, &FetchRequest::new("refs/heads/a"), Protocol::Http11)
.unwrap();
assert_eq!(request.uri(), "/r/refs/heads/a");
});
}
#[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 tls_options(url: &str) -> FetcherOptions {
FetcherOptions {
tls: TlsOptions {
roots: TrustRoots::Pem(
include_bytes!("../../../tests/fixtures/tls/ca.pem").to_vec(),
),
..TlsOptions::default()
},
..FetcherOptions::new(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())],
..FetcherOptions::new("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())],
..FetcherOptions::new("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();
}
}