Skip to main content

ostrya_fetch/
lib.rs

1#![forbid(unsafe_code)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4//! An async HTTP/1.1 and HTTP/2 client over rustls, for the mirrors of a remote.
5//!
6//! A caller builds a [`Fetcher`] from the mirrors, headers, credentials, proxy,
7//! TLS configuration, retry limits, and deadlines of one remote. The fetcher
8//! downloads files with `GET` and sends uploads with `POST` or `DELETE`. A
9//! response body streams in bounded chunks, so no object is held whole in memory.
10//!
11//! The [`Target`] of a request is a path under each mirror, a path with a
12//! query string under each mirror, or an absolute URL. The fetcher sends a
13//! path and a query as written, so the caller escapes them.
14//!
15//! # Entry points
16//!
17//! - [`Fetcher::new`] builds a fetcher from [`FetcherOptions`].
18//! - [`Fetcher::fetch`] sends a [`FetchRequest`] and returns a [`Fetched`].
19//! - [`Body`] streams a response body in bounded chunks.
20//! - [`Fetcher::refetching`] returns a [`Refetch`], which fetches a failed body again.
21//! - [`Fetcher::upload`] sends an [`UploadRequest`] and returns an [`Uploaded`].
22//! - [`UploadBody`] gives an upload body whole or streams it from an [`UploadWriter`].
23//! - [`Error`] is the error of each fallible operation of the crate.
24//!
25//! # Modules
26//!
27//! - [`gate`]: the priority admission gate that bounds concurrent work.
28//!
29//! # Features
30//!
31//! - `smol` (default): the `smol` backend of `ostrya-rt`.
32//! - `tokio`: the `tokio` backend of `ostrya-rt`, with tokio I/O impls on [`Body`] and [`UploadWriter`].
33//!
34//! # Examples
35//!
36//! ```no_run
37//! use futures_lite::AsyncReadExt;
38//! use ostrya_fetch::{FetchRequest, Fetched, Fetcher, FetcherOptions};
39//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
40//! let fetcher = Fetcher::new(FetcherOptions::new("https://example.com/repo")).await?;
41//! if let Fetched::Body(mut body) = fetcher.fetch(FetchRequest::path("config")).await? {
42//!     let mut config = Vec::new();
43//!     body.read_to_end(&mut config).await?;
44//! }
45//! # Ok(())
46//! # }
47//! ```
48
49use std::borrow::Cow;
50use std::collections::HashMap;
51use std::future::Future;
52use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
53use std::sync::{Arc, Mutex, MutexGuard};
54use std::time::{Duration, Instant};
55
56use futures_io::{AsyncRead, AsyncWrite};
57use hyper::body::{Body as _, Bytes, Frame, Incoming, SizeHint};
58use hyper::header::{HeaderName, HeaderValue};
59use hyper::http::uri::Scheme;
60use hyper::{Method, Request, Response, StatusCode, Uri, Version};
61use ostrya_rt as rt;
62use std::pin::Pin;
63use std::task::{Context, Poll, Waker, ready};
64
65mod error;
66pub mod gate;
67mod io;
68mod tls;
69
70pub use self::error::{Error, Result};
71
72use gate::{Gate, Permit};
73#[doc(hidden)]
74pub use io::{FuturesIo, RtExecutor, RtTimer, WriteVectored};
75use tls::{ClientConfigs, client_config};
76pub use tls::{ClientIdentity, TlsOptions, TrustRoots};
77#[doc(hidden)]
78pub use tls::{client_cert_verifier, server_config};
79
80/// The `User-Agent` value of each request. A `User-Agent` header of the fetcher
81/// or of the request replaces it.
82const USER_AGENT: &str = concat!("ostrya/", env!("CARGO_PKG_VERSION"));
83
84/// The one content coding that a fetch accepts, which is no coding. Each
85/// request asks for it, and a response that declares another coding fails the
86/// attempt. An `Accept-Encoding` header of the fetcher or of the request
87/// replaces the value that the fetcher sends.
88const IDENTITY: &str = "identity";
89
90/// The one transfer coding that a response can declare. It frames a message,
91/// and the connection removes the framing, so the caller gets the body as the
92/// remote wrote it. The fetcher sends no `TE` header, so another transfer coding
93/// is a server fault. A response that declares one fails the attempt.
94const CHUNKED: &str = "chunked";
95
96/// The variables that [`Proxy::Environment`] reads, in the order of preference
97/// of a lookup.
98///
99/// The list holds the lower-case name of each variable, and the upper-case name
100/// where the lookup reads one. Nothing reads `HTTP_PROXY`. A CGI gateway gives a
101/// request header `Proxy` to the program as `HTTP_PROXY`, so a client can set
102/// that variable with a request.
103const PROXY_VARIABLES: [&str; 7] = [
104    "http_proxy",
105    "https_proxy",
106    "HTTPS_PROXY",
107    "all_proxy",
108    "ALL_PROXY",
109    "no_proxy",
110    "NO_PROXY",
111];
112
113/// The scheme of a proxy URL. A proxy connection opens with this scheme alone.
114const PROXY_SCHEME: &str = "http://";
115
116/// The statuses at which a fetch follows a redirect. A fetch is a GET, so none
117/// of the five changes the method of the next hop. The statuses that differ in
118/// the method are one case here. An upload follows [`UPLOAD_REDIRECTS`] alone.
119const REDIRECTS: [StatusCode; 5] = [
120    StatusCode::MOVED_PERMANENTLY,
121    StatusCode::FOUND,
122    StatusCode::SEE_OTHER,
123    StatusCode::TEMPORARY_REDIRECT,
124    StatusCode::PERMANENT_REDIRECT,
125];
126
127/// The statuses at which an upload follows a redirect. These two keep the
128/// method and the body, so the next hop sends the same request again.
129const UPLOAD_REDIRECTS: [StatusCode; 2] = [
130    StatusCode::TEMPORARY_REDIRECT,
131    StatusCode::PERMANENT_REDIRECT,
132];
133
134/// The message for a layer that sets both credentials and an `Authorization`
135/// header. The layer does not state which of the two the request sends. A
136/// choice of one sends a credential that the caller did not choose.
137const AMBIGUOUS_AUTHORIZATION: &str =
138    "basic-auth credentials and an authorization header both set Authorization: pass one of them";
139
140/// The message for a layer that sets both a bearer token and an
141/// `Authorization` header, for the reason that [`AMBIGUOUS_AUTHORIZATION`]
142/// states.
143const AMBIGUOUS_BEARER: &str =
144    "a bearer token and an authorization header both set Authorization: pass one of them";
145
146/// The message for a layer that sets both basic-auth credentials and a bearer
147/// token, for the reason that [`AMBIGUOUS_AUTHORIZATION`] states.
148const BASIC_AND_BEARER: &str =
149    "basic-auth credentials and a bearer token both set Authorization: pass one of them";
150
151/// The message for a layer that sets a `Host` header. The header states the
152/// authority of the destination, and the fetcher reads it from the URL.
153const HOST_COMES_FROM_THE_URL: &str = "the host header is set from the url the request is sent to";
154
155/// The header names that the connection layer sets.
156///
157/// These names frame a request, or state what happens to the connection that
158/// carries it. A value of the caller puts the wire and the connection pool out
159/// of step. For example, a `Content-Length` of the caller ends the HTTP/1.1
160/// connection under a pooled sender. The next fetch over that fetcher then
161/// fails on a channel that the connection task dropped.
162const CONNECTION_HEADERS: [&str; 9] = [
163    "connection",
164    "content-length",
165    "expect",
166    "keep-alive",
167    "proxy-connection",
168    "te",
169    "trailer",
170    "transfer-encoding",
171    "upgrade",
172];
173
174/// The size of the frames of an upload body.
175///
176/// The writer fills one frame while the slot holds the frame that it handed
177/// over last, so the writer holds at most two frames. hyper takes a body given
178/// whole in frames of this size.
179///
180/// The connection buffers more of the body. Over HTTP/1.1, hyper takes another
181/// frame while it holds fewer than 16 frames and less than 408 KiB. Over HTTP/2,
182/// it holds up to two frames.
183const UPLOAD_FRAME: usize = 64 * 1024;
184
185/// The size under which a flush hands over a copy of its part-filled frame and
186/// keeps the buffer. So a small frame that waits in the connection does not hold
187/// a whole frame of memory.
188const SMALL_FRAME: usize = 4 * 1024;
189
190/// The longest idle time in the pool of an HTTP/1.1 connection that an upload
191/// takes. [`Inner::take_upload`] states why an upload takes only a connection
192/// that became idle a short time ago.
193const UPLOAD_IDLE: Duration = Duration::from_secs(2);
194
195/// The largest declared response body that a failed attempt reads to the end,
196/// so that its HTTP/1.1 connection goes back to the pool. If the declared length
197/// is larger, or if the response declares no length, the fetcher closes the
198/// connection.
199const DRAIN_LIMIT: u64 = 64 * 1024;
200
201/// The HTTP/2 flow-control window of each stream. The default of hyper is
202/// 64 KiB, which limits the throughput of one stream on a link with a high
203/// bandwidth-delay product. An object fetch is one stream, so this window limits
204/// it.
205const H2_STREAM_WINDOW: u32 = 2 * 1024 * 1024;
206
207/// The largest flow-control window the protocol allows, 2^31 - 1.
208const H2_MAX_WINDOW: u32 = i32::MAX as u32;
209
210/// How often an HTTP/2 connection with an open stream pings its peer, and how
211/// long it waits for the reply. Both values are less than the default
212/// [`progress_timeout`](FetcherOptions::progress_timeout). So the ping reports a
213/// peer that went away, and no read waits for ever.
214const H2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15);
215const H2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(15);
216
217/// The priority of a request that waits for admission to a [`Fetcher`].
218///
219/// If [`max_outstanding`](FetcherOptions::max_outstanding) requests are in
220/// flight, a new request waits in a queue. The queue serves the highest
221/// priority first, and requests of one priority in arrival order. The
222/// [`gate`] module holds the queue.
223#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
224pub enum Priority {
225    /// The lowest priority, for bulk content.
226    Low,
227    /// The middle priority, which is the default.
228    #[default]
229    Normal,
230    /// The highest priority, for metadata that other work waits for.
231    High,
232}
233
234/// The HTTP version of a response.
235#[derive(Clone, Copy, Debug, Eq, PartialEq)]
236pub enum Protocol {
237    /// HTTP/1.1.
238    Http11,
239    /// HTTP/2.
240    Http2,
241}
242
243/// The credentials of HTTP basic authentication.
244///
245/// The [`Debug`] output shows the user name and a fixed word in place of the
246/// password. So the log of a struct that holds credentials does not show the
247/// password.
248#[derive(Clone, Eq, PartialEq)]
249pub struct BasicAuth {
250    /// The user name.
251    pub user: String,
252    /// The password.
253    pub password: String,
254}
255
256impl std::fmt::Debug for BasicAuth {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258        f.debug_struct("BasicAuth")
259            .field("user", &self.user)
260            .field("password", &"<redacted>")
261            .finish()
262    }
263}
264
265/// A token for `Authorization: Bearer`.
266///
267/// The fetcher sends the token as written, so the token must have the token68
268/// syntax of HTTP authentication. This is one or more ASCII letters, digits,
269/// `-`, `.`, `_`, `~`, `+`, or `/`, then any number of `=`. If the token has
270/// another form, [`Error::Fetch`] occurs. A request fails before admission, and
271/// [`FetcherOptions::bearer_token`] fails [`Fetcher::new`]. The message holds
272/// no part of the token.
273///
274/// The [`Debug`] output shows a fixed word in place of the token. So the log of
275/// a struct that holds a token does not show it.
276#[derive(Clone, Eq, PartialEq)]
277pub struct BearerToken {
278    /// The token.
279    pub token: String,
280}
281
282impl std::fmt::Debug for BearerToken {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.debug_struct("BearerToken")
285            .field("token", &"<redacted>")
286            .finish()
287    }
288}
289
290/// The validators of a response, which make a later fetch conditional.
291#[derive(Clone, Debug, Default, Eq, PartialEq)]
292pub struct Validators {
293    /// The `ETag` of the response, sent back as `If-None-Match`.
294    pub etag: Option<String>,
295    /// The `Last-Modified` of the response, sent back as `If-Modified-Since`.
296    pub last_modified: Option<String>,
297}
298
299impl Validators {
300    /// Returns `true` if no validator holds a value.
301    pub fn is_empty(&self) -> bool {
302        self.etag.is_none() && self.last_modified.is_none()
303    }
304}
305
306/// The lowest transfer rate that a fetch accepts.
307///
308/// The fetcher samples the rate of a transfer once a second. Each sample is the
309/// bytes of the last five seconds divided by five. In the first five seconds, a
310/// sample is the bytes so far divided by the whole seconds so far.
311///
312/// If the rate stays at `limit` or less for `time` without a break, the
313/// transfer fails as a transport failure. A transfer starts under the limit,
314/// because it carried no bytes. A sample over the limit starts the count of
315/// `time` again. For the response head, the count starts at the start of the
316/// attempt, and for the body, at the first read.
317#[derive(Clone, Copy, Debug, Eq, PartialEq)]
318pub struct LowSpeed {
319    /// The rate in bytes per second that a transfer must keep.
320    ///
321    /// A zero fails [`Fetcher::new`].
322    pub limit: u32,
323    /// The longest time that the rate can stay at `limit` or less.
324    ///
325    /// A zero fails [`Fetcher::new`]. The fetcher samples the rate once a
326    /// second, so a part of a second counts as a whole second.
327    pub time: Duration,
328}
329
330impl LowSpeed {
331    /// Returns `time` rounded up to whole seconds. The addition saturates at the
332    /// maximum and does not wrap.
333    fn whole_seconds(&self) -> Duration {
334        let partial = u64::from(self.time.subsec_nanos() > 0);
335        Duration::from_secs(self.time.as_secs().saturating_add(partial))
336    }
337}
338
339/// How often the low-speed rule samples the rate of a body.
340const SAMPLE_PERIOD: Duration = Duration::from_secs(1);
341
342/// The number of samples over which the low-speed rule measures the rate.
343const RATE_SPAN: usize = 5;
344
345/// The proxy through which a [`Fetcher`] reaches each origin.
346///
347/// [`Fetcher::new`] resolves each form once, and refuses a proxy URL that the
348/// fetcher cannot connect through. A request does not read the environment
349/// again.
350///
351/// The [`Debug`] output does not show the userinfo of a proxy URL. So the log
352/// of a struct that holds proxy credentials does not show them.
353///
354/// # Variables
355///
356/// `http_proxy` serves `http` origins, and `https_proxy` serves `https`
357/// origins. If the variable of the scheme is unset, `all_proxy` serves the
358/// origin. The fetcher also reads each name in upper case, except `HTTP_PROXY`.
359/// A CGI gateway gives a request header `Proxy` to the program as `HTTP_PROXY`,
360/// so a client can set that variable with a request.
361///
362/// The lower-case name has priority over the upper-case name. An empty value
363/// counts as unset.
364///
365/// # White space
366///
367/// If the value of `http_proxy`, `https_proxy`, or `all_proxy`, or of an
368/// upper-case name, has white space at its start or end, [`Fetcher::new`]
369/// fails with [`Error::Unsupported`]. A value of white space alone also fails.
370/// It is not empty, so it counts as set and hides the upper-case name.
371///
372/// The fetcher checks the value of each variable that the lookup reads, when it
373/// builds the fetcher. It checks a variable also if no request goes through
374/// that proxy. The message names the variable and holds no part of the value,
375/// which can hold a password. The fetcher trims the URL of [`Proxy::Url`] and
376/// each `no_proxy` entry.
377///
378/// # Proxy URL
379///
380/// A proxy URL has the form `http://host[:port]`, and the port is 80 by
381/// default. The URL has no path other than `/`, no query, and no fragment. The
382/// fetcher percent-decodes the userinfo and sends it to the proxy as
383/// `Proxy-Authorization: Basic`.
384///
385/// Any other form fails [`Fetcher::new`] with [`Error::Unsupported`], for
386/// example an `https://` or a `socks5://` proxy. This applies to a URL from the
387/// options and to a URL from the environment. The message names the value
388/// without its userinfo.
389///
390/// # Exemptions
391///
392/// `no_proxy` is a comma-separated list of the origins that the two
393/// environment forms exempt. An entry holds a host text, with one leading `.`
394/// if it is written with one, and `:port` if it names a port. The fetcher
395/// ignores the space around an entry. An entry that names no host exempts
396/// nothing, for example an empty entry, `.`, or `:8080`.
397///
398/// If the port text of an entry is not a number from 0 to 65535, the whole
399/// entry is one host text. No origin holds that text, so the entry exempts
400/// nothing.
401///
402/// `*` as a whole entry exempts all hosts. It is the one wildcard that the list
403/// reads. `*.example.com` is a host text, and no origin holds it.
404///
405/// An entry matches an origin if it equals the host, or if the host ends with a
406/// `.` and the entry. The fetcher removes one leading `.` from the entry first,
407/// so `.example.com` and `example.com` both exempt `a.example.com`. A second
408/// leading `.` is part of the host text of the entry. An entry with `:port`
409/// matches that port alone.
410///
411/// The match compares the host text of the URL, with ASCII case ignored. It
412/// never compares the address of the host. So `localhost` exempts no origin
413/// written as `127.0.0.1`, and an entry that is an IP literal matches that text
414/// alone.
415///
416/// An entry in CIDR notation names no network. The fetcher reads it as a host
417/// text, which no origin holds. This is a divergence from curl 7.86 and later,
418/// which read such an entry as a network. An empty `no_proxy` value exempts
419/// nothing, and [`Proxy::Url`] reads no exemptions.
420///
421/// # Cleartext origins
422///
423/// The fetcher reaches a cleartext origin behind a proxy over a connection to
424/// the proxy. The request carries the absolute-form target, the whole
425/// `http://host/path` URL, and the `Host` header of the origin. Such a
426/// connection uses HTTP/1.1, because cleartext HTTP/2 needs prior knowledge or
427/// an upgrade.
428///
429/// The pool keeps such a connection under the proxy endpoint, so one proxy
430/// connection carries requests for all cleartext origins. The pool key marks a
431/// connection as a proxy connection. So the pool never gives a direct
432/// connection to the proxy endpoint to a proxied request, or the reverse. The
433/// two request forms differ, and a server answers the unexpected form with a
434/// 404.
435///
436/// # TLS origins
437///
438/// The fetcher reaches a TLS origin behind a proxy over a `CONNECT` tunnel. The
439/// request names the target as `host:port`. The port is always written, and an
440/// IPv6 literal keeps its brackets. If the proxy URL holds userinfo, the
441/// `CONNECT` carries the same `Proxy-Authorization`.
442///
443/// On a 2xx answer, the fetcher gets the tunneled socket back. The TLS
444/// handshake, the ALPN selection, and the pool entry are then the same as for a
445/// direct connection to that origin. Nothing follows a `CONNECT` response, so a
446/// byte that arrives before the client sends fails the connect.
447///
448/// A non-2xx answer is a retryable failure, and a 407 is a definitive failure.
449/// Both are [`Error::Fetch`] and name the proxy.
450/// [`connect_timeout`](FetcherOptions::connect_timeout) is the limit for all
451/// these steps together: the connect to the proxy, the `CONNECT` exchange, the
452/// TLS handshake, and the HTTP handshake.
453///
454/// # Proxy credential
455///
456/// The proxy credential belongs to the connection layer. It goes to the proxy
457/// on a proxied cleartext request and on a `CONNECT`, and to no origin. It is
458/// not in the merged header list, so the cleartext credential check and the
459/// redirect scoping do not read it. A tunnel carries no part of it.
460///
461/// A `Proxy-Authorization` header that a caller sets keeps the meaning that it
462/// has without a proxy. It is a credential in the merged list. A fetch refuses
463/// it for a cleartext destination, as it refuses an `Authorization` or a
464/// `Cookie` header.
465///
466/// On a proxied cleartext request, the header of the caller replaces the proxy
467/// credential of the fetcher. Two values for one header give two answers to one
468/// question. Over a tunnel, the two never meet. The header of the caller goes
469/// to the origin, and the credential of the fetcher goes to the proxy.
470///
471/// # Redirects
472///
473/// The fetcher makes the proxy decision for each hop, from the origin of that
474/// hop. So a redirect to another origin goes the same way as a route that names
475/// that origin. A proxy does not change the cleartext rule: a cleartext origin
476/// is cleartext also through a proxy.
477///
478/// # Examples
479///
480/// ```no_run
481/// use ostrya_fetch::{Fetcher, FetcherOptions, Proxy};
482/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
483/// let mut options = FetcherOptions::new("https://example.com/repo");
484/// options.proxy = Proxy::Variables(vec![
485///     ("https_proxy".into(), "http://proxy.example.com:3128".into()),
486///     ("no_proxy".into(), ".internal.example.com".into()),
487/// ]);
488/// let fetcher = Fetcher::new(options).await?;
489/// # let _ = fetcher;
490/// # Ok(())
491/// # }
492/// ```
493#[derive(Clone, Default)]
494pub enum Proxy {
495    /// A direct connection, whatever the environment holds.
496    None,
497    /// The proxy variables of the process environment.
498    ///
499    /// [`Fetcher::new`] reads the variables once. This is the default.
500    /// [Variables](Proxy#variables) states the names, and
501    /// [White space](Proxy#white-space) states the check of each value.
502    #[default]
503    Environment,
504    /// The proxy variables, given as name and value pairs.
505    ///
506    /// The fetcher does not read the process environment. It ignores a name
507    /// that the environment forms do not read. Of two entries of one name, the
508    /// first entry with a value counts. [White space](Proxy#white-space) states
509    /// the check of each value.
510    Variables(Vec<(String, String)>),
511    /// One `http://` proxy URL for all origins.
512    ///
513    /// The fetcher sends the userinfo of the URL as
514    /// `Proxy-Authorization: Basic`. No origin is exempt, because the fetcher
515    /// reads the environment for neither the proxy nor the exemptions. The
516    /// fetcher trims white space around the URL.
517    Url(String),
518}
519
520impl std::fmt::Debug for Proxy {
521    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
522        match self {
523            Proxy::None => f.write_str("None"),
524            Proxy::Environment => f.write_str("Environment"),
525            Proxy::Variables(variables) => f
526                .debug_tuple("Variables")
527                .field(&RedactedVariables { variables })
528                .finish(),
529            Proxy::Url(url) => f.debug_tuple("Url").field(&RedactedUrl::url(url)).finish(),
530        }
531    }
532}
533
534/// The proxy variables in a [`Debug`] output: a list of name and value pairs.
535///
536/// Each value shows as [`RedactedUrl`] shows an absolute URL.
537struct RedactedVariables<'a> {
538    variables: &'a [(String, String)],
539}
540
541impl std::fmt::Debug for RedactedVariables<'_> {
542    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543        let RedactedVariables { variables } = self;
544        f.debug_list()
545            .entries(
546                variables
547                    .iter()
548                    .map(|(name, value)| (name, RedactedUrl::url(value))),
549            )
550            .finish()
551    }
552}
553
554/// The headers in a [`Debug`] output: a list of name and `<redacted>` pairs.
555///
556/// A header value can be a credential, so no value shows. Each call of `names`
557/// gives the name of each header value, in order.
558struct RedactedHeaders<F> {
559    names: F,
560}
561
562impl<'a, F, I> std::fmt::Debug for RedactedHeaders<F>
563where
564    F: Fn() -> I,
565    I: Iterator<Item = &'a str>,
566{
567    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
568        f.debug_list()
569            .entries((self.names)().map(|name| (name, "<redacted>")))
570            .finish()
571    }
572}
573
574/// A URL or a request path in a [`Debug`] output, with no userinfo, query
575/// value, or fragment value.
576///
577/// The userinfo of an absolute URL is the text after the `://` of the scheme,
578/// up to and including the last `@`. When the text has no valid scheme before
579/// the first `://`, the userinfo is the text from the start up to and including
580/// the last `@`. A password can hold a `/`, `?`, or `#`, so the output removes
581/// the userinfo first and leaves no marker for it. Then a query shows as
582/// `?<redacted>`, and a fragment shows as `#<redacted>`. A path has no
583/// userinfo. Each other part shows as the [`Debug`] output of a `str` shows it.
584struct RedactedUrl<'a> {
585    text: &'a str,
586    /// `true` if `text` is an absolute URL, which can hold userinfo.
587    absolute: bool,
588}
589
590impl<'a> RedactedUrl<'a> {
591    /// Shows an absolute URL.
592    fn url(text: &'a str) -> RedactedUrl<'a> {
593        RedactedUrl {
594            text,
595            absolute: true,
596        }
597    }
598
599    /// Shows a request path.
600    fn path(text: &'a str) -> RedactedUrl<'a> {
601        RedactedUrl {
602            text,
603            absolute: false,
604        }
605    }
606}
607
608impl std::fmt::Debug for RedactedUrl<'_> {
609    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
610        use std::fmt::Write as _;
611
612        let RedactedUrl { text, absolute } = *self;
613        let (scheme, rest) = if absolute {
614            let end = scheme_len(text);
615            let rest = &text[end..];
616            let rest = rest.rfind('@').map_or(rest, |at| &rest[at + 1..]);
617            (&text[..end], rest)
618        } else {
619            ("", text)
620        };
621        let (shown, query, fragment) = match rest.find(['?', '#']) {
622            None => (rest, false, false),
623            Some(at) if rest[at..].starts_with('#') => (&rest[..at], false, true),
624            Some(at) => (&rest[..at], true, rest[at..].contains('#')),
625        };
626        // The `Debug` output of a `str` escapes each `char` as
627        // `char::escape_debug` does, except `'`, which it writes as it is.
628        f.write_char('"')?;
629        for c in scheme.chars().chain(shown.chars()) {
630            if c == '\'' {
631                f.write_char(c)?;
632            } else {
633                for escaped in c.escape_debug() {
634                    f.write_char(escaped)?;
635                }
636            }
637        }
638        if query {
639            f.write_str("?<redacted>")?;
640        }
641        if fragment {
642            f.write_str("#<redacted>")?;
643        }
644        f.write_char('"')
645    }
646}
647
648/// A list of URLs in a [`Debug`] output, each one shown as [`RedactedUrl`]
649/// shows an absolute URL.
650struct RedactedUrls<'a> {
651    urls: &'a [String],
652}
653
654impl std::fmt::Debug for RedactedUrls<'_> {
655    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
656        let RedactedUrls { urls } = self;
657        f.debug_list()
658            .entries(urls.iter().map(|url| RedactedUrl::url(url)))
659            .finish()
660    }
661}
662
663/// The options of a [`Fetcher`]: the remote, the credentials, and the limits.
664///
665/// [`FetcherOptions::default`] sets each field to the default that the field
666/// states. [`FetcherOptions::new`] also sets one mirror.
667///
668/// The [`Debug`] output shows the name of each header, and `<redacted>` in
669/// place of its value. The output also shows no password of `basic_auth`, no
670/// token of `bearer_token`, no client key or passphrase, and no userinfo of a
671/// proxy URL. Each mirror URL shows with no userinfo. A query shows as
672/// `?<redacted>`, and a fragment shows as `#<redacted>`.
673#[derive(Clone)]
674pub struct FetcherOptions {
675    /// The base URLs, tried in order for each request that names a
676    /// [`Target::Path`] or a [`Target::PathQuery`].
677    ///
678    /// A remote with a mirror list gives one entry for each mirror. A base URL
679    /// is a scheme, an authority, and a path. A query string or userinfo fails
680    /// [`Fetcher::new`], so neither part of a base URL reaches the wire. A
681    /// request target is the base path, then `/` and the request path, then
682    /// `?` and the query of a [`Target::PathQuery`].
683    ///
684    /// An empty list serves [`Target::Url`] requests alone. The default is an
685    /// empty list.
686    pub mirrors: Vec<String>,
687    /// The extra headers of each request, to each destination and redirect hop.
688    ///
689    /// A request header of the same name replaces an entry. The fetcher sets
690    /// `User-Agent` and `Accept-Encoding: identity`, and an entry of one of
691    /// these names replaces the value of the fetcher. Other headers go as
692    /// written. The default is an empty list.
693    ///
694    /// An `Authorization`, `Proxy-Authorization`, or `Cookie` header is a
695    /// credential, because its value is a secret, whatever it holds. A
696    /// credential goes to the origin that the route names, and to a redirect hop
697    /// at that origin alone.
698    ///
699    /// [`Fetcher::new`] refuses these entries:
700    ///
701    /// - a credential header, if a mirror is cleartext `http` and
702    ///   [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
703    ///   is `false`
704    /// - a `Host` header
705    /// - a header that the connection layer sets: a framing name or a
706    ///   hop-by-hop name
707    /// - an `Authorization` header beside
708    ///   [`basic_auth`](FetcherOptions::basic_auth)
709    /// - an `Authorization` header beside
710    ///   [`bearer_token`](FetcherOptions::bearer_token)
711    /// - an invalid header name or value.
712    pub headers: Vec<(String, String)>,
713    /// The credentials for `Authorization: Basic`, sent with each request.
714    ///
715    /// The credentials go to each destination, and to a redirect hop at the
716    /// origin that the route names. [`FetchRequest::basic_auth`] replaces them
717    /// for one request. The default is `None`.
718    ///
719    /// Each mirror must be `https`, unless
720    /// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
721    /// is `true`. [`Fetcher::new`] refuses a cleartext mirror, so the
722    /// credentials go in cleartext only with that permission. An
723    /// `Authorization` entry in [`headers`](FetcherOptions::headers) or a
724    /// [`bearer_token`](FetcherOptions::bearer_token) beside these also fails
725    /// [`Fetcher::new`], because each of them sets the same header.
726    pub basic_auth: Option<BasicAuth>,
727    /// The token for `Authorization: Bearer`, sent with each request.
728    ///
729    /// The token goes to each destination, and to a redirect hop at the origin
730    /// that the route names. Each of these replaces it for one request:
731    /// [`FetchRequest::basic_auth`], [`UploadRequest::basic_auth`],
732    /// [`UploadRequest::bearer_token`], or an `Authorization` entry in the
733    /// headers of the request. The default is `None`.
734    ///
735    /// [`Fetcher::new`] refuses a token that does not have the token68 syntax
736    /// that [`BearerToken`] states. It also refuses the token beside
737    /// [`basic_auth`](FetcherOptions::basic_auth), or beside an
738    /// `Authorization` entry in [`headers`](FetcherOptions::headers), because
739    /// each of them sets the same header.
740    ///
741    /// Each mirror must be `https`, unless
742    /// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
743    /// is `true`.
744    pub bearer_token: Option<BearerToken>,
745    /// The permission for a credential to reach a cleartext origin.
746    ///
747    /// If this is `true`, [`Fetcher::new`] does not refuse a cleartext mirror
748    /// beside a credential: [`basic_auth`](FetcherOptions::basic_auth),
749    /// [`bearer_token`](FetcherOptions::bearer_token), or a credential header
750    /// in [`headers`](FetcherOptions::headers). A fetch or an upload also does
751    /// not refuse a credential for a cleartext destination, whatever the flag
752    /// of the request is. [`FetchRequest::allow_cleartext_credentials`] states
753    /// that rule.
754    ///
755    /// The redirect rules apply with this flag. A hop at another origin gets no
756    /// credential, and a hop from `https` to `http` is refused. The default is
757    /// `false`.
758    ///
759    /// A caller sets it for a server on a loopback address, or for a server
760    /// behind a proxy that terminates TLS.
761    pub allow_cleartext_credentials: bool,
762    /// The trust anchors and the client certificate for `https` mirrors.
763    ///
764    /// The default is [`TlsOptions::default`]: [`TrustRoots::System`] and no
765    /// client identity.
766    pub tls: TlsOptions,
767    /// The proxy through which the fetcher reaches an origin.
768    ///
769    /// [`Fetcher::new`] resolves the value once, and a request does not read it
770    /// again. It refuses a proxy URL that is not `http://host[:port]`, and a
771    /// proxy variable with [white space](Proxy#white-space) around its value.
772    /// The default is [`Proxy::Environment`], the proxy that the process
773    /// environment names.
774    pub proxy: Proxy,
775    /// The switch that offers HTTP/2 in ALPN.
776    ///
777    /// If this is `false`, the fetcher uses HTTP/1.1, also with a server that
778    /// supports HTTP/2. The default is `true`.
779    pub http2: bool,
780    /// The number of times that a fetch repeats a round after a retryable
781    /// failure.
782    ///
783    /// [`Fetcher::fetch`] states the retry rules. The default is 5.
784    pub max_retries: u32,
785    /// The number of redirects that one attempt against one destination
786    /// follows.
787    ///
788    /// The attempt follows a 301, 302, 303, 307, or 308 while it followed fewer
789    /// redirects than this value. If the next one names a URL, the attempt fails
790    /// definitively with [`Error::RedirectLimit`]. If it names no URL, the
791    /// attempt reports its own status.
792    ///
793    /// Zero follows nothing, so each of those statuses is then a definitive
794    /// answer. The count belongs to one attempt, so a repeated round counts
795    /// again from the destination that the route names. [`Fetcher::fetch`]
796    /// states the redirect rules. The default is 10.
797    pub max_redirects: u32,
798    /// The number of requests in flight at one time.
799    ///
800    /// The fetcher admits this many requests at a time, and serves the queue in
801    /// [`Priority`] order. A request holds its permit until the fetch fails, or
802    /// until its response body reaches its end or is dropped. A body in flight
803    /// occupies a connection, so it keeps the permit.
804    ///
805    /// The default is 8. The fetcher admits at least one request, so 0 admits
806    /// one request.
807    pub max_outstanding: usize,
808    /// The time limit to open a connection.
809    ///
810    /// The limit applies to the TCP connect, the TLS handshake, and the HTTP
811    /// handshake together. Through a proxy, it also applies to the connect to
812    /// the proxy and to the `CONNECT` exchange.
813    ///
814    /// The TCP connect resolves the host name, then races the addresses that
815    /// the resolver gave. A new attempt starts every 250ms, and an attempt that
816    /// fails starts the next one immediately. So the limit includes the
817    /// resolution and all attempts.
818    ///
819    /// The expiry is a transport failure. So it is retryable, and the fetch
820    /// tries the next destination. The default is 30 s.
821    pub connect_timeout: Duration,
822    /// The longest time that a response can go without bytes.
823    ///
824    /// The window applies to the wait for the response head and to each stall
825    /// of the body. It measures the silence since a read asked for bytes. So it
826    /// limits silence, and leaves the transfer time unlimited.
827    ///
828    /// The window runs from the read that finds no bytes until bytes arrive.
829    /// After a read found no bytes, the window runs also when no read is
830    /// outstanding. A body that no read found empty is not on the clock.
831    ///
832    /// If the body stalls, the read fails with
833    /// [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut), and each
834    /// later read fails the same way. An expired wait for the head is a
835    /// retryable transport failure, so the fetch tries the next destination.
836    /// The default is 60 s.
837    pub progress_timeout: Duration,
838    /// The lowest transfer rate that an attempt accepts, as [`LowSpeed`]
839    /// states.
840    ///
841    /// The response head must arrive within `time` of the start of the attempt,
842    /// rounded up to whole seconds, redirects included. The rate of the body
843    /// counts from its first read. So the fetcher does not measure a body that
844    /// waits for its consumer before the consumer asks for bytes.
845    ///
846    /// The fetcher samples the body only while a read is outstanding. A gap
847    /// between reads that is longer than a second counts as one second. The
848    /// bytes that arrived in the gap count at the next read.
849    ///
850    /// A transfer slower than the rate is a transport failure. A slow head is a
851    /// retryable failure of the attempt. A slow body fails the read with
852    /// [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut).
853    ///
854    /// `None` checks no rate. The default is `None`.
855    pub low_speed: Option<LowSpeed>,
856    /// The longest time that one fetch can take to get a response head.
857    ///
858    /// The limit includes all rounds, all retries, and the delays between them,
859    /// from the admission of the fetch until the response head arrives. Only
860    /// [`progress_timeout`](FetcherOptions::progress_timeout) limits the body
861    /// that follows. `None` sets no limit. The default is 300 s.
862    ///
863    /// This limit is the longest time that a fetch with no response holds an
864    /// admission permit. So a caller sizes it against
865    /// [`max_outstanding`](FetcherOptions::max_outstanding). Without this
866    /// limit, an unresponsive peer can stall a fetch for a product of three
867    /// values. These are the destination count, the retry count, and the two
868    /// deadlines of an attempt.
869    ///
870    /// On expiry, the fetch fails with [`Error::Fetch`] and tries nothing more.
871    /// The attempt that the expiry cancels releases the admission permit. An
872    /// upload has a narrower limit, which [`Fetcher::upload`] states.
873    pub fetch_timeout: Option<Duration>,
874}
875
876impl Default for FetcherOptions {
877    fn default() -> Self {
878        FetcherOptions {
879            mirrors: Vec::new(),
880            headers: Vec::new(),
881            basic_auth: None,
882            bearer_token: None,
883            allow_cleartext_credentials: false,
884            tls: TlsOptions::default(),
885            proxy: Proxy::default(),
886            http2: true,
887            max_retries: 5,
888            max_redirects: 10,
889            max_outstanding: 8,
890            connect_timeout: Duration::from_secs(30),
891            progress_timeout: Duration::from_secs(60),
892            low_speed: None,
893            fetch_timeout: Some(Duration::from_secs(300)),
894        }
895    }
896}
897
898impl std::fmt::Debug for FetcherOptions {
899    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
900        let FetcherOptions {
901            mirrors,
902            headers,
903            basic_auth,
904            bearer_token,
905            allow_cleartext_credentials,
906            tls,
907            proxy,
908            http2,
909            max_retries,
910            max_redirects,
911            max_outstanding,
912            connect_timeout,
913            progress_timeout,
914            low_speed,
915            fetch_timeout,
916        } = self;
917        let headers = RedactedHeaders {
918            names: || headers.iter().map(|(name, _)| name.as_str()),
919        };
920        f.debug_struct("FetcherOptions")
921            .field("mirrors", &RedactedUrls { urls: mirrors })
922            .field("headers", &headers)
923            .field("basic_auth", basic_auth)
924            .field("bearer_token", bearer_token)
925            .field("allow_cleartext_credentials", allow_cleartext_credentials)
926            .field("tls", tls)
927            .field("proxy", proxy)
928            .field("http2", http2)
929            .field("max_retries", max_retries)
930            .field("max_redirects", max_redirects)
931            .field("max_outstanding", max_outstanding)
932            .field("connect_timeout", connect_timeout)
933            .field("progress_timeout", progress_timeout)
934            .field("low_speed", low_speed)
935            .field("fetch_timeout", fetch_timeout)
936            .finish()
937    }
938}
939
940impl FetcherOptions {
941    /// Creates options with one base URL and the default of each other field.
942    pub fn new(url: impl Into<String>) -> FetcherOptions {
943        FetcherOptions {
944            mirrors: vec![url.into()],
945            ..FetcherOptions::default()
946        }
947    }
948}
949
950/// The target of a request.
951///
952/// The [`Debug`] output shows no userinfo of a URL. A query shows as
953/// `?<redacted>`, and a fragment shows as `#<redacted>`, in a URL and in a
954/// path. The query of [`Target::PathQuery`] shows as `<redacted>`.
955#[derive(Clone, Copy, Eq, PartialEq)]
956#[non_exhaustive]
957pub enum Target<'a> {
958    /// A path under the base URL of each mirror.
959    Path(&'a str),
960    /// A path under the base URL of each mirror, with a query string.
961    ///
962    /// The fetcher adds `?` and the query to the URL of each mirror. It sends
963    /// the query as written, so the query carries the escapes that the server
964    /// expects.
965    PathQuery {
966        /// The path, read as [`Target::Path`] is.
967        path: &'a str,
968        /// The query string, without the `?`.
969        query: &'a str,
970    },
971    /// An absolute `http` or `https` URL.
972    ///
973    /// The fetcher does not use the mirror list for it.
974    Url(&'a str),
975}
976
977impl std::fmt::Debug for Target<'_> {
978    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
979        match *self {
980            Target::Path(path) => f
981                .debug_tuple("Path")
982                .field(&RedactedUrl::path(path))
983                .finish(),
984            Target::PathQuery { path, query: _ } => f
985                .debug_struct("PathQuery")
986                .field("path", &RedactedUrl::path(path))
987                .field("query", &"<redacted>")
988                .finish(),
989            Target::Url(url) => f.debug_tuple("Url").field(&RedactedUrl::url(url)).finish(),
990        }
991    }
992}
993
994impl<'a> Target<'a> {
995    /// Returns the text that names the target in each message: the path, the
996    /// path with `?` and its query, or the URL, as the caller wrote it.
997    fn describe(&self) -> Cow<'a, str> {
998        match *self {
999            Target::Path(path) => Cow::Borrowed(path),
1000            Target::PathQuery { path, query } => Cow::Owned(format!("{path}?{query}")),
1001            Target::Url(url) => Cow::Borrowed(url),
1002        }
1003    }
1004}
1005
1006/// The request of one fetch.
1007///
1008/// The [`Debug`] output shows the name of each header, and `<redacted>` in
1009/// place of its value. The target shows as the [`Debug`] output of [`Target`]
1010/// shows it.
1011#[derive(Clone)]
1012pub struct FetchRequest<'a> {
1013    /// The target: a path under the base URL of each mirror, the same with a
1014    /// query string, or an absolute URL.
1015    ///
1016    /// The fetcher adds a path to the base path as written, so the path carries
1017    /// the escapes that the server expects. A path holds no `?` and no `#`,
1018    /// because neither is part of a path. Either one fails the fetch before
1019    /// admission.
1020    ///
1021    /// The fetcher adds `?` and the query of [`Target::PathQuery`] after the
1022    /// path, as written, so the query carries the escapes that the server
1023    /// expects. A query holds no `#`, because a `#` starts a fragment. A `#`
1024    /// fails the fetch before admission.
1025    ///
1026    /// The fetcher sends the query string of a URL as written. A fragment in a
1027    /// URL fails the fetch, because no request sends a fragment. A character
1028    /// that a request target cannot hold fails the fetch when the fetcher
1029    /// assembles the URL.
1030    pub target: Target<'a>,
1031    /// The place of the request in the queue when the fetcher is at its limit.
1032    pub priority: Priority,
1033    /// The validators of a previous fetch.
1034    ///
1035    /// If the server reports that the copy is still current, the fetch gives
1036    /// [`Fetched::NotModified`].
1037    pub validators: Option<&'a Validators>,
1038    /// The largest response body, in bytes, that the fetch accepts.
1039    ///
1040    /// A larger `Content-Length` fails the fetch with [`Error::FetchTooLarge`].
1041    /// If a body grows past the cap while it streams, the read fails with
1042    /// [`io::ErrorKind::FileTooLarge`](std::io::ErrorKind::FileTooLarge). The
1043    /// fetcher compares the cap with the response that answers, and does not
1044    /// measure an intermediate redirect response.
1045    pub max_size: Option<u64>,
1046    /// Headers merged over the headers of the fetcher.
1047    ///
1048    /// An entry replaces a fetcher header of the same name. Names compare as
1049    /// `HeaderName`, so the comparison ignores case. Two entries of one name
1050    /// both go on the wire. An invalid name or value fails the fetch before
1051    /// admission.
1052    ///
1053    /// The fetcher sets `User-Agent` and `Accept-Encoding: identity`, and an
1054    /// entry of one of these names replaces the value. An entry can ask for a
1055    /// content coding. A response that declares a coding fails with
1056    /// [`Error::ContentEncoded`], whichever layer asked for it.
1057    ///
1058    /// A `Host` entry fails the fetch, because the header comes from the URL. A
1059    /// header that the connection layer sets fails at both layers: a framing
1060    /// name or a hop-by-hop name. The connection owns the framing of a request
1061    /// and the state of its connection. A value of the caller puts the wire and
1062    /// the connection pool out of step.
1063    ///
1064    /// # Authorization
1065    ///
1066    /// The request carries the `Authorization` header of the first of these
1067    /// that is set:
1068    ///
1069    /// 1. [`FetchRequest::basic_auth`]
1070    /// 2. an `Authorization` entry in these headers
1071    /// 3. [`FetcherOptions::basic_auth`] or [`FetcherOptions::bearer_token`]
1072    /// 4. an `Authorization` entry in [`FetcherOptions::headers`].
1073    ///
1074    /// Credentials beside an `Authorization` header in one layer give two
1075    /// answers to one question. [`Fetcher::new`] refuses them on the fetcher,
1076    /// and the fetch refuses them on a request.
1077    pub headers: &'a [(String, String)],
1078    /// Credentials that replace the credentials of the fetcher for this
1079    /// request.
1080    ///
1081    /// These set the `Authorization` header, so an `Authorization` entry in
1082    /// [`headers`](FetchRequest::headers) beside them fails the fetch.
1083    ///
1084    /// The fetcher encodes the header value for each request. A caller that
1085    /// sends one credential over many requests can encode the `Authorization`
1086    /// value once and set it in [`headers`](FetchRequest::headers). That entry
1087    /// replaces the credential of the fetcher for the request in the same way.
1088    pub basic_auth: Option<&'a BasicAuth>,
1089    /// The permission for a credential to reach a cleartext origin.
1090    ///
1091    /// If this is `false` and the merged headers carry a credential, the fetch
1092    /// fails if a destination that it can reach is `http`. The merged headers
1093    /// include the credentials of the fetcher. The check of [`Fetcher::new`] on
1094    /// the mirror list applies whatever this value is. The default is `false`.
1095    ///
1096    /// [`FetcherOptions::allow_cleartext_credentials`] lifts this refusal for
1097    /// each request of the fetcher.
1098    ///
1099    /// A redirect hop never carries a credential to a cleartext origin of its
1100    /// own. The fetcher removes the credential for a hop at another origin, and
1101    /// refuses a hop from `https` to `http`. [`Fetcher::fetch`] states the
1102    /// redirect rules.
1103    ///
1104    /// # Cleartext credentials
1105    ///
1106    /// The fetcher withholds a credential from no destination that a route
1107    /// names. So it refuses a credential and a cleartext destination together.
1108    /// The credentials are [`basic_auth`](FetchRequest::basic_auth), and an
1109    /// `Authorization`, `Proxy-Authorization`, or `Cookie` entry in the merged
1110    /// headers. [`FetcherOptions::basic_auth`] and
1111    /// [`FetcherOptions::bearer_token`] are `Authorization` entries in the
1112    /// merged headers.
1113    ///
1114    /// If a fetch carries a credential and a destination that it can reach is
1115    /// `http`, the fetch fails before admission with [`Error::Fetch`]. The
1116    /// message names that origin. The other choice is to withhold the
1117    /// credential from that one destination. That choice turns a configuration
1118    /// mistake into a 401 that names nothing.
1119    pub allow_cleartext_credentials: bool,
1120}
1121
1122impl std::fmt::Debug for FetchRequest<'_> {
1123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1124        let FetchRequest {
1125            target,
1126            priority,
1127            validators,
1128            max_size,
1129            headers,
1130            basic_auth,
1131            allow_cleartext_credentials,
1132        } = self;
1133        let headers = RedactedHeaders {
1134            names: || headers.iter().map(|(name, _)| name.as_str()),
1135        };
1136        f.debug_struct("FetchRequest")
1137            .field("target", target)
1138            .field("priority", priority)
1139            .field("validators", validators)
1140            .field("max_size", max_size)
1141            .field("headers", &headers)
1142            .field("basic_auth", basic_auth)
1143            .field("allow_cleartext_credentials", allow_cleartext_credentials)
1144            .finish()
1145    }
1146}
1147
1148impl<'a> FetchRequest<'a> {
1149    /// Creates a request for `path` under each mirror.
1150    ///
1151    /// The request has normal priority, no validators, and no size cap. It
1152    /// carries the headers and the credentials of the fetcher.
1153    pub fn path(path: &'a str) -> FetchRequest<'a> {
1154        FetchRequest::for_target(Target::Path(path))
1155    }
1156
1157    /// Creates a request for `path` with the query string `query` under each
1158    /// mirror.
1159    ///
1160    /// The query has no leading `?`. The request has normal priority, no
1161    /// validators, and no size cap. It carries the headers and the
1162    /// credentials of the fetcher.
1163    pub fn path_query(path: &'a str, query: &'a str) -> FetchRequest<'a> {
1164        FetchRequest::for_target(Target::PathQuery { path, query })
1165    }
1166
1167    /// Creates a request for the absolute URL `url`.
1168    ///
1169    /// The request has normal priority, no validators, and no size cap. It
1170    /// carries the headers and the credentials of the fetcher.
1171    pub fn url(url: &'a str) -> FetchRequest<'a> {
1172        FetchRequest::for_target(Target::Url(url))
1173    }
1174
1175    /// Creates a request for `target` with the default of each other field.
1176    fn for_target(target: Target<'a>) -> FetchRequest<'a> {
1177        FetchRequest {
1178            target,
1179            priority: Priority::default(),
1180            validators: None,
1181            max_size: None,
1182            headers: &[],
1183            basic_auth: None,
1184            allow_cleartext_credentials: false,
1185        }
1186    }
1187}
1188
1189/// The result of a fetch.
1190#[derive(Debug)]
1191// The body variant is much larger than the other variant. A box adds an
1192// allocation on the path of each object, so the variant stays inline.
1193#[allow(clippy::large_enum_variant)]
1194pub enum Fetched {
1195    /// The body of the object that the server sent.
1196    Body(Body),
1197    /// A 304 answer: the copy of the caller is current.
1198    NotModified,
1199}
1200
1201/// The method of an upload.
1202#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1203pub enum UploadMethod {
1204    /// `POST`, which sends the body.
1205    ///
1206    /// This is the default.
1207    #[default]
1208    Post,
1209    /// `DELETE`, which sends no body.
1210    ///
1211    /// The request takes an empty [`UploadBody::bytes`]. Any other body fails
1212    /// the upload before admission with [`Error::Fetch`].
1213    Delete,
1214}
1215
1216/// The request body of an upload.
1217///
1218/// A body has one of two forms:
1219///
1220/// - [`bytes`](UploadBody::bytes) gives the whole body. The request declares
1221///   its `Content-Length`, and hyper takes the bytes in frames of 64 KiB. A
1222///   followed redirect sends the bytes again.
1223/// - [`channel`](UploadBody::channel) streams the body. The caller writes the
1224///   body into the [`UploadWriter`] while the upload runs. Over HTTP/1.1, the
1225///   body travels chunked.
1226///
1227/// If a channel body is dropped before an upload sends it, or after its upload
1228/// ends, each write of its writer fails with
1229/// [`io::ErrorKind::BrokenPipe`](std::io::ErrorKind::BrokenPipe). If a `POST`
1230/// body is at its end when the fetcher hands over the request, the request
1231/// declares a `Content-Length` of zero.
1232pub struct UploadBody {
1233    form: UploadForm,
1234}
1235
1236/// The two forms of an [`UploadBody`].
1237enum UploadForm {
1238    /// The whole body, which each hop of the upload sends.
1239    Bytes(Bytes),
1240    /// The reading end of a body that an [`UploadWriter`] fills.
1241    Channel(BodyEnd),
1242}
1243
1244impl UploadBody {
1245    /// Creates a body of `bytes`.
1246    ///
1247    /// The request sends the vector in frames cut from it with no copy.
1248    pub fn bytes(bytes: Vec<u8>) -> UploadBody {
1249        UploadBody {
1250            form: UploadForm::Bytes(Bytes::from(bytes)),
1251        }
1252    }
1253
1254    /// Creates a streamed body and the writer that fills it.
1255    pub fn channel() -> (UploadBody, UploadWriter) {
1256        let exchange = Arc::new(Exchange::default());
1257        let body = UploadBody {
1258            form: UploadForm::Channel(BodyEnd {
1259                exchange: exchange.clone(),
1260            }),
1261        };
1262        let writer = UploadWriter {
1263            exchange,
1264            // The first write allocates the frame. So a body that gets no
1265            // write holds no frame of memory.
1266            buffer: Vec::new(),
1267            stall: None,
1268            failed: None,
1269        };
1270        (body, writer)
1271    }
1272}
1273
1274impl From<Vec<u8>> for UploadBody {
1275    fn from(bytes: Vec<u8>) -> UploadBody {
1276        UploadBody::bytes(bytes)
1277    }
1278}
1279
1280impl std::fmt::Debug for UploadBody {
1281    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1282        match &self.form {
1283            UploadForm::Bytes(bytes) => f.debug_tuple("Bytes").field(&bytes.len()).finish(),
1284            UploadForm::Channel(_) => f.write_str("Channel"),
1285        }
1286    }
1287}
1288
1289/// The request of one upload, which sends a body and gets a bounded response.
1290///
1291/// The [`Debug`] output shows the name of each header, and `<redacted>` in
1292/// place of its value. The target shows as the [`Debug`] output of [`Target`]
1293/// shows it.
1294pub struct UploadRequest<'a> {
1295    /// The target, read as [`FetchRequest::target`] is. A
1296    /// [`Target::PathQuery`] goes to the mirrors with its query, as for a
1297    /// fetch.
1298    ///
1299    /// The fetcher tries the mirrors in order until one of them takes the
1300    /// request. It never asks a mirror after that one.
1301    pub target: Target<'a>,
1302    /// The method.
1303    ///
1304    /// The default is `POST`.
1305    pub method: UploadMethod,
1306    /// The body that the request sends.
1307    pub body: UploadBody,
1308    /// The place of the request in the queue when the fetcher is at its limit.
1309    pub priority: Priority,
1310    /// The largest response body, in bytes, for each status.
1311    ///
1312    /// A larger `Content-Length` fails the upload with
1313    /// [`Error::UploadInterrupted`]. If a body grows past the cap while it
1314    /// streams, the read fails with
1315    /// [`io::ErrorKind::FileTooLarge`](std::io::ErrorKind::FileTooLarge). The
1316    /// default is [`UploadRequest::DEFAULT_MAX_RESPONSE`].
1317    pub max_response: u64,
1318    /// Headers merged over the headers of the fetcher.
1319    ///
1320    /// [`FetchRequest::headers`] states the merge. The fetcher sets no
1321    /// `Content-Type`, so a `Content-Type` that the server needs goes here.
1322    pub headers: &'a [(String, String)],
1323    /// Credentials for `Authorization: Basic`, for this request.
1324    ///
1325    /// They replace the credentials of the fetcher.
1326    ///
1327    /// Beside [`bearer_token`](UploadRequest::bearer_token), or beside an
1328    /// `Authorization` entry in [`headers`](UploadRequest::headers), they fail
1329    /// the upload before admission with [`Error::Fetch`].
1330    pub basic_auth: Option<&'a BasicAuth>,
1331    /// A token for `Authorization: Bearer`, for this request.
1332    ///
1333    /// It replaces the credentials of the fetcher.
1334    ///
1335    /// Beside [`basic_auth`](UploadRequest::basic_auth), or beside an
1336    /// `Authorization` entry in [`headers`](UploadRequest::headers), it fails
1337    /// the upload before admission with [`Error::Fetch`].
1338    pub bearer_token: Option<&'a BearerToken>,
1339    /// The permission for a credential to reach a cleartext origin.
1340    ///
1341    /// [`FetchRequest::allow_cleartext_credentials`] states the rule.
1342    pub allow_cleartext_credentials: bool,
1343    /// The longest wait for the response head after hyper takes the end of the
1344    /// body.
1345    ///
1346    /// `None` takes [`progress_timeout`](FetcherOptions::progress_timeout).
1347    pub response_timeout: Option<Duration>,
1348}
1349
1350impl std::fmt::Debug for UploadRequest<'_> {
1351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1352        let UploadRequest {
1353            target,
1354            method,
1355            body,
1356            priority,
1357            max_response,
1358            headers,
1359            basic_auth,
1360            bearer_token,
1361            allow_cleartext_credentials,
1362            response_timeout,
1363        } = self;
1364        let headers = RedactedHeaders {
1365            names: || headers.iter().map(|(name, _)| name.as_str()),
1366        };
1367        f.debug_struct("UploadRequest")
1368            .field("target", target)
1369            .field("method", method)
1370            .field("body", body)
1371            .field("priority", priority)
1372            .field("max_response", max_response)
1373            .field("headers", &headers)
1374            .field("basic_auth", basic_auth)
1375            .field("bearer_token", bearer_token)
1376            .field("allow_cleartext_credentials", allow_cleartext_credentials)
1377            .field("response_timeout", response_timeout)
1378            .finish()
1379    }
1380}
1381
1382impl<'a> UploadRequest<'a> {
1383    /// The default response cap of a request: 2 MiB.
1384    pub const DEFAULT_MAX_RESPONSE: u64 = 2 * 1024 * 1024;
1385
1386    /// Creates a `POST` of `body` to `path` under each mirror.
1387    ///
1388    /// The request has normal priority. It carries the headers and the
1389    /// credentials of the fetcher.
1390    pub fn path(path: &'a str, body: UploadBody) -> UploadRequest<'a> {
1391        UploadRequest::for_target(Target::Path(path), body)
1392    }
1393
1394    /// Creates a `POST` of `body` to the absolute URL `url`.
1395    ///
1396    /// The request has normal priority. It carries the headers and the
1397    /// credentials of the fetcher.
1398    pub fn url(url: &'a str, body: UploadBody) -> UploadRequest<'a> {
1399        UploadRequest::for_target(Target::Url(url), body)
1400    }
1401
1402    /// Creates a request for `target` with the default of each other field.
1403    fn for_target(target: Target<'a>, body: UploadBody) -> UploadRequest<'a> {
1404        UploadRequest {
1405            target,
1406            method: UploadMethod::default(),
1407            body,
1408            priority: Priority::default(),
1409            max_response: UploadRequest::DEFAULT_MAX_RESPONSE,
1410            headers: &[],
1411            basic_auth: None,
1412            bearer_token: None,
1413            allow_cleartext_credentials: false,
1414            response_timeout: None,
1415        }
1416    }
1417}
1418
1419/// The answer to an upload: the status, the headers, and the response body.
1420///
1421/// Each final status arrives here, also an unsuccessful one. The caller
1422/// decides what it means.
1423///
1424/// The [`Debug`] output shows the name of each response header, and
1425/// `<redacted>` in place of its value. A header with several values shows its
1426/// name once for each value. The URL shows with no userinfo. A query shows as
1427/// `?<redacted>`, and a fragment shows as `#<redacted>`.
1428pub struct Uploaded {
1429    status: StatusCode,
1430    headers: hyper::HeaderMap,
1431    url: String,
1432    body: Body,
1433}
1434
1435impl std::fmt::Debug for Uploaded {
1436    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1437        let Uploaded {
1438            status,
1439            headers,
1440            url,
1441            body,
1442        } = self;
1443        let headers = RedactedHeaders {
1444            names: || headers.iter().map(|(name, _)| name.as_str()),
1445        };
1446        f.debug_struct("Uploaded")
1447            .field("status", status)
1448            .field("headers", &headers)
1449            .field("url", &RedactedUrl::url(url))
1450            .field("body", body)
1451            .finish()
1452    }
1453}
1454
1455impl Uploaded {
1456    /// Returns the status of the response.
1457    pub fn status(&self) -> u16 {
1458        self.status.as_u16()
1459    }
1460
1461    /// Returns the headers of the response.
1462    pub fn headers(&self) -> &hyper::HeaderMap {
1463        &self.headers
1464    }
1465
1466    /// Returns the URL that answered.
1467    ///
1468    /// After a redirect, this is the URL of the last hop.
1469    pub fn url(&self) -> &str {
1470        &self.url
1471    }
1472
1473    /// Returns the HTTP version of the response.
1474    pub fn protocol(&self) -> Protocol {
1475        self.body.protocol()
1476    }
1477
1478    /// Returns the response body, capped at
1479    /// [`max_response`](UploadRequest::max_response).
1480    ///
1481    /// The body holds the admission permit until it ends or is dropped.
1482    pub fn into_body(self) -> Body {
1483        self.body
1484    }
1485}
1486
1487/// A parsed base URL.
1488#[derive(Clone, Debug)]
1489struct Mirror {
1490    /// The scheme, the host, and the port of the origin.
1491    origin: Origin,
1492    /// The `host[:port]` of this mirror, which is the `Host` header of an
1493    /// HTTP/1.1 request. It holds the authority as the base URL wrote it,
1494    /// without the default port of the scheme. An IPv6 literal keeps its
1495    /// brackets.
1496    authority: HeaderValue,
1497    /// The `scheme://authority` prefix of each absolute URL for this mirror.
1498    /// A message names the origin of the mirror with this prefix.
1499    prefix: String,
1500    /// The base path, without a trailing slash. It is empty for a mirror at the
1501    /// root.
1502    base: String,
1503}
1504
1505impl Mirror {
1506    /// Returns the destination of a request for `path` and `query` under this
1507    /// mirror. The one string of the destination is the prefix and the base
1508    /// path of the mirror, then the request path, then `?` and the query if
1509    /// there is one.
1510    fn destination(&self, path: &str, query: Option<&str>) -> Destination {
1511        let path = path.trim_start_matches('/');
1512        let url = match query {
1513            None => format!("{}{}/{path}", self.prefix, self.base),
1514            Some(query) => format!("{}{}/{path}?{query}", self.prefix, self.base),
1515        };
1516        Destination {
1517            origin: self.origin.clone(),
1518            authority: self.authority.clone(),
1519            url,
1520            path_at: self.prefix.len(),
1521        }
1522    }
1523}
1524
1525/// The place to which one attempt sends its request.
1526///
1527/// A URL target resolves its one destination once for each fetch, and each
1528/// attempt and each retry round uses it. A path target resolves the
1529/// destination of a mirror at the attempt that uses that mirror.
1530#[derive(Clone, Debug)]
1531struct Destination {
1532    /// The scheme, the host, and the port of the origin. The pool key holds it,
1533    /// together with the client identity that the connection presents.
1534    origin: Origin,
1535    /// The `host[:port]` of the request, which is the `Host` header of an
1536    /// HTTP/1.1 request. It holds the authority as the caller wrote it, without
1537    /// the default port of the scheme. An IPv6 literal keeps its brackets.
1538    authority: HeaderValue,
1539    /// The absolute URL. It holds the two forms that one request needs: the
1540    /// whole string, and the tail from `path_at`.
1541    url: String,
1542    /// The start of the request path in `url`, which is the length of the
1543    /// `scheme://authority` prefix.
1544    path_at: usize,
1545}
1546
1547impl Destination {
1548    /// Returns the absolute URL, which an HTTP/2 request carries and each
1549    /// message names.
1550    fn url(&self) -> &str {
1551        &self.url
1552    }
1553
1554    /// Returns the origin-form request target, which an HTTP/1.1 request to an
1555    /// origin server carries. It is the path, and the query string of a URL
1556    /// target or of a path target with a query.
1557    fn target(&self) -> &str {
1558        &self.url[self.path_at..]
1559    }
1560
1561    /// Returns the `scheme://authority` of this destination. A message about
1562    /// the origin names it with this string.
1563    fn origin_url(&self) -> &str {
1564        &self.url[..self.path_at]
1565    }
1566}
1567
1568/// The destinations of a fetch, in the order in which it asks them.
1569///
1570/// A path target goes to each mirror. So a round walks the mirror list, and
1571/// builds the destination of a mirror when it asks that mirror. If the first
1572/// mirror answers, the fetch builds one destination, whatever the length of the
1573/// list. A URL target names one destination, which the fetch parses once.
1574#[derive(Debug)]
1575enum Route<'a> {
1576    /// Each mirror in order, for this request path and query string.
1577    Mirrors {
1578        path: &'a str,
1579        query: Option<&'a str>,
1580    },
1581    /// The one destination that a URL target names.
1582    One(Destination),
1583}
1584
1585/// A connection endpoint.
1586#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1587struct Origin {
1588    tls: bool,
1589    /// The host that the connect resolves, and the source of the TLS server
1590    /// name. So an IPv6 literal has no brackets here. An ASCII host is in lower
1591    /// case, so one origin written in two cases is one pool key and one
1592    /// connection.
1593    host: String,
1594    port: u16,
1595}
1596
1597/// The key of the connection pool.
1598///
1599/// The key holds an endpoint, the client configuration that opened the
1600/// connection, and the proxy flag. A connection presents the client
1601/// certificate for each request that it carries. So the pool never gives a
1602/// connection with the certificate to a hop that must not present it. It never
1603/// gives a connection without the certificate to the origin that the route
1604/// named.
1605///
1606/// The identity flag is in this key, and not in [`Origin`]. [`Origin`] states
1607/// the identity of a network endpoint, and the cleartext and trust-anchor
1608/// checks read it.
1609#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1610struct PoolKey {
1611    origin: Origin,
1612    /// `true` if the connection presents the configured client certificate.
1613    identity: bool,
1614    /// `true` if the connection goes to a proxy and carries absolute-form
1615    /// requests.
1616    ///
1617    /// The pool keeps such a connection under the proxy endpoint. A cleartext
1618    /// origin of the same host and port has the same endpoint, and the two
1619    /// carry different request forms. This flag keeps the pool from giving one
1620    /// to a request of the other.
1621    proxied: bool,
1622}
1623
1624/// One proxy that the fetcher connects through, resolved from a proxy URL.
1625#[derive(Debug)]
1626struct ProxyEndpoint {
1627    /// The endpoint of the connection. The fetcher reaches a proxy over
1628    /// cleartext, so this origin is never TLS.
1629    endpoint: Origin,
1630    /// The `Proxy-Authorization` value from the userinfo of the proxy URL, if
1631    /// the URL holds userinfo.
1632    credential: Option<HeaderValue>,
1633    /// The name of this proxy in a message, which is its URL without the
1634    /// userinfo.
1635    named: String,
1636}
1637
1638/// One `no_proxy` entry: a host text, and the port of the entry if it names
1639/// one.
1640#[derive(Debug)]
1641struct Exemption {
1642    /// The host that the entry names, in ASCII lower case, without one leading
1643    /// `.`. It is never empty: an entry that names no host exempts nothing and
1644    /// gets no place in a list.
1645    host: String,
1646    /// The port that the entry matches, if it names a port that the fetcher
1647    /// can read.
1648    port: Option<u16>,
1649}
1650
1651impl Exemption {
1652    /// Returns `true` if this entry exempts `origin`.
1653    ///
1654    /// The comparison is byte by byte, with ASCII case ignored. So a host that
1655    /// is not ASCII needs no slice at a character boundary, which can panic.
1656    fn matches(&self, origin: &Origin) -> bool {
1657        if self.port.is_some_and(|port| port != origin.port) {
1658            return false;
1659        }
1660        let host = origin.host.as_bytes();
1661        let entry = self.host.as_bytes();
1662        if host.eq_ignore_ascii_case(entry) {
1663            return true;
1664        }
1665        // The `.` before the entry states that the host is a name under the
1666        // entry. `notexample.com` is no part of `example.com`.
1667        host.len() > entry.len()
1668            && host[host.len() - entry.len() - 1] == b'.'
1669            && host[host.len() - entry.len()..].eq_ignore_ascii_case(entry)
1670    }
1671}
1672
1673/// The proxy of each scheme, and the exemptions from both.
1674#[derive(Debug, Default)]
1675struct Proxies {
1676    /// The proxy of a cleartext origin.
1677    http: Option<Arc<ProxyEndpoint>>,
1678    /// The proxy of a TLS origin. If one proxy URL serves both schemes, this
1679    /// field and `http` hold one endpoint.
1680    https: Option<Arc<ProxyEndpoint>>,
1681    /// `true` if `no_proxy` lists `*`, which exempts all hosts.
1682    exempt_all: bool,
1683    /// The hosts that `no_proxy` lists.
1684    exempt: Vec<Exemption>,
1685}
1686
1687impl Proxies {
1688    /// Returns the way to reach a hop at `origin`. This reads the resolved
1689    /// state and allocates nothing, so the decision costs a fetch one walk of
1690    /// the exemption list.
1691    fn via(&self, origin: &Origin) -> Via<'_> {
1692        let proxy = if origin.tls { &self.https } else { &self.http };
1693        let Some(proxy) = proxy.as_deref() else {
1694            return Via::Direct;
1695        };
1696        if self.exempt_all || self.exempt.iter().any(|entry| entry.matches(origin)) {
1697            return Via::Direct;
1698        }
1699        if origin.tls {
1700            Via::Tunnel(proxy)
1701        } else {
1702            Via::Absolute(proxy)
1703        }
1704    }
1705}
1706
1707/// The way that one hop reaches its origin.
1708#[derive(Clone, Copy, Debug)]
1709enum Via<'a> {
1710    /// A direct connection to the origin.
1711    Direct,
1712    /// A connection to the proxy that carries absolute-form requests. A
1713    /// cleartext origin behind a proxy uses this way.
1714    Absolute(&'a ProxyEndpoint),
1715    /// A `CONNECT` tunnel through the proxy. A TLS origin behind a proxy uses
1716    /// this way.
1717    Tunnel(&'a ProxyEndpoint),
1718}
1719
1720/// The body of a request: no body for a fetch and for a `CONNECT`, or the
1721/// reading end of an upload body. One type serves both, so a fetch and an
1722/// upload share a pooled connection.
1723enum RequestBody {
1724    /// No body: a fetch, a `CONNECT`.
1725    Empty,
1726    /// The body of an upload.
1727    Upload(BodyEnd),
1728}
1729
1730impl hyper::body::Body for RequestBody {
1731    type Data = Bytes;
1732    type Error = std::io::Error;
1733
1734    fn poll_frame(
1735        self: Pin<&mut Self>,
1736        cx: &mut Context<'_>,
1737    ) -> Poll<Option<std::result::Result<Frame<Bytes>, Self::Error>>> {
1738        match self.get_mut() {
1739            RequestBody::Empty => Poll::Ready(None),
1740            RequestBody::Upload(end) => end.poll_frame(cx),
1741        }
1742    }
1743
1744    fn is_end_stream(&self) -> bool {
1745        match self {
1746            RequestBody::Empty => true,
1747            RequestBody::Upload(end) => end.is_end_stream(),
1748        }
1749    }
1750
1751    fn size_hint(&self) -> SizeHint {
1752        match self {
1753            RequestBody::Empty => SizeHint::with_exact(0),
1754            RequestBody::Upload(end) => match end.exchange.exact {
1755                Some(length) => SizeHint::with_exact(length),
1756                None => SizeHint::default(),
1757            },
1758        }
1759    }
1760}
1761
1762/// The state that one upload body shares between its writer, the reading end
1763/// that hyper polls, and the upload that waits for the response.
1764#[derive(Default)]
1765struct Exchange {
1766    slot: Mutex<Slot>,
1767    /// The length of a body given whole, which the request declares. This
1768    /// field is here, and not in the reading end, so the body of a fetch stays
1769    /// one pointer wide.
1770    exact: Option<u64>,
1771}
1772
1773/// The one slot through which an upload body passes its frames, and the
1774/// progress of each party.
1775#[derive(Default)]
1776struct Slot {
1777    /// A frame that the writer handed over and hyper did not take yet. For a
1778    /// body given whole, this is the remaining part of the body, which hyper
1779    /// takes in frames of [`UPLOAD_FRAME`].
1780    frame: Option<Bytes>,
1781    /// `true` if the writer closed the body, so no frame follows `frame`.
1782    closed: bool,
1783    /// The reason for the failure of the body. The writer was dropped before
1784    /// it closed the body, a frame waited past the stall window, or the
1785    /// response ended before the body.
1786    aborted: Option<String>,
1787    /// `true` if the reading end is dropped, which ends the upload.
1788    gone: bool,
1789    /// `true` if the reading end gave hyper the end of the body.
1790    ended: bool,
1791    /// `true` if hyper polled the body for a frame.
1792    polled: bool,
1793    /// `true` if the body was at its end at the hand-over of the request, so
1794    /// the request declares a length of zero.
1795    empty: bool,
1796    /// The stall window, which runs from the hand-over of the request.
1797    stall: Option<Stall>,
1798    /// The writer, which waits for the slot to empty or for the end.
1799    writer: Option<Waker>,
1800    /// hyper, which waits for a frame.
1801    reader: Option<Waker>,
1802    /// The upload, which waits for the end of the body or for its failure.
1803    upload: Option<Waker>,
1804}
1805
1806/// The stall window of an upload body: the longest time that a frame can wait
1807/// in the slot for hyper to take it.
1808#[derive(Clone, Copy)]
1809struct Stall {
1810    window: Duration,
1811    /// The start of the wait of the frame in the slot. This is the latest of
1812    /// three instants: the frame got its place, hyper took the frame before it
1813    /// from a body given whole, or the window started.
1814    since: Instant,
1815}
1816
1817impl Slot {
1818    /// Records that the body is at its end, and gives back the wakers of the
1819    /// two parties that wait for it.
1820    fn end(&mut self) -> [Option<Waker>; 2] {
1821        self.ended = true;
1822        [self.writer.take(), self.upload.take()]
1823    }
1824
1825    /// Fails the body for `reason`, and gives back the wakers of the parties
1826    /// that read the failure. If the body failed before, the first reason
1827    /// stays.
1828    fn abort(&mut self, reason: impl FnOnce() -> String) -> [Option<Waker>; 3] {
1829        self.aborted.get_or_insert_with(reason);
1830        [self.reader.take(), self.upload.take(), self.writer.take()]
1831    }
1832
1833    /// Returns `true` if the body is at its end: closed, with no frame left to
1834    /// take and no failure.
1835    fn at_end(&self) -> bool {
1836        self.closed && self.frame.is_none() && self.aborted.is_none()
1837    }
1838
1839    /// Returns the instant at which the frame in the slot waited the whole
1840    /// stall window. It is `None` if no frame waits, no window runs, or the
1841    /// body failed.
1842    fn stall_end(&self) -> Option<Instant> {
1843        let stall = self.stall?;
1844        if self.frame.is_none() || self.aborted.is_some() {
1845            return None;
1846        }
1847        stall.since.checked_add(stall.window)
1848    }
1849
1850    /// Starts the wait of the frame in the slot again, from now.
1851    fn restart_stall(&mut self) {
1852        if let Some(stall) = &mut self.stall {
1853            stall.since = Instant::now();
1854        }
1855    }
1856}
1857
1858/// The state of the body that the upload sees while it waits for the response.
1859enum Watch {
1860    /// The body still streams. A body given whole has no writer, so the upload
1861    /// runs its stall window, which ends at the given instant.
1862    Streaming(Option<Instant>),
1863    /// hyper took the end of the body.
1864    Ended,
1865    /// The body failed, for the reason given.
1866    Aborted(String),
1867}
1868
1869impl Exchange {
1870    /// Creates the exchange of a body given whole. The bytes are the frame that
1871    /// hyper takes in parts, and the body is closed. An empty body holds no
1872    /// frame, so it is at its end before hyper polls it.
1873    fn whole(bytes: &Bytes) -> Exchange {
1874        Exchange {
1875            slot: Mutex::new(Slot {
1876                frame: (!bytes.is_empty()).then(|| bytes.clone()),
1877                closed: true,
1878                ..Slot::default()
1879            }),
1880            exact: Some(bytes.len() as u64),
1881        }
1882    }
1883
1884    fn lock(&self) -> MutexGuard<'_, Slot> {
1885        self.slot.lock().expect("upload body mutex")
1886    }
1887
1888    /// Returns the reason for the failure of the body, if the body failed.
1889    fn aborted(&self) -> Option<String> {
1890        self.lock().aborted.clone()
1891    }
1892
1893    /// Hands the body to hyper. This starts the stall window of `stall` from
1894    /// now, and returns `true` if the body is at its end, which the request then
1895    /// declares. The function does not hand over a failed body, and returns
1896    /// the reason for the failure as the error.
1897    fn hand_over(&self, stall: Duration) -> std::result::Result<bool, String> {
1898        let mut slot = self.lock();
1899        if let Some(reason) = &slot.aborted {
1900            return Err(reason.clone());
1901        }
1902        slot.stall = Some(Stall {
1903            window: stall,
1904            since: Instant::now(),
1905        });
1906        slot.empty = slot.at_end();
1907        let empty = slot.empty;
1908        let writer = slot.writer.take();
1909        drop(slot);
1910        wake(writer);
1911        Ok(empty)
1912    }
1913
1914    /// Returns `true` if hyper took the end of the body, with no failure.
1915    fn has_ended(&self) -> bool {
1916        let slot = self.lock();
1917        slot.ended && slot.aborted.is_none()
1918    }
1919
1920    /// Takes the body back from hyper, which gave the request back unwritten.
1921    /// The stall window stops until the next hand-over.
1922    fn withdraw(&self) {
1923        let mut slot = self.lock();
1924        slot.stall = None;
1925        slot.empty = false;
1926    }
1927
1928    /// Fails the body if the frame in the slot waited the whole stall window,
1929    /// and returns the reason. If the frame still has time, or no frame waits,
1930    /// the error holds the instant at which the wait ends.
1931    fn check_stall(&self) -> std::result::Result<String, Option<Instant>> {
1932        let mut slot = self.lock();
1933        let end = slot.stall_end();
1934        let (Some(end), Some(stall)) = (end, slot.stall) else {
1935            return Err(None);
1936        };
1937        if Instant::now() < end {
1938            return Err(Some(end));
1939        }
1940        let message = format!("the upload body was not taken for {:?}", stall.window);
1941        let wakers = slot.abort(|| message.clone());
1942        drop(slot);
1943        wakers.into_iter().for_each(wake);
1944        Ok(message)
1945    }
1946
1947    /// Fails a body that did not end, because its response ended or was
1948    /// dropped. hyper stops the body and closes the connection, and the writer
1949    /// gets a broken pipe.
1950    fn cut(&self) {
1951        let mut slot = self.lock();
1952        if slot.ended {
1953            return;
1954        }
1955        let wakers = slot.abort(|| "the response to the upload ended before its body".into());
1956        drop(slot);
1957        wakers.into_iter().for_each(wake);
1958    }
1959
1960    /// Returns the state of the body, and registers the upload for a wake when
1961    /// the state changes.
1962    fn watch(&self, cx: &mut Context<'_>) -> Watch {
1963        let mut slot = self.lock();
1964        if let Some(reason) = &slot.aborted {
1965            return Watch::Aborted(reason.clone());
1966        }
1967        if slot.ended {
1968            return Watch::Ended;
1969        }
1970        park(&mut slot.upload, cx);
1971        Watch::Streaming(self.exact.and(slot.stall_end()))
1972    }
1973}
1974
1975/// Keeps the waker of `cx` in `waker`, unless the held waker wakes the same
1976/// task.
1977fn park(waker: &mut Option<Waker>, cx: &Context<'_>) {
1978    if !waker
1979        .as_ref()
1980        .is_some_and(|held| held.will_wake(cx.waker()))
1981    {
1982        *waker = Some(cx.waker().clone());
1983    }
1984}
1985
1986/// Wakes `waker`, if a party left one.
1987fn wake(waker: Option<Waker>) {
1988    if let Some(waker) = waker {
1989        waker.wake();
1990    }
1991}
1992
1993/// Polls a timer toward `end`, and is ready after `end`.
1994///
1995/// The function arms the timer once, for the remaining time. If the start of a
1996/// window moves later, as the stall window does with each frame, `end` moves
1997/// later and the timer stays. If the timer fires early, the function arms it
1998/// again for the remaining time.
1999fn poll_until(timer: &mut Option<rt::Deadline>, cx: &mut Context<'_>, end: Instant) -> Poll<()> {
2000    loop {
2001        let left = end.saturating_duration_since(Instant::now());
2002        if left.is_zero() {
2003            *timer = None;
2004            return Poll::Ready(());
2005        }
2006        let deadline = timer.get_or_insert_with(|| rt::Deadline::new(left));
2007        if deadline.poll_expired(cx).is_pending() {
2008            return Poll::Pending;
2009        }
2010        *timer = None;
2011    }
2012}
2013
2014/// The reading end of an upload body, which hyper polls for frames.
2015///
2016/// The reading end takes a frame out of the slot as it is. So the bytes of a
2017/// frame get at most one copy, from the buffer of the caller into the buffer of
2018/// the writer. A body given whole goes in frames of [`UPLOAD_FRAME`] cut from
2019/// its bytes, with no copy. A drop of the end wakes the writer, and each later
2020/// write fails.
2021struct BodyEnd {
2022    exchange: Arc<Exchange>,
2023}
2024
2025impl BodyEnd {
2026    /// Creates the reading end of a body given whole.
2027    fn whole(bytes: &Bytes) -> BodyEnd {
2028        BodyEnd {
2029            exchange: Arc::new(Exchange::whole(bytes)),
2030        }
2031    }
2032
2033    /// Polls for the next frame. A failed body fails the poll. So hyper ends
2034    /// the request unfinished, and does not send a truncated body as a whole
2035    /// body.
2036    fn poll_frame(&mut self, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> {
2037        let mut slot = self.exchange.lock();
2038        slot.polled = true;
2039        if let Some(reason) = &slot.aborted {
2040            return Poll::Ready(Some(Err(std::io::Error::other(reason.clone()))));
2041        }
2042        // hyper takes a body given whole in frames. So the end follows the last
2043        // frame, and the stall window runs over each frame.
2044        if let Some(held) = &mut slot.frame
2045            && held.len() > UPLOAD_FRAME
2046        {
2047            let frame = held.split_to(UPLOAD_FRAME);
2048            slot.restart_stall();
2049            return Poll::Ready(Some(Ok(Frame::data(frame))));
2050        }
2051        if let Some(frame) = slot.frame.take() {
2052            // The last frame of a closed body is also its end. hyper reads the
2053            // end from `is_end_stream`, and does not poll for it.
2054            let wakers = if slot.closed {
2055                slot.end()
2056            } else {
2057                [slot.writer.take(), None]
2058            };
2059            drop(slot);
2060            wakers.into_iter().for_each(wake);
2061            return Poll::Ready(Some(Ok(Frame::data(frame))));
2062        }
2063        if slot.closed {
2064            let wakers = slot.end();
2065            drop(slot);
2066            wakers.into_iter().for_each(wake);
2067            return Poll::Ready(None);
2068        }
2069        park(&mut slot.reader, cx);
2070        Poll::Pending
2071    }
2072
2073    /// Returns `true` if the body has no more frames. hyper asks before it
2074    /// polls, and never polls a body at its end. So this answer records the
2075    /// end, as a poll that finds the end does.
2076    ///
2077    /// hyper frames the request from the first answer. Over HTTP/1.1, a
2078    /// request at its end at that time carries no length of its own. So before
2079    /// the first poll, a body is at its end only if the request declared a
2080    /// length of zero at the hand-over. If a body reached its end after the
2081    /// hand-over, hyper frames it as a stream, and the stream ends empty.
2082    fn is_end_stream(&self) -> bool {
2083        let mut slot = self.exchange.lock();
2084        if slot.ended {
2085            return true;
2086        }
2087        if !slot.at_end() || !(slot.polled || slot.empty) {
2088            return false;
2089        }
2090        let wakers = slot.end();
2091        drop(slot);
2092        wakers.into_iter().for_each(wake);
2093        true
2094    }
2095}
2096
2097impl Drop for BodyEnd {
2098    fn drop(&mut self) {
2099        let mut slot = self.exchange.lock();
2100        slot.gone = true;
2101        let writer = slot.writer.take();
2102        drop(slot);
2103        wake(writer);
2104    }
2105}
2106
2107/// The request body of an upload, which its response holds. If the response
2108/// ends or is dropped before the request body ends, the request body fails. So
2109/// hyper stops the body and closes the connection.
2110struct RequestEnd {
2111    exchange: Arc<Exchange>,
2112}
2113
2114impl Drop for RequestEnd {
2115    fn drop(&mut self) {
2116        self.exchange.cut();
2117    }
2118}
2119
2120type H1Sender = hyper::client::conn::http1::SendRequest<RequestBody>;
2121type H2Sender = hyper::client::conn::http2::SendRequest<RequestBody>;
2122
2123/// A connection ready to carry one request.
2124enum Sender {
2125    /// An HTTP/1.1 connection, which carries one request at a time. It goes
2126    /// back to the pool when its response body ends.
2127    H1(H1Sender),
2128    /// A handle on a pooled HTTP/2 connection, which multiplexes requests.
2129    H2(H2Sender),
2130}
2131
2132/// The connections pooled under one [`PoolKey`].
2133#[derive(Default)]
2134struct PoolEntry {
2135    /// The HTTP/2 connection of the origin, if one is open.
2136    h2: Option<H2Sender>,
2137    /// The idle HTTP/1.1 connections. The connection that became idle last is
2138    /// at the end.
2139    h1: Vec<IdleH1>,
2140}
2141
2142/// An idle HTTP/1.1 connection in the pool, and the instant at which it became
2143/// idle.
2144struct IdleH1 {
2145    sender: H1Sender,
2146    since: Instant,
2147}
2148
2149/// The shared state of a fetcher. A [`Fetcher`] is a handle on this state.
2150struct Inner {
2151    mirrors: Vec<Mirror>,
2152    headers: Vec<(HeaderName, HeaderValue)>,
2153    tls: ClientConfigs,
2154    /// `true` if a handshake has the anchors to verify the peer.
2155    ///
2156    /// A store with no anchor gets here only for a fetcher with all mirrors in
2157    /// cleartext, which opens no handshake that reads the store. The fetcher
2158    /// then refuses a TLS destination. A bypass variant of [`TrustRoots`] reads
2159    /// no store and sets `true`, because its handshake reads no anchor and
2160    /// completes.
2161    has_trust_anchors: bool,
2162    /// `true` if a client certificate is configured, so the two client
2163    /// configurations differ. If none is configured, each connection opens
2164    /// over one configuration, and the pool holds one entry for each origin.
2165    client_identity: bool,
2166    /// The proxy of each scheme, resolved at construction.
2167    proxies: Proxies,
2168    /// `true` if a credential can reach a cleartext destination. A fetch and
2169    /// an upload then skip the cleartext check.
2170    allow_cleartext_credentials: bool,
2171    max_retries: u32,
2172    max_redirects: u32,
2173    connect_timeout: Duration,
2174    progress_timeout: Duration,
2175    low_speed: Option<LowSpeed>,
2176    fetch_timeout: Option<Duration>,
2177    /// The number of requests that the gate admits at one time, at least 1.
2178    max_outstanding: usize,
2179    gate: Arc<Gate>,
2180    h2_connection_window: u32,
2181    pool: Mutex<HashMap<PoolKey, PoolEntry>>,
2182}
2183
2184/// Returns the HTTP/2 flow-control window of the connection for a fetcher that
2185/// admits `max_outstanding` requests: one stream window for each request.
2186///
2187/// A receiver credits a window back when the caller reads the data. So a
2188/// parked stream, whose body the caller received and did not read yet, holds
2189/// its own credit. The connection window is the sum of the stream windows, so
2190/// that credit belongs to the parked stream alone. Each other open stream
2191/// still has a full window.
2192///
2193/// For example, the HTTP pull of `ostrya` parks content bodies while they wait
2194/// for a write permit. The metadata object that its scan waits for uses the
2195/// same connection.
2196///
2197/// The cost is the received and unread data that one connection can hold,
2198/// which is this window. At the default limit of 8, it is 16 MiB.
2199fn h2_connection_window(max_outstanding: usize) -> u32 {
2200    u32::try_from(max_outstanding)
2201        .unwrap_or(u32::MAX)
2202        .saturating_mul(H2_STREAM_WINDOW)
2203        .min(H2_MAX_WINDOW)
2204}
2205
2206/// A failed attempt, and the retry class of the failure.
2207enum Failure {
2208    /// A transport failure, or a status that a later attempt can avoid.
2209    Retry(Error),
2210    /// A definitive answer, which a retry gets again.
2211    Fatal(Error),
2212}
2213
2214impl Failure {
2215    /// Returns the error of the failure, of either kind.
2216    fn into_error(self) -> Error {
2217        match self {
2218            Failure::Retry(e) | Failure::Fatal(e) => e,
2219        }
2220    }
2221}
2222
2223/// A failed upload attempt, and the send state of the request.
2224enum UploadFailure {
2225    /// No part of the request reached hyper, so the round continues as for a
2226    /// fetch.
2227    Unsent(Failure),
2228    /// hyper took the request, so the upload ends with
2229    /// [`Error::UploadInterrupted`] of this URL and message. A sent request has
2230    /// no other error, and [`Error::is_unsent`] reads this fact.
2231    Sent { url: String, message: String },
2232}
2233
2234/// The parts that each attempt of one upload sends, set before admission.
2235struct UploadPlan<'a> {
2236    method: Method,
2237    headers: &'a [(HeaderName, HeaderValue)],
2238    /// The bytes of a body given whole, which a followed redirect sends again.
2239    /// A streamed body has none, so the upload follows no redirect of it.
2240    bytes: Option<Bytes>,
2241    max_response: u64,
2242    response_timeout: Duration,
2243}
2244
2245/// The result of a request after hyper took it.
2246enum Answer<T> {
2247    /// The send resolved, with the response head or the error of hyper.
2248    Sent(T),
2249    /// The writer failed the body before the response head arrived.
2250    Aborted(String),
2251    /// The body ended, and no response head followed within the window.
2252    Silent(Duration),
2253}
2254
2255/// The response of one upload hop, its protocol, and the body that the request
2256/// sent. It also holds the HTTP/1.1 connection, which goes back to the pool
2257/// when the response body ends.
2258type UploadResponse = (Response<Incoming>, Protocol, RequestEnd, Option<H1Sender>);
2259
2260/// An async HTTP client for one remote.
2261///
2262/// A fetcher holds the mirrors, the headers, the credentials, and the TLS
2263/// configuration of one remote. It serves a [`Target::Url`] from the origin of
2264/// that URL. A clone of a `Fetcher` is another handle on the same connection
2265/// pool and the same admission limit. The clone has the counters of received
2266/// body bytes of the handle. [`counted`](Fetcher::counted) gives a handle with
2267/// more counters.
2268///
2269/// # Connections
2270///
2271/// The TLS handshake selects the protocol: ALPN offers `h2` and `http/1.1`,
2272/// and the fetcher uses the choice of the server. Over cleartext, the fetcher
2273/// uses HTTP/1.1. The pool keeps one HTTP/2 connection for each origin, which
2274/// carries concurrent requests. The pool also keeps HTTP/1.1 connections, and
2275/// the fetcher uses one again after the previous body is read to the end.
2276///
2277/// The pool key holds three terms:
2278///
2279/// - the endpoint of the connection
2280/// - `true` if the connection presents the configured client certificate
2281/// - `true` if the connection goes to a proxy and carries absolute-form
2282///   requests.
2283///
2284/// The endpoint is the origin for a direct connection and for a tunnel,
2285/// because the TLS of a tunnel reaches the origin. For a proxied cleartext
2286/// connection, the endpoint is the proxy. So a URL target shares a connection
2287/// with a mirror at the same origin. One proxy connection carries requests for
2288/// all cleartext origins.
2289///
2290/// An unsuccessful status, or a `Content-Length` over the cap of the request,
2291/// ends an attempt with a response body in flight. If the declared length is
2292/// 64 KiB or less, the fetcher reads the body to the end. The HTTP/1.1
2293/// connection then goes back to the pool. If the declared length is larger, or
2294/// if there is none, the fetcher closes the connection.
2295///
2296/// A 404 is the usual answer for an object that the remote does not hold. So
2297/// this rule saves a connection setup for each absent object.
2298///
2299/// All such reads of one attempt share one
2300/// [`progress_timeout`](FetcherOptions::progress_timeout)
2301/// window, whatever the number of hops. A peer can declare a short body on
2302/// each hop and send fewer bytes. Such a peer uses the window once, and the
2303/// later reads close their connections and do not wait.
2304#[derive(Clone)]
2305pub struct Fetcher {
2306    inner: Arc<Inner>,
2307    /// The counters that get the bytes of each response body of a request of
2308    /// this handle.
2309    received: Arc<[Arc<AtomicU64>]>,
2310}
2311
2312impl std::fmt::Debug for Fetcher {
2313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2314        f.debug_struct("Fetcher")
2315            .field("mirrors", &self.inner.mirrors)
2316            .finish_non_exhaustive()
2317    }
2318}
2319
2320impl Fetcher {
2321    /// Creates a fetcher from `options`.
2322    ///
2323    /// If the mirror list is empty, the fetcher serves [`Target::Url`] requests
2324    /// alone.
2325    ///
2326    /// The fetcher has no counters of received body bytes.
2327    /// [`counted`](Fetcher::counted) gives a handle that has counters.
2328    ///
2329    /// The function is async, because [`TrustRoots::System`], the default,
2330    /// reads the host trust store on the blocking pool. An encrypted client key
2331    /// runs a key derivation function, also on the blocking pool. Under
2332    /// [`TrustRoots::Pem`] with no encrypted client key, all work is in memory,
2333    /// and the function never yields.
2334    ///
2335    /// # Trust store
2336    ///
2337    /// The function reads the system store if a fetch can open a handshake.
2338    /// That is the case if one or more mirrors are `https`. It is also the case
2339    /// if the mirror list is empty, because a request can then name an `https`
2340    /// URL. It is also the case if
2341    /// [`max_redirects`](FetcherOptions::max_redirects) is more than zero,
2342    /// because a redirect can go to an `https` URL.
2343    ///
2344    /// A fetcher with all mirrors `http` that follows no redirect reads no
2345    /// store and holds no trust anchor. If a request of that fetcher names an
2346    /// `https` URL of its own, the fetch fails before admission and names the
2347    /// origin. A host without a CA bundle still reaches a cleartext remote.
2348    ///
2349    /// Under either bypass variant of [`TrustRoots`], the function reads no
2350    /// store, so an empty host store fails no fetcher. With no encrypted client
2351    /// key, the function then never yields.
2352    ///
2353    /// # Errors
2354    ///
2355    /// - [`Error::Fetch`] if a [`low_speed`](FetcherOptions::low_speed) rule
2356    ///   holds a zero.
2357    /// - [`Error::Fetch`] if a mirror URL is not a valid absolute URL, has no
2358    ///   usable host, or holds a query string or userinfo.
2359    /// - [`Error::Fetch`] if a mirror URL names a port that is not a number
2360    ///   from 0 to 65535.
2361    /// - [`Error::Unsupported`] if the scheme of a mirror URL is neither `http`
2362    ///   nor `https`.
2363    /// - [`Error::Fetch`] if a header name or value is invalid, or if a header
2364    ///   is `Host` or a header that the connection layer sets.
2365    /// - [`Error::Fetch`] if a mirror is cleartext `http`, the options hold a
2366    ///   credential, and
2367    ///   [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
2368    ///   is `false`. The credentials are
2369    ///   [`basic_auth`](FetcherOptions::basic_auth),
2370    ///   [`bearer_token`](FetcherOptions::bearer_token), and an
2371    ///   `Authorization`, `Proxy-Authorization`, or `Cookie` header.
2372    /// - [`Error::Fetch`] if two of these are set:
2373    ///   [`basic_auth`](FetcherOptions::basic_auth),
2374    ///   [`bearer_token`](FetcherOptions::bearer_token), and an
2375    ///   `Authorization` header.
2376    /// - [`Error::Fetch`] if [`basic_auth`](FetcherOptions::basic_auth) does
2377    ///   not give a valid header value, or if
2378    ///   [`bearer_token`](FetcherOptions::bearer_token) does not have the
2379    ///   token68 syntax.
2380    /// - [`Error::Unsupported`] if a proxy URL is not `http://host[:port]`,
2381    ///   from the options or from the environment.
2382    /// - [`Error::Unsupported`] if a proxy variable has
2383    ///   [white space](Proxy#white-space) around its value.
2384    /// - [`Error::Fetch`] if the TLS material does not parse or the TLS setup
2385    ///   fails: a trust anchor, the client certificate, or the client key.
2386    ///   [`ClientIdentity::key_passphrase`] states the refusals of a client
2387    ///   key.
2388    /// - [`Error::Fetch`] if the system trust store holds no certificate, and
2389    ///   one or more mirrors are `https` or the mirror list is empty.
2390    pub async fn new(options: FetcherOptions) -> Result<Fetcher> {
2391        // A limit of zero or a time of zero measures nothing. No rate is under
2392        // a zero limit, and each transfer fails a zero time immediately.
2393        if let Some(low) = options.low_speed
2394            && (low.limit == 0 || low.time.is_zero())
2395        {
2396            return Err(Error::Fetch(format!(
2397                "low-speed limit {} bytes per second over {:?}: neither may be zero",
2398                low.limit, low.time
2399            )));
2400        }
2401        let mirrors = options
2402            .mirrors
2403            .iter()
2404            .map(|url| parse_mirror(url))
2405            .collect::<Result<Vec<_>>>()?;
2406        // The fetcher sends a credential with each request to each mirror. So
2407        // one cleartext entry in the list puts the credential on the wire in
2408        // the clear, and the fetcher refuses such a configuration, unless the
2409        // caller permits it. A fetch that withholds the credential gets a 401
2410        // that does not state why.
2411        let cleartext = if options.allow_cleartext_credentials {
2412            None
2413        } else {
2414            options
2415                .mirrors
2416                .iter()
2417                .zip(&mirrors)
2418                .find(|(_, mirror)| !mirror.origin.tls)
2419                .map(|(url, _)| url.as_str())
2420        };
2421        let credential = match (&options.basic_auth, &options.bearer_token) {
2422            (Some(_), Some(_)) => return Err(Error::Fetch(BASIC_AND_BEARER.into())),
2423            (Some(_), None) => Some("basic-auth credentials"),
2424            (None, Some(_)) => Some("the bearer token"),
2425            (None, None) => None,
2426        };
2427        if let Some(credential) = credential
2428            && let Some(url) = cleartext
2429        {
2430            return Err(Error::Fetch(format!(
2431                "{credential} would reach the http mirror {url} in the clear: \
2432                 use https mirrors, drop the credentials, or set \
2433                 FetcherOptions::allow_cleartext_credentials"
2434            )));
2435        }
2436        let mut headers = vec![
2437            (
2438                hyper::header::USER_AGENT,
2439                HeaderValue::from_static(USER_AGENT),
2440            ),
2441            (
2442                hyper::header::ACCEPT_ENCODING,
2443                HeaderValue::from_static(IDENTITY),
2444            ),
2445        ];
2446        // The length of the part of the list that the fetcher sets. A
2447        // configured header of one of those names replaces that entry, as a
2448        // request header replaces a fetcher header of the same name. Without
2449        // this rule, both go on the wire and give one question two answers.
2450        // After this part, the list holds configured headers, and two entries
2451        // of one name both go on the wire.
2452        let mut base = headers.len();
2453        for (name, value) in &options.headers {
2454            let name = HeaderName::try_from(name.as_str())
2455                .map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
2456            if name == hyper::header::HOST {
2457                return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
2458            }
2459            if is_connection_header(&name) {
2460                return Err(connection_header_refused(&name));
2461            }
2462            if name == hyper::header::AUTHORIZATION && options.basic_auth.is_some() {
2463                return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
2464            }
2465            if name == hyper::header::AUTHORIZATION && options.bearer_token.is_some() {
2466                return Err(Error::Fetch(AMBIGUOUS_BEARER.into()));
2467            }
2468            if is_credential(&name)
2469                && let Some(url) = cleartext
2470            {
2471                return Err(Error::Fetch(format!(
2472                    "the {name} header carries credentials, which the http mirror {url} \
2473                     would receive in the clear: use https mirrors, drop the header, or set \
2474                     FetcherOptions::allow_cleartext_credentials"
2475                )));
2476            }
2477            let mut value = HeaderValue::try_from(value.as_str())
2478                .map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
2479            value.set_sensitive(is_credential(&name));
2480            if let Some(at) = headers[..base].iter().position(|(held, _)| *held == name) {
2481                headers.remove(at);
2482                base -= 1;
2483            }
2484            headers.push((name, value));
2485        }
2486        if let Some(auth) = &options.basic_auth {
2487            headers.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
2488        }
2489        if let Some(token) = &options.bearer_token {
2490            headers.push((hyper::header::AUTHORIZATION, bearer_value(token)?));
2491        }
2492        let proxies = resolve_proxy(&options.proxy)?;
2493        let max_outstanding = options.max_outstanding.max(1);
2494        // A fetcher with no mirror serves the URLs of its requests, and each
2495        // of them can be `https`. So it must hold trust anchors, and an empty
2496        // system store fails it as for an `https` mirror.
2497        let https = mirrors.is_empty() || mirrors.iter().any(|mirror| mirror.origin.tls);
2498        // A redirect can go from a cleartext mirror to a TLS origin. So the
2499        // fetcher also reads the system store if it follows redirects. If not,
2500        // a fetch reaches a TLS origin only through a URL target of its own. A
2501        // fetcher with no anchor refuses that target before admission.
2502        let reaches_tls = https || options.max_redirects > 0;
2503        let tls = client_config(&options.tls, options.http2, https, reaches_tls).await?;
2504        Ok(Fetcher {
2505            inner: Arc::new(Inner {
2506                mirrors,
2507                headers,
2508                has_trust_anchors: tls.has_trust_anchors,
2509                client_identity: options.tls.client_identity.is_some(),
2510                proxies,
2511                tls,
2512                allow_cleartext_credentials: options.allow_cleartext_credentials,
2513                max_retries: options.max_retries,
2514                max_redirects: options.max_redirects,
2515                connect_timeout: options.connect_timeout,
2516                progress_timeout: options.progress_timeout,
2517                low_speed: options.low_speed,
2518                fetch_timeout: options.fetch_timeout,
2519                max_outstanding,
2520                gate: Arc::new(Gate::new(max_outstanding)),
2521                h2_connection_window: h2_connection_window(max_outstanding),
2522                pool: Mutex::new(HashMap::new()),
2523            }),
2524            received: Arc::new([]),
2525        })
2526    }
2527
2528    /// Returns a handle on this fetcher that adds counters of received body
2529    /// bytes.
2530    ///
2531    /// The new handle shares the configuration, the connection pool, and the
2532    /// admission limit of this handle. It has the counters of this handle and
2533    /// the counters of `received`. A clone of the new handle has the same
2534    /// counters.
2535    ///
2536    /// Each response body of a request of the new handle adds the bytes that it
2537    /// takes from the connection to each of these counters. This includes the
2538    /// bytes of a body before it fails, the body of a [`Refetch`], a body that
2539    /// the caller drops before its end, and the response body of an upload. A
2540    /// request does not count a response that it does not give to the caller:
2541    /// a redirect, an unsuccessful status of a fetch, or a refused response.
2542    ///
2543    /// The counters of this handle do not change. A request of this handle adds
2544    /// to the counters of this handle alone. Each data frame costs one relaxed
2545    /// atomic add for each counter. A counter that the new handle has two times
2546    /// gets the bytes two times.
2547    pub fn counted(&self, received: Vec<Arc<AtomicU64>>) -> Fetcher {
2548        Fetcher {
2549            inner: Arc::clone(&self.inner),
2550            received: self.received.iter().cloned().chain(received).collect(),
2551        }
2552    }
2553
2554    /// Returns the number of requests that the fetcher admits at one time.
2555    ///
2556    /// The number is [`max_outstanding`](FetcherOptions::max_outstanding) of
2557    /// the options, and at least 1. All handles on one fetcher share this
2558    /// limit.
2559    pub fn max_outstanding(&self) -> usize {
2560        self.inner.max_outstanding
2561    }
2562
2563    /// Sends `request` to each destination in turn and returns the response.
2564    ///
2565    /// # Retries
2566    ///
2567    /// A path target goes to each mirror, in the mirror order. The fetch
2568    /// resolves the destination of a mirror at the attempt that uses it. A URL
2569    /// target has the one destination that the URL names.
2570    ///
2571    /// - The fetch tries each destination in order before it retries.
2572    /// - Transport failures and the statuses 408, 429, and 5xx are retryable.
2573    ///   If one or more destinations of a round fail that way, the fetch
2574    ///   repeats the round, up to [`max_retries`](FetcherOptions::max_retries)
2575    ///   times. The delay before a repeat starts at 250ms, doubles each time,
2576    ///   and stops at two seconds. A repeated round asks only the destinations
2577    ///   with a retryable failure.
2578    /// - Each other unsuccessful status is definitive. The fetch does not ask
2579    ///   that destination again, because its answer is the same in each round.
2580    /// - The expiry of [`connect_timeout`](FetcherOptions::connect_timeout),
2581    ///   [`progress_timeout`](FetcherOptions::progress_timeout), or
2582    ///   [`low_speed`](FetcherOptions::low_speed) is a transport failure. The
2583    ///   fetch reports the deadline that expires first.
2584    ///
2585    /// The hop count belongs to one attempt. So a retryable status on a hop
2586    /// makes the whole attempt retryable, and the repeated round starts again
2587    /// from the destination that the route names.
2588    ///
2589    /// The retries end at the response head. So if a body fails in transit,
2590    /// the caller gets a failed read. [`refetching`](Fetcher::refetching)
2591    /// fetches such a body again.
2592    ///
2593    /// # Failure order
2594    ///
2595    /// A fetch ends if it has no more destinations to ask or no more rounds to
2596    /// repeat. In both cases, it reports a definitive answer if it got one, and
2597    /// the first retryable failure if not.
2598    ///
2599    /// A caller can act on a definitive answer, for example a 404 that states
2600    /// that the object is absent. So the fetch reports such an answer from any
2601    /// round, and an earlier retryable failure does not hide it. Of two
2602    /// definitive answers, the fetch reports the answer that it got first. In
2603    /// one round, this is the mirror order.
2604    ///
2605    /// # Redirects
2606    ///
2607    /// A 301, 302, 303, 307, or 308 sends the attempt to the URL of its
2608    /// `Location` header, up to [`max_redirects`](FetcherOptions::max_redirects)
2609    /// times. A fetch is a GET, so none of the five statuses changes the method
2610    /// of the next hop.
2611    ///
2612    /// The fetch resolves `Location` against the URL of the response that
2613    /// carries it. So `Location` can be an absolute URL, a relative URL
2614    /// (`/other/path`, `sibling`), or a scheme-relative URL (`//host/path`). The
2615    /// resolution normalizes the result, as the HTTP specification prescribes
2616    /// for a redirect:
2617    ///
2618    /// - it resolves dot segments
2619    /// - it reads a backslash as a path separator
2620    /// - it removes tabs and newlines
2621    /// - it percent-encodes a character that a path or a query cannot carry
2622    /// - it puts an IPv4 or an IPv6 host in canonical form
2623    /// - it removes the fragment.
2624    ///
2625    /// A [`Target::Url`] goes on the wire as the caller wrote it. So one string
2626    /// as a URL target and as a `Location` can reach the server as two
2627    /// different request targets.
2628    ///
2629    /// The fetch refuses two hops definitively: a scheme other than `http` or
2630    /// `https`, and a hop from `https` to `http`. The [`Error::Fetch`] names the
2631    /// URL that redirected and the URL that it named. On a fetcher with no trust
2632    /// anchors, the fetch also refuses a hop to a TLS origin in the same way.
2633    /// The fetch follows a hop from `http` to `https`.
2634    ///
2635    /// If a response with one of the five statuses has no readable `Location`,
2636    /// the fetch reports the status, whatever the hop count. This applies to a
2637    /// missing header, an empty value, a value that is not text, and a value
2638    /// that the resolution cannot read.
2639    ///
2640    /// `Authorization`, `Proxy-Authorization`, and `Cookie` from either layer
2641    /// go to the origin that the route names. They also go to a hop at that
2642    /// origin: the same scheme, host, and port.
2643    ///
2644    /// The fetch removes them for a hop at another origin. A removed credential
2645    /// stays removed for the rest of the attempt, also on a redirect back to the
2646    /// named origin. At that time, the operator of the other origin has the
2647    /// request.
2648    ///
2649    /// All other headers go to each hop, also the `User-Agent` and the
2650    /// `Accept-Encoding` of the fetcher. The fetcher presents a configured
2651    /// client certificate to the origin that the route names and to no other
2652    /// origin. So the pool keeps the connections with the certificate apart
2653    /// from the connections without it.
2654    ///
2655    /// The fetch discards the body of an intermediate response as it discards
2656    /// the body of an unsuccessful response. So if the declared length is
2657    /// 64 KiB or less, the HTTP/1.1 connection goes back to the pool. A chain
2658    /// on one origin then uses one connection. If the intermediate responses
2659    /// declare more, or declare no length, the chain opens a connection for
2660    /// each hop.
2661    ///
2662    /// The validators go to each hop, because they describe the resource. A 304
2663    /// from any hop is the answer of the fetch. Each message names the URL of
2664    /// the response that answered, which after a redirect is the URL of the
2665    /// last hop.
2666    ///
2667    /// # Content coding
2668    ///
2669    /// A fetch gives the bytes that the remote stores. So each request carries
2670    /// `Accept-Encoding: identity`, and asks for no content coding. Without
2671    /// that header, a server can compress a response and stay within the HTTP
2672    /// specification. The body then holds bytes other than the bytes that the
2673    /// checksum of the object names.
2674    ///
2675    /// A 200 response fails the attempt definitively with
2676    /// [`Error::ContentEncoded`] in two cases: a `Content-Encoding` other than
2677    /// `identity`, or a `Transfer-Encoding` other than `chunked` and
2678    /// `identity`. This applies whichever layer asked for the coding. A caller
2679    /// that wants a coded body decodes it outside the fetcher.
2680    ///
2681    /// `chunked` frames a message, and the connection removes the framing. So a
2682    /// response with `chunked` alone gives the body as the remote wrote it.
2683    ///
2684    /// # Errors
2685    ///
2686    /// If more than one destination fails, the failure order rules state which
2687    /// error the fetch reports.
2688    ///
2689    /// - [`Error::Fetch`] before admission, if a path holds a `?` or a `#`, if
2690    ///   the query of a [`Target::PathQuery`] holds a `#`, or if the fetcher
2691    ///   has no mirror for a path target.
2692    /// - [`Error::Fetch`] before admission, if a URL target is not a valid
2693    ///   absolute URL, or holds a fragment or userinfo.
2694    /// - [`Error::Unsupported`] if the scheme of a URL target is neither `http`
2695    ///   nor `https`.
2696    /// - [`Error::Fetch`] before admission, if a request header is invalid, is
2697    ///   `Host`, or is a header that the connection layer sets.
2698    /// - [`Error::Fetch`] before admission, if an `Authorization` header is
2699    ///   beside [`basic_auth`](FetchRequest::basic_auth).
2700    /// - [`Error::Fetch`] before admission, if a credential can reach a
2701    ///   cleartext destination, and neither
2702    ///   [`allow_cleartext_credentials`](FetchRequest::allow_cleartext_credentials)
2703    ///   nor [`FetcherOptions::allow_cleartext_credentials`] is `true`.
2704    /// - [`Error::Fetch`] before admission, if the route names a TLS
2705    ///   destination and the fetcher holds no trust anchors.
2706    /// - [`Error::Fetch`] if a transport failure ends the rounds: a failed
2707    ///   connect, handshake, or proxy `CONNECT`, or an expired deadline.
2708    /// - [`Error::Fetch`] if the fetch refuses a redirect hop, as the redirect
2709    ///   rules state.
2710    /// - [`Error::Fetch`] if hyper cannot build a request, for example from an
2711    ///   invalid validator value.
2712    /// - [`Error::Fetch`] if [`fetch_timeout`](FetcherOptions::fetch_timeout)
2713    ///   expires.
2714    /// - [`Error::HttpStatus`] if a destination answers with a status other
2715    ///   than 200 and 304. This includes a redirect that the fetch does not
2716    ///   follow: no usable `Location`, or a redirect limit of zero.
2717    /// - [`Error::RedirectLimit`] if an attempt follows
2718    ///   [`max_redirects`](FetcherOptions::max_redirects) redirects, and the
2719    ///   next response names a URL to follow.
2720    /// - [`Error::FetchTooLarge`] if the `Content-Length` of the response is
2721    ///   more than [`max_size`](FetchRequest::max_size).
2722    /// - [`Error::ContentEncoded`] if the response declares a coding, as the
2723    ///   content coding rules state.
2724    pub async fn fetch(&self, request: FetchRequest<'_>) -> Result<Fetched> {
2725        let (fetched, _) = self
2726            .fetch_budgeted(&request, self.inner.max_retries)
2727            .await?;
2728        Ok(fetched)
2729    }
2730
2731    /// Returns a [`Refetch`] of `request`, which fetches a failed body again.
2732    ///
2733    /// [`Refetch`] states the budget that it spends.
2734    pub fn refetching<'r>(&self, request: FetchRequest<'r>) -> Refetch<'_, 'r> {
2735        Refetch {
2736            fetcher: self,
2737            request,
2738            left: self.inner.max_retries,
2739            round: 0,
2740            interrupted: Arc::new(AtomicBool::new(false)),
2741        }
2742    }
2743
2744    /// Fetches `request`, and repeats a round at most `max_retries` times.
2745    /// Returns the response and the number of repeated rounds.
2746    async fn fetch_budgeted(
2747        &self,
2748        request: &FetchRequest<'_>,
2749        max_retries: u32,
2750    ) -> Result<(Fetched, u32)> {
2751        // The target, the headers, their credentials, and the anchors of a TLS
2752        // destination are the same for each destination. So the fetch settles
2753        // all of them before admission, and reports a failure of them one
2754        // time. The fetch takes no permit and opens no socket for it.
2755        let route = self.route(request.target)?;
2756        let headers = merge_headers(
2757            &self.inner.headers,
2758            request.headers,
2759            request.basic_auth,
2760            None,
2761        )?;
2762        if !request.allow_cleartext_credentials && !self.inner.allow_cleartext_credentials {
2763            self.check_cleartext(&route, &headers)?;
2764        }
2765        self.check_trust_anchors(&route)?;
2766        let permit = self.inner.gate.acquire(request.priority).await;
2767        let rounds = self.rounds(request, &route, &headers, permit, max_retries);
2768        let Some(limit) = self.inner.fetch_timeout else {
2769            return rounds.await;
2770        };
2771        // The expiry drops the rounds, the attempt in flight, and the permit.
2772        // So the slot is free before the fetch reports the failure.
2773        match within(limit, rounds).await {
2774            Some(result) => result,
2775            None => Err(Error::Fetch(format!(
2776                "fetch of {} timed out after {limit:?}",
2777                request.target.describe()
2778            ))),
2779        }
2780    }
2781
2782    /// Returns the destinations of a fetch of `target`, in the order in which
2783    /// the fetch asks them.
2784    ///
2785    /// A URL target names its one destination, which this function parses. A
2786    /// path target, with or without a query, goes to the mirrors, so a
2787    /// fetcher with no mirror has no destination for it.
2788    fn route<'a>(&self, target: Target<'a>) -> Result<Route<'a>> {
2789        let (path, query) = match target {
2790            Target::Url(url) => return Ok(Route::One(parse_url(url)?)),
2791            Target::Path(path) => (path, None),
2792            Target::PathQuery { path, query } => (path, Some(query)),
2793        };
2794        check_path(path)?;
2795        if let Some(query) = query {
2796            check_query(path, query)?;
2797        }
2798        if self.inner.mirrors.is_empty() {
2799            return Err(Error::Fetch(format!(
2800                "fetch of the path {} has nowhere to go: no mirror is configured",
2801                target.describe()
2802            )));
2803        }
2804        Ok(Route::Mirrors { path, query })
2805    }
2806
2807    /// Refuses a fetch if its headers carry a credential that a cleartext
2808    /// destination gets in the clear.
2809    ///
2810    /// The fetch withholds a credential from no destination. So one cleartext
2811    /// destination that the fetch can reach is enough for a refusal. The other
2812    /// choice is to send the request without the credential, which gets a 401
2813    /// that names nothing.
2814    fn check_cleartext(
2815        &self,
2816        route: &Route<'_>,
2817        headers: &[(HeaderName, HeaderValue)],
2818    ) -> Result<()> {
2819        if !headers.iter().any(|(name, _)| is_credential(name)) {
2820            return Ok(());
2821        }
2822        let Some(origin) = self.matching_origin(route, |origin| !origin.tls) else {
2823            return Ok(());
2824        };
2825        Err(Error::Fetch(format!(
2826            "the request carries credentials, which the cleartext origin {origin} would receive \
2827             in the clear: fetch over https, drop the credentials, or set \
2828             allow_cleartext_credentials on the request or on the fetcher"
2829        )))
2830    }
2831
2832    /// Refuses a fetch if its route names a TLS destination and the fetcher
2833    /// holds no trust anchors.
2834    ///
2835    /// A handshake verifies the server certificate against an anchor, so a
2836    /// fetcher with no anchor reaches no TLS origin. Only one case gets here: a
2837    /// request with an `https` URL of its own, on a fetcher with all mirrors in
2838    /// cleartext. Each other combination of route and anchors fails
2839    /// [`Fetcher::new`].
2840    ///
2841    /// The handshake reports this case as an unknown issuer. That is a
2842    /// retryable failure, which uses all rounds and all backoffs before it
2843    /// names the cause. So the refusal occurs here, before admission.
2844    ///
2845    /// This function reads the destinations of the route. A redirect hop names
2846    /// an origin that the server chooses. If that origin is TLS, the attempt
2847    /// refuses the hop with the same message, from [`no_trust_anchors`].
2848    fn check_trust_anchors(&self, route: &Route<'_>) -> Result<()> {
2849        if self.inner.has_trust_anchors {
2850            return Ok(());
2851        }
2852        let Some(origin) = self.matching_origin(route, |origin| origin.tls) else {
2853            return Ok(());
2854        };
2855        Err(no_trust_anchors(origin))
2856    }
2857
2858    /// Returns the `scheme://authority` of the first destination on `route`
2859    /// whose origin `wanted` accepts.
2860    fn matching_origin<'a>(
2861        &'a self,
2862        route: &'a Route<'_>,
2863        wanted: fn(&Origin) -> bool,
2864    ) -> Option<&'a str> {
2865        match route {
2866            Route::Mirrors { .. } => self
2867                .inner
2868                .mirrors
2869                .iter()
2870                .find(|mirror| wanted(&mirror.origin))
2871                .map(|mirror| mirror.prefix.as_str()),
2872            Route::One(destination) => {
2873                wanted(&destination.origin).then(|| destination.origin_url())
2874            }
2875        }
2876    }
2877
2878    /// Tries each destination in turn, and repeats the round at most
2879    /// `max_retries` times while a destination has a retryable failure.
2880    ///
2881    /// The permit moves into the body of a successful round. If no round
2882    /// succeeds, the permit drops with this future. A success returns the
2883    /// number of repeated rounds.
2884    async fn rounds(
2885        &self,
2886        request: &FetchRequest<'_>,
2887        route: &Route<'_>,
2888        headers: &[(HeaderName, HeaderValue)],
2889        permit: Permit,
2890        max_retries: u32,
2891    ) -> Result<(Fetched, u32)> {
2892        let destination_count = match route {
2893            Route::Mirrors { .. } => self.inner.mirrors.len(),
2894            Route::One(_) => 1,
2895        };
2896        // A destination with a definitive answer gives the same answer in each
2897        // round, so the fetch asks it once. A repeated round asks only the
2898        // destinations with a retryable failure.
2899        let mut settled = vec![false; destination_count];
2900        // The failure that both end paths report. A caller can act on a
2901        // definitive answer, so it has priority over a retryable failure from
2902        // any round. A destination that fails transiently and then answers 404
2903        // reports the 404. Of two failures of one kind, the fetch keeps the
2904        // first.
2905        let mut reported: Option<Error> = None;
2906        let mut definitive = false;
2907        let mut round = 0;
2908        loop {
2909            let mut retryable = false;
2910            for (position, settled) in settled.iter_mut().enumerate() {
2911                if *settled {
2912                    continue;
2913                }
2914                // The fetch builds the destination of a mirror for the attempt
2915                // that uses it. So if the first mirror answers, the fetch builds
2916                // one destination, whatever the length of the list.
2917                let destination = match route {
2918                    Route::Mirrors { path, query } => {
2919                        Cow::Owned(self.inner.mirrors[position].destination(path, *query))
2920                    }
2921                    Route::One(destination) => Cow::Borrowed(destination),
2922                };
2923                let failure = match self.attempt(&destination, request, headers).await {
2924                    Ok(Attempted::Body(mut body)) => {
2925                        body.permit = Some(permit);
2926                        return Ok((Fetched::Body(body), round));
2927                    }
2928                    Ok(Attempted::NotModified) => return Ok((Fetched::NotModified, round)),
2929                    Err(failure) => failure,
2930                };
2931                match failure {
2932                    Failure::Retry(e) => {
2933                        retryable = true;
2934                        if reported.is_none() {
2935                            reported = Some(e);
2936                        }
2937                    }
2938                    Failure::Fatal(e) => {
2939                        *settled = true;
2940                        if !definitive {
2941                            reported = Some(e);
2942                            definitive = true;
2943                        }
2944                    }
2945                }
2946            }
2947            // If `retryable` is `true`, one or more destinations had a
2948            // retryable failure. If not, each destination gave a definitive
2949            // answer.
2950            if !retryable || round >= max_retries {
2951                return Err(reported.expect("a failed round holds a failure"));
2952            }
2953            round += 1;
2954            rt::Timer::after(backoff(round)).await;
2955        }
2956    }
2957
2958    /// Sends one request to one destination, and follows the redirects of the
2959    /// responses.
2960    ///
2961    /// The hop state of an attempt is three locals:
2962    ///
2963    /// - the destination, borrowed from the route until a redirect names
2964    ///   another destination
2965    /// - the header list, which is the slice of the caller until a hop goes to
2966    ///   another origin and a credential must come out
2967    /// - the count of followed redirects.
2968    ///
2969    /// If the first response answers the request, all three stay as they
2970    /// start. So the attempt builds no URL, copies no header list, and
2971    /// allocates no bookkeeping.
2972    async fn attempt(
2973        &self,
2974        destination: &Destination,
2975        request: &FetchRequest<'_>,
2976        headers: &[(HeaderName, HeaderValue)],
2977    ) -> std::result::Result<Attempted, Failure> {
2978        // The origin that the route names. A credential and the client
2979        // certificate go to this origin alone.
2980        let named = &destination.origin;
2981        let mut hop = Cow::Borrowed(destination);
2982        let mut headers = Cow::Borrowed(headers);
2983        let mut followed = 0u32;
2984        let progress_timeout = self.inner.progress_timeout;
2985        // One progress window applies to all drains of this attempt, whatever
2986        // the number of hops. A peer can answer each hop with a short declared
2987        // body and then stop. Such a peer uses the window on the first drain,
2988        // and each later drain drops its connection and does not wait. An
2989        // attempt that follows no redirect drains once, with the whole window.
2990        let drain_until = Instant::now() + progress_timeout;
2991        // The response head must arrive within the time of the rule, in whole
2992        // seconds, from the start of the attempt, whatever the number of hops.
2993        // A head carries no bytes for the rate. So the rate stays under the
2994        // limit from the start until the head arrives.
2995        let head_until = self
2996            .inner
2997            .low_speed
2998            .and_then(|low| Some((Instant::now().checked_add(low.whole_seconds())?, low)));
2999        loop {
3000            // Each hop makes its own proxy decision. The pool keeps a cleartext
3001            // hop behind a proxy under the proxy endpoint. So one such
3002            // connection carries requests for all cleartext origins.
3003            let via = self.inner.proxies.via(&hop.origin);
3004            let key = PoolKey {
3005                origin: match via {
3006                    Via::Absolute(proxy) => proxy.endpoint.clone(),
3007                    Via::Direct | Via::Tunnel(_) => hop.origin.clone(),
3008                },
3009                identity: self.presents_identity(&hop.origin, named),
3010                proxied: matches!(via, Via::Absolute(_)),
3011            };
3012            let url = hop.url();
3013            let (response, protocol, reuse) = match head_until {
3014                None => self.send(&hop, &key, via, request, &headers).await?,
3015                Some((until, low)) => {
3016                    // The send is in a box under the window. So the attempt
3017                    // holds one inline copy of its state.
3018                    let sent = Box::pin(self.send(&hop, &key, via, request, &headers));
3019                    match within(until.saturating_duration_since(Instant::now()), sent).await {
3020                        Some(result) => result?,
3021                        None => return Err(Failure::Retry(too_slow(url, low))),
3022                    }
3023                }
3024            };
3025            let status = response.status();
3026            if status == StatusCode::NOT_MODIFIED {
3027                // A 304 carries no body, so the connection is ready for the
3028                // next request immediately. The validators describe the
3029                // resource. So a 304 from a hop is the answer for the caller,
3030                // as a 304 from the named destination is.
3031                if let Some(sender) = reuse {
3032                    self.inner.put_h1(&key, sender);
3033                }
3034                return Ok(Attempted::NotModified);
3035            }
3036            // A limit of zero follows nothing. Each redirect status is then a
3037            // definitive answer.
3038            if is_redirect(status) && self.inner.max_redirects > 0 {
3039                let location = response
3040                    .headers()
3041                    .get(hyper::header::LOCATION)
3042                    .and_then(|value| resolve_location(url, value));
3043                let Some(location) = location else {
3044                    // There is no URL to follow. So the attempt reports the
3045                    // status of the hop, whatever the hop count is.
3046                    let failure = classify(status, url);
3047                    self.discard(&key, response, reuse, drain_until).await;
3048                    return Err(failure);
3049                };
3050                // The limit stops the attempt at a URL that it can follow. So
3051                // the attempt reads the limit after the `Location` names a URL.
3052                if followed >= self.inner.max_redirects {
3053                    self.discard(&key, response, reuse, drain_until).await;
3054                    return Err(Failure::Fatal(Error::RedirectLimit {
3055                        url: url.to_string(),
3056                        hops: followed,
3057                    }));
3058                }
3059                let next = redirect_destination(&hop, &location);
3060                // The attempt discards the intermediate body as it discards an
3061                // unsuccessful body. So a short body returns its HTTP/1.1
3062                // connection to the pool, and the next hop at this origin
3063                // uses it.
3064                self.discard(&key, response, reuse, drain_until).await;
3065                let next = next.map_err(Failure::Fatal)?;
3066                // A handshake verifies the server certificate against an
3067                // anchor. So the attempt refuses a hop to a TLS origin if the
3068                // fetcher holds no anchor. Without this check, the handshake
3069                // fails retryably, and uses all rounds and all backoffs on a
3070                // message about the peer.
3071                if next.origin.tls && !self.inner.has_trust_anchors {
3072                    return Err(Failure::Fatal(no_trust_anchors(next.origin_url())));
3073                }
3074                // The operator of the origin that a request reaches gets its
3075                // credentials. So the attempt removes them for a hop at an
3076                // origin other than the named origin. They stay removed for the
3077                // rest of the attempt, also on a redirect back to the named
3078                // origin. At that time, the other operator controls the request.
3079                if next.origin != *named && headers.iter().any(|(name, _)| is_credential(name)) {
3080                    let scoped = headers
3081                        .iter()
3082                        .filter(|(name, _)| !is_credential(name))
3083                        .cloned()
3084                        .collect::<Vec<_>>();
3085                    headers = Cow::Owned(scoped);
3086                }
3087                hop = Cow::Owned(next);
3088                followed += 1;
3089                continue;
3090            }
3091            if status != StatusCode::OK {
3092                let failure = classify(status, url);
3093                self.discard(&key, response, reuse, drain_until).await;
3094                return Err(failure);
3095            }
3096            // A coded body holds bytes other than the bytes that the remote
3097            // stores. So the declared length tells nothing about the object,
3098            // and the attempt refuses the coding before it compares the cap.
3099            // The refusal names the coding, and a checksum mismatch cannot. The
3100            // refusal is definitive, because another attempt against the same
3101            // destination gets the same answer.
3102            if let Some(encoding) = declared_coding(response.headers()) {
3103                let url = url.to_string();
3104                self.discard(&key, response, reuse, drain_until).await;
3105                return Err(Failure::Fatal(Error::ContentEncoded { url, encoding }));
3106            }
3107            let validators = read_validators(response.headers());
3108            let content_length = content_length(response.headers());
3109            // The cap is the limit of the caller on the object. So the attempt
3110            // compares it with the response that carries the object, and with
3111            // no redirect before it.
3112            if let (Some(limit), Some(length)) = (request.max_size, content_length)
3113                && length > limit
3114            {
3115                self.discard(&key, response, reuse, drain_until).await;
3116                return Err(Failure::Fatal(Error::FetchTooLarge { limit }));
3117            }
3118            let protocol = match response.version() {
3119                Version::HTTP_2 => Protocol::Http2,
3120                _ => protocol,
3121            };
3122            return Ok(Attempted::Body(Body {
3123                incoming: response.into_body(),
3124                chunk: Bytes::new(),
3125                received: 0,
3126                max_size: request.max_size,
3127                validators,
3128                content_length,
3129                protocol,
3130                inner: self.inner.clone(),
3131                counters: self.received.clone(),
3132                key,
3133                reuse,
3134                permit: None,
3135                done: false,
3136                failed: None,
3137                deadline: rt::Deadline::new(progress_timeout),
3138                waiting: false,
3139                low_speed: self.inner.low_speed.map(Monitor::new),
3140                interrupted: None,
3141                request_body: None,
3142            }));
3143        }
3144    }
3145
3146    /// Takes or opens a connection for one hop, and sends the request over it.
3147    ///
3148    /// The function returns the response, its protocol, and the HTTP/1.1
3149    /// connection of the response. That connection goes back to the pool after
3150    /// the response is read to its end.
3151    async fn send(
3152        &self,
3153        hop: &Destination,
3154        key: &PoolKey,
3155        via: Via<'_>,
3156        request: &FetchRequest<'_>,
3157        headers: &[(HeaderName, HeaderValue)],
3158    ) -> std::result::Result<(Response<Incoming>, Protocol, Option<H1Sender>), Failure> {
3159        let url = hop.url();
3160        let origin = &key.origin;
3161        let connect_timeout = self.inner.connect_timeout;
3162        let progress_timeout = self.inner.progress_timeout;
3163        let sender = match self.inner.take_conn(key) {
3164            Some(sender) => sender,
3165            None => {
3166                // The open of a connection is the largest state of a fetch: the
3167                // TLS handshake and the state of hyper. It is also the rarest,
3168                // because it occurs only if the pool has no connection for this
3169                // origin. A box keeps that state out of the fetch future, which
3170                // each caller nests in its own future.
3171                //
3172                // A fetch measures 5064 bytes with the box and 36136 bytes
3173                // without it. A caller that wraps several helpers around one
3174                // fetch multiplies the saving.
3175                let opened = within(connect_timeout, Box::pin(self.connect(key, via))).await;
3176                match opened {
3177                    Some(result) => result?,
3178                    None => {
3179                        return Err(Failure::Retry(connect_timed_out(
3180                            origin,
3181                            via,
3182                            connect_timeout,
3183                        )));
3184                    }
3185                }
3186            }
3187        };
3188        match sender {
3189            Sender::H1(mut sender) => {
3190                let http_request = self
3191                    .build_request(hop, request, headers, Protocol::Http11, via)
3192                    .map_err(Failure::Fatal)?;
3193                // The request and the wait for the response head share the
3194                // progress window, because the head is the first bytes of the
3195                // response.
3196                let sent = within(progress_timeout, async {
3197                    sender.ready().await?;
3198                    sender.send_request(http_request).await
3199                })
3200                .await;
3201                let response = match sent {
3202                    Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
3203                    None => return Err(Failure::Retry(stalled(url, progress_timeout))),
3204                };
3205                Ok((response, Protocol::Http11, Some(sender)))
3206            }
3207            Sender::H2(mut sender) => {
3208                let http_request = self
3209                    .build_request(hop, request, headers, Protocol::Http2, via)
3210                    .map_err(Failure::Fatal)?;
3211                let sent = within(progress_timeout, async {
3212                    sender.ready().await?;
3213                    sender.send_request(http_request).await
3214                })
3215                .await;
3216                let response = match sent {
3217                    Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
3218                    None => return Err(Failure::Retry(stalled(url, progress_timeout))),
3219                };
3220                Ok((response, Protocol::Http2, None))
3221            }
3222        }
3223    }
3224
3225    /// Returns `true` if a connection to `hop` presents the configured client
3226    /// certificate.
3227    ///
3228    /// This is the case if a certificate is configured, the hop is the origin
3229    /// that the route names, and that origin is TLS. A cleartext connection
3230    /// presents no certificate. If no certificate is configured, the result is
3231    /// always `false`, so the pool holds one entry for each origin.
3232    fn presents_identity(&self, hop: &Origin, named: &Origin) -> bool {
3233        self.inner.client_identity && hop.tls && hop == named
3234    }
3235
3236    /// Ends an attempt with a response that the caller did not ask for.
3237    ///
3238    /// If the response declares a body of at most [`DRAIN_LIMIT`] bytes, the
3239    /// function reads it to the end. This frees its HTTP/1.1 connection for the
3240    /// next request. The function drops a larger declared body, or a body with
3241    /// no declared length. The connection then closes, because the rest of the
3242    /// response is still in flight.
3243    ///
3244    /// An HTTP/2 stream has no such cost, because its connection stays in the
3245    /// pool, whatever the stream did. So it needs no drain.
3246    ///
3247    /// `drain_until` is the limit for all reads of one attempt here. It is one
3248    /// progress window from the start of the attempt, and the reads share it. A
3249    /// read that reaches the end of the window drops the remaining response. A
3250    /// read that finds no time left drops the connection and reads nothing.
3251    async fn discard(
3252        &self,
3253        key: &PoolKey,
3254        response: Response<Incoming>,
3255        reuse: Option<H1Sender>,
3256        drain_until: Instant,
3257    ) {
3258        let Some(sender) = reuse else { return };
3259        if content_length(response.headers()).is_none_or(|length| length > DRAIN_LIMIT) {
3260            return;
3261        }
3262        let budget = drain_until.saturating_duration_since(Instant::now());
3263        if budget.is_zero() {
3264            return;
3265        }
3266        let mut body = response.into_body();
3267        // The drain runs in the remaining window of the attempt. So a peer that
3268        // declares a short body and then stops costs the attempt no more than a
3269        // stalled body, whatever the hop count.
3270        let drained = within(budget, async {
3271            loop {
3272                let frame = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
3273                match frame {
3274                    Some(Ok(_)) => continue,
3275                    Some(Err(_)) => return false,
3276                    None => return true,
3277                }
3278            }
3279        })
3280        .await;
3281        if drained == Some(true) {
3282            self.inner.put_h1(key, sender);
3283        }
3284    }
3285
3286    /// Sends `request` and tries each destination until one takes it.
3287    ///
3288    /// Each final status returns an [`Uploaded`], also 408, 429, and 5xx. The
3289    /// mirrors, the proxy, TLS, the client certificate, the headers, the
3290    /// credentials, and the cleartext rule apply to an upload as they apply to
3291    /// [`fetch`](Fetcher::fetch). An upload can also carry a [`BearerToken`] of
3292    /// its own as its credential. The fetcher sets no `Content-Type` header and
3293    /// no `Expect` header.
3294    ///
3295    /// The hand-over gives the request to hyper. A failure before the
3296    /// hand-over returns the error that a fetch returns. A failure after the
3297    /// hand-over returns [`Error::UploadInterrupted`].
3298    ///
3299    /// # Retries
3300    ///
3301    /// The fetcher tries an upload again only while no part of the request is
3302    /// sent. The request is unsent if the attempt fails before hyper accepts
3303    /// it, in one of these steps:
3304    ///
3305    /// - the connect
3306    /// - the `CONNECT` tunnel
3307    /// - the TLS handshake
3308    /// - the HTTP handshake
3309    /// - the wait for a ready connection.
3310    ///
3311    /// The request is also unsent if hyper gives it back unwritten. The bytes
3312    /// of a `CONNECT` go to the proxy alone and are no part of the request.
3313    ///
3314    /// An unsent attempt spends a round as a retryable failure of a fetch
3315    /// does. The upload asks the next mirror, then repeats the round after the
3316    /// backoff, up to [`max_retries`](FetcherOptions::max_retries) times. A 407
3317    /// to the `CONNECT` is definitive. If the rounds run out before the request
3318    /// is sent, the upload returns the [`Error::Fetch`] that a fetch returns.
3319    ///
3320    /// If the writer of a streamed body is dropped before it closes the body,
3321    /// the upload fails before the hand-over. It fails with [`Error::Fetch`]
3322    /// and sends nothing.
3323    ///
3324    /// All other outcomes count as sent. The upload then ends on the
3325    /// destination that took it, and asks no other mirror and no other round.
3326    /// A failure after the hand-over fails the upload with
3327    /// [`Error::UploadInterrupted`], because the server can have received the
3328    /// whole request and acted on it. An HTTP/2 stream that the server refuses
3329    /// or resets after the hand-over is such a failure.
3330    ///
3331    /// # Redirects
3332    ///
3333    /// For a body given whole, the upload follows a 307 or a 308. It keeps the
3334    /// method and sends the bytes again. The redirect rules of
3335    /// [`fetch`](Fetcher::fetch) apply: the redirect limit, the refusal of a
3336    /// hop from `https` to `http`, and the scope of the credentials.
3337    ///
3338    /// The first hop sends the request. So a failure on a later hop, a refused
3339    /// hop, and a redirect past the limit each fail the upload with
3340    /// [`Error::UploadInterrupted`].
3341    ///
3342    /// The upload returns these redirects as their status in an [`Uploaded`]:
3343    ///
3344    /// - a redirect status other than 307 and 308
3345    /// - each redirect of a streamed body
3346    /// - a 307 or a 308 with no `Location` that the upload can read
3347    /// - each redirect if [`max_redirects`](FetcherOptions::max_redirects) is
3348    ///   0.
3349    ///
3350    /// # Connections
3351    ///
3352    /// An upload uses the pooled HTTP/2 connection of its origin. It takes an
3353    /// idle HTTP/1.1 connection from the pool only if the connection became
3354    /// idle less than 2 seconds ago. Otherwise, it opens a connection of its
3355    /// own.
3356    ///
3357    /// A server can close an idle connection at any time. If hyper began to
3358    /// write an upload over a connection that the server closed, the upload
3359    /// counts as sent. A server closes an idle connection at the end of its
3360    /// idle timeout, so it keeps a connection that became idle a short time
3361    /// ago.
3362    ///
3363    /// If a pooled HTTP/1.1 connection fails before hyper writes the request,
3364    /// the fetcher drops the connection. The upload then continues over a new
3365    /// connection and spends no round.
3366    ///
3367    /// The HTTP/1.1 connection of an upload goes back to the pool if both
3368    /// bodies end cleanly. That is, hyper takes the end of the request body
3369    /// before the response head arrives. Then the caller reads the response
3370    /// body to its end with no failure. Each of these closes the connection:
3371    ///
3372    /// - a response that closes the connection
3373    /// - an HTTP/1.0 response
3374    /// - an answer that arrives before the end of the request body
3375    /// - a response body that fails
3376    /// - a response that is dropped before its end.
3377    ///
3378    /// # The response ends the request body
3379    ///
3380    /// A server can answer before it reads the whole request body. If the
3381    /// response body ends or is dropped before the request body ends, the
3382    /// fetcher fails the request body. The writer then gets
3383    /// [`io::ErrorKind::BrokenPipe`](std::io::ErrorKind::BrokenPipe), and hyper
3384    /// stops the body.
3385    ///
3386    /// The stop of the body closes an HTTP/1.1 connection and resets an HTTP/2
3387    /// stream. The same applies to a response that the upload does not
3388    /// deliver: a followed redirect, a refused coding, and a declared length
3389    /// over the cap.
3390    ///
3391    /// # Deadlines
3392    ///
3393    /// - [`connect_timeout`](FetcherOptions::connect_timeout) bounds the open
3394    ///   of a connection.
3395    /// - [`fetch_timeout`](FetcherOptions::fetch_timeout) bounds the upload
3396    ///   from admission to the hand-over alone.
3397    /// - While a streamed body streams, the one bound is the stall window of
3398    ///   [`UploadWriter`], which starts at the hand-over.
3399    /// - For a body given whole, a frame that the connection does not take for
3400    ///   [`progress_timeout`](FetcherOptions::progress_timeout) ends the upload
3401    ///   with [`Error::UploadInterrupted`].
3402    /// - The wait for the response head lasts
3403    ///   [`response_timeout`](UploadRequest::response_timeout).
3404    /// - The response body has the progress window of a fetch.
3405    ///
3406    /// Before the hand-over, a wait of the writer has no bound of its own. This
3407    /// applies at the gate, during the connect, and during the backoff between
3408    /// rounds.
3409    /// The low-speed rule does not apply to an upload.
3410    ///
3411    /// # Errors
3412    ///
3413    /// If more than one destination fails before the hand-over, the failure
3414    /// order of [`fetch`](Fetcher::fetch) states which error the upload
3415    /// returns.
3416    ///
3417    /// - [`Error::Fetch`] before admission, if a path holds a `?` or a `#`, if
3418    ///   the query of a [`Target::PathQuery`] holds a `#`, or if the fetcher
3419    ///   has no mirror for a path target.
3420    /// - [`Error::Fetch`] before admission, if a URL target is not a valid
3421    ///   absolute URL, or holds a fragment or userinfo.
3422    /// - [`Error::Unsupported`] if the scheme of a URL target is neither `http`
3423    ///   nor `https`.
3424    /// - [`Error::Fetch`] before admission, if a request header is invalid, is
3425    ///   `Host`, or is a header that the connection layer sets.
3426    /// - [`Error::Fetch`] before admission, if two credentials of the request
3427    ///   meet: [`basic_auth`](UploadRequest::basic_auth),
3428    ///   [`bearer_token`](UploadRequest::bearer_token), and an `Authorization`
3429    ///   header. A bearer token that is not token68 also fails.
3430    /// - [`Error::Fetch`] before admission, if a credential can reach a
3431    ///   cleartext destination, and neither
3432    ///   [`allow_cleartext_credentials`](UploadRequest::allow_cleartext_credentials)
3433    ///   nor [`FetcherOptions::allow_cleartext_credentials`] is `true`.
3434    /// - [`Error::Fetch`] before admission, if the route names a TLS
3435    ///   destination and the fetcher holds no trust anchors.
3436    /// - [`Error::Fetch`] before admission, if the method is `DELETE` and the
3437    ///   body is not an empty [`UploadBody::bytes`].
3438    /// - [`Error::Fetch`] if a transport failure ends the rounds before the
3439    ///   hand-over: a failed connect, handshake, or proxy `CONNECT`, or an
3440    ///   expired deadline.
3441    /// - [`Error::Fetch`] if hyper cannot build the request.
3442    /// - [`Error::Fetch`] if the writer of a streamed body is dropped before
3443    ///   the hand-over.
3444    /// - [`Error::Fetch`] if [`fetch_timeout`](FetcherOptions::fetch_timeout)
3445    ///   expires before the hand-over.
3446    /// - [`Error::UploadInterrupted`] if a failure occurs after the hand-over.
3447    ///   This includes a refused redirect hop, a redirect past the limit, a
3448    ///   response that declares a coding, and a `Content-Length` over
3449    ///   [`max_response`](UploadRequest::max_response). The message names the
3450    ///   cause.
3451    ///
3452    /// # Examples
3453    ///
3454    /// ```no_run
3455    /// use ostrya_fetch::{Fetcher, FetcherOptions, UploadBody, UploadRequest};
3456    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
3457    /// let fetcher = Fetcher::new(FetcherOptions::new("https://example.com/repo")).await?;
3458    /// let body = UploadBody::bytes(b"report".to_vec());
3459    /// let uploaded = fetcher.upload(UploadRequest::path("inbox/report", body)).await?;
3460    /// println!("the server answered {}", uploaded.status());
3461    /// # Ok(())
3462    /// # }
3463    /// ```
3464    pub async fn upload(&self, request: UploadRequest<'_>) -> Result<Uploaded> {
3465        let UploadRequest {
3466            target,
3467            method,
3468            body,
3469            priority,
3470            max_response,
3471            headers,
3472            basic_auth,
3473            bearer_token,
3474            allow_cleartext_credentials,
3475            response_timeout,
3476        } = request;
3477        // As for a fetch, the checks of the request run before admission.
3478        // The check of the body that a DELETE does not send runs there too.
3479        let route = self.route(target)?;
3480        let headers = merge_headers(&self.inner.headers, headers, basic_auth, bearer_token)?;
3481        if !allow_cleartext_credentials && !self.inner.allow_cleartext_credentials {
3482            self.check_cleartext(&route, &headers)?;
3483        }
3484        self.check_trust_anchors(&route)?;
3485        let method = match method {
3486            UploadMethod::Post => Method::POST,
3487            UploadMethod::Delete => Method::DELETE,
3488        };
3489        let (end, bytes) = match body.form {
3490            UploadForm::Bytes(bytes) => (BodyEnd::whole(&bytes), Some(bytes)),
3491            UploadForm::Channel(end) => (end, None),
3492        };
3493        if method == Method::DELETE && !bytes.as_ref().is_some_and(Bytes::is_empty) {
3494            return Err(Error::Fetch(format!(
3495                "the delete of {} carries a body, which a delete does not send: pass an empty \
3496                 UploadBody::bytes",
3497                target.describe()
3498            )));
3499        }
3500        let plan = UploadPlan {
3501            method,
3502            headers: &headers,
3503            bytes,
3504            max_response,
3505            response_timeout: response_timeout.unwrap_or(self.inner.progress_timeout),
3506        };
3507        let permit = self.inner.gate.acquire(priority).await;
3508        // This flag is set while hyper holds the request. The admission
3509        // deadline stops then, because the steps after the hand-over have
3510        // deadlines of their own.
3511        let handed = AtomicBool::new(false);
3512        let rounds = self.upload_rounds(&plan, &route, end, &handed);
3513        let mut uploaded = match self.inner.fetch_timeout {
3514            None => rounds.await?,
3515            Some(limit) => match before_hand_over(limit, &handed, rounds).await {
3516                Some(result) => result?,
3517                None => {
3518                    return Err(Error::Fetch(format!(
3519                        "upload of {} was not sent within {limit:?}",
3520                        target.describe()
3521                    )));
3522                }
3523            },
3524        };
3525        uploaded.body.permit = Some(permit);
3526        Ok(uploaded)
3527    }
3528
3529    /// Tries each destination in turn, as [`rounds`](Fetcher::rounds) does for
3530    /// a fetch.
3531    ///
3532    /// The function repeats the round while the request is unsent and a
3533    /// destination failed retryably. A request that is sent ends the rounds,
3534    /// whatever its outcome.
3535    async fn upload_rounds(
3536        &self,
3537        plan: &UploadPlan<'_>,
3538        route: &Route<'_>,
3539        end: BodyEnd,
3540        handed: &AtomicBool,
3541    ) -> Result<Uploaded> {
3542        let destination_count = match route {
3543            Route::Mirrors { .. } => self.inner.mirrors.len(),
3544            Route::One(_) => 1,
3545        };
3546        let mut settled = vec![false; destination_count];
3547        let mut reported: Option<Error> = None;
3548        let mut definitive = false;
3549        let mut round = 0;
3550        // An attempt takes the body when it hands the request over. If the
3551        // request comes back unsent, the attempt puts the body back here.
3552        let mut body = Some(end);
3553        loop {
3554            let mut retryable = false;
3555            for (position, settled) in settled.iter_mut().enumerate() {
3556                if *settled {
3557                    continue;
3558                }
3559                let destination = match route {
3560                    Route::Mirrors { path, query } => {
3561                        Cow::Owned(self.inner.mirrors[position].destination(path, *query))
3562                    }
3563                    Route::One(destination) => Cow::Borrowed(destination),
3564                };
3565                match self
3566                    .upload_attempt(&destination, plan, &mut body, handed)
3567                    .await
3568                {
3569                    Ok(uploaded) => return Ok(uploaded),
3570                    Err(UploadFailure::Sent { url, message }) => {
3571                        return Err(Error::UploadInterrupted { url, message });
3572                    }
3573                    Err(UploadFailure::Unsent(Failure::Retry(e))) => {
3574                        retryable = true;
3575                        if reported.is_none() {
3576                            reported = Some(e);
3577                        }
3578                    }
3579                    Err(UploadFailure::Unsent(Failure::Fatal(e))) => {
3580                        *settled = true;
3581                        if !definitive {
3582                            reported = Some(e);
3583                            definitive = true;
3584                        }
3585                    }
3586                }
3587            }
3588            if !retryable || round >= self.inner.max_retries {
3589                return Err(reported.expect("a failed round holds a failure"));
3590            }
3591            round += 1;
3592            rt::Timer::after(backoff(round)).await;
3593        }
3594    }
3595
3596    /// Runs one upload against one destination, and follows the redirects of a
3597    /// body given whole.
3598    ///
3599    /// The first hop that hyper takes sends the request. So a failure on a
3600    /// later hop is final: the function reports an interrupted upload, and the
3601    /// rounds stop. The function drops a response that the upload does not
3602    /// deliver. This also drops a request body that did not end, and closes
3603    /// the connection of an HTTP/1.1 hop.
3604    async fn upload_attempt(
3605        &self,
3606        destination: &Destination,
3607        plan: &UploadPlan<'_>,
3608        body: &mut Option<BodyEnd>,
3609        handed: &AtomicBool,
3610    ) -> std::result::Result<Uploaded, UploadFailure> {
3611        let named = &destination.origin;
3612        let mut hop = Cow::Borrowed(destination);
3613        let mut headers = Cow::Borrowed(plan.headers);
3614        let mut followed = 0u32;
3615        loop {
3616            let via = self.inner.proxies.via(&hop.origin);
3617            let key = PoolKey {
3618                origin: match via {
3619                    Via::Absolute(proxy) => proxy.endpoint.clone(),
3620                    Via::Direct | Via::Tunnel(_) => hop.origin.clone(),
3621                },
3622                identity: self.presents_identity(&hop.origin, named),
3623                proxied: matches!(via, Via::Absolute(_)),
3624            };
3625            let url = hop.url();
3626            let sent = self
3627                .upload_send(&hop, &key, via, plan, &headers, body, handed)
3628                .await;
3629            let (response, protocol, request_end, reuse) = match sent {
3630                Ok(sent) => sent,
3631                Err(UploadFailure::Unsent(failure)) if followed > 0 => {
3632                    return Err(interrupted(url, failure.into_error().to_string()));
3633                }
3634                Err(failure) => return Err(failure),
3635            };
3636            let status = response.status();
3637            if let Some(bytes) = &plan.bytes
3638                && UPLOAD_REDIRECTS.contains(&status)
3639                && self.inner.max_redirects > 0
3640                && let Some(location) = response
3641                    .headers()
3642                    .get(hyper::header::LOCATION)
3643                    .and_then(|value| resolve_location(url, value))
3644            {
3645                if followed >= self.inner.max_redirects {
3646                    return Err(undelivered(
3647                        url,
3648                        Error::RedirectLimit {
3649                            url: url.to_string(),
3650                            hops: followed,
3651                        },
3652                    ));
3653                }
3654                let next =
3655                    redirect_destination(&hop, &location).map_err(|e| undelivered(url, e))?;
3656                if next.origin.tls && !self.inner.has_trust_anchors {
3657                    return Err(undelivered(url, no_trust_anchors(next.origin_url())));
3658                }
3659                // As for a fetch, a credential stays with the origin that the
3660                // route names.
3661                if next.origin != *named && headers.iter().any(|(name, _)| is_credential(name)) {
3662                    let scoped = headers
3663                        .iter()
3664                        .filter(|(name, _)| !is_credential(name))
3665                        .cloned()
3666                        .collect::<Vec<_>>();
3667                    headers = Cow::Owned(scoped);
3668                }
3669                hop = Cow::Owned(next);
3670                followed += 1;
3671                *body = Some(BodyEnd::whole(bytes));
3672                continue;
3673            }
3674            if let Some(encoding) = declared_coding(response.headers()) {
3675                return Err(undelivered(
3676                    url,
3677                    Error::ContentEncoded {
3678                        url: url.to_string(),
3679                        encoding,
3680                    },
3681                ));
3682            }
3683            let content_length = content_length(response.headers());
3684            if content_length.is_some_and(|length| length > plan.max_response) {
3685                return Err(undelivered(
3686                    url,
3687                    Error::FetchTooLarge {
3688                        limit: plan.max_response,
3689                    },
3690                ));
3691            }
3692            let protocol = match response.version() {
3693                Version::HTTP_2 => Protocol::Http2,
3694                _ => protocol,
3695            };
3696            let (parts, incoming) = response.into_parts();
3697            return Ok(Uploaded {
3698                status: parts.status,
3699                headers: parts.headers,
3700                url: url.to_string(),
3701                body: Body {
3702                    incoming,
3703                    chunk: Bytes::new(),
3704                    received: 0,
3705                    max_size: Some(plan.max_response),
3706                    validators: Validators::default(),
3707                    content_length,
3708                    protocol,
3709                    inner: self.inner.clone(),
3710                    counters: self.received.clone(),
3711                    key,
3712                    reuse,
3713                    permit: None,
3714                    done: false,
3715                    failed: None,
3716                    deadline: rt::Deadline::new(self.inner.progress_timeout),
3717                    waiting: false,
3718                    low_speed: None,
3719                    interrupted: None,
3720                    request_body: Some(request_end),
3721                },
3722            });
3723        }
3724    }
3725
3726    /// Takes or opens a connection for one upload hop, and hands the request
3727    /// to hyper.
3728    ///
3729    /// An upload takes the pooled HTTP/2 connection, or an idle HTTP/1.1
3730    /// connection from [`Inner::take_upload`]. If a pooled HTTP/1.1 connection
3731    /// fails before hyper writes the request, the function drops it. The hop
3732    /// then continues over a new connection and spends no round.
3733    ///
3734    /// A failure before the hand-over leaves the body in `body`. A request
3735    /// that hyper gives back unwritten also leaves it there. A body that failed
3736    /// before the hand-over is never sent. The stall window of the body starts
3737    /// at the hand-over, and [`answer`] then bounds the wait for the response
3738    /// head.
3739    ///
3740    /// The HTTP/1.1 connection comes back with the response if it can carry
3741    /// the next request after the response body ends. That is, hyper took the
3742    /// end of the request body before the response head arrived, and the
3743    /// response does not close the connection. In each other case, the
3744    /// connection closes at the end of the exchange.
3745    #[allow(clippy::too_many_arguments)]
3746    async fn upload_send(
3747        &self,
3748        hop: &Destination,
3749        key: &PoolKey,
3750        via: Via<'_>,
3751        plan: &UploadPlan<'_>,
3752        headers: &[(HeaderName, HeaderValue)],
3753        body: &mut Option<BodyEnd>,
3754        handed: &AtomicBool,
3755    ) -> std::result::Result<UploadResponse, UploadFailure> {
3756        let url = hop.url();
3757        let unsent = |failure: Failure| -> std::result::Result<UploadResponse, UploadFailure> {
3758            Err(UploadFailure::Unsent(failure))
3759        };
3760        let exchange = body
3761            .as_ref()
3762            .expect("an upload attempt holds its body until it sends it")
3763            .exchange
3764            .clone();
3765        if let Some(reason) = exchange.aborted() {
3766            return unsent(Failure::Fatal(not_sent(url, reason)));
3767        }
3768        let progress_timeout = self.inner.progress_timeout;
3769        let mut pooled = self.inner.take_upload(key);
3770        loop {
3771            // If a pooled HTTP/1.1 connection fails before hyper writes the
3772            // request, the server closed it while it was idle.
3773            let stale_h1 = matches!(pooled, Some(Sender::H1(_)));
3774            let mut sender = match pooled.take() {
3775                Some(sender) => sender,
3776                None => {
3777                    let connect_timeout = self.inner.connect_timeout;
3778                    match within(connect_timeout, Box::pin(self.connect(key, via))).await {
3779                        Some(Ok(sender)) => sender,
3780                        Some(Err(failure)) => return unsent(failure),
3781                        None => {
3782                            return unsent(Failure::Retry(connect_timed_out(
3783                                &key.origin,
3784                                via,
3785                                connect_timeout,
3786                            )));
3787                        }
3788                    }
3789                }
3790            };
3791            let protocol = match sender {
3792                Sender::H1(_) => Protocol::Http11,
3793                Sender::H2(_) => Protocol::Http2,
3794            };
3795            let mut head = match self.upload_head(hop, plan, headers, protocol, via) {
3796                Ok(head) => head,
3797                Err(e) => return unsent(Failure::Fatal(e)),
3798            };
3799            let ready = match &mut sender {
3800                Sender::H1(sender) => within(progress_timeout, sender.ready()).await,
3801                Sender::H2(sender) => within(progress_timeout, sender.ready()).await,
3802            };
3803            match ready {
3804                Some(Ok(())) => {}
3805                Some(Err(_)) if stale_h1 => continue,
3806                Some(Err(e)) => return unsent(Failure::Retry(transport(url, e))),
3807                None => return unsent(Failure::Retry(stalled(url, progress_timeout))),
3808            }
3809            let empty = match exchange.hand_over(progress_timeout) {
3810                Ok(empty) => empty,
3811                Err(reason) => return unsent(Failure::Fatal(not_sent(url, reason))),
3812            };
3813            // A `POST` whose body is at its end states its length. hyper writes
3814            // no length for an HTTP/1.1 request at the end of its body. The
3815            // method defines content, so a server that waits for the framing
3816            // reads `0`.
3817            if empty && plan.method == Method::POST {
3818                head.headers_mut()
3819                    .insert(hyper::header::CONTENT_LENGTH, HeaderValue::from_static("0"));
3820            }
3821            let end = body
3822                .take()
3823                .expect("an upload attempt holds its body until it sends it");
3824            let request = head.map(|()| RequestBody::Upload(end));
3825            handed.store(true, Ordering::Relaxed);
3826            let window = plan.response_timeout;
3827            let (answered, h1) = match sender {
3828                Sender::H1(mut sender) => {
3829                    let answered =
3830                        answer(sender.try_send_request(request), &exchange, window).await;
3831                    (answered, Some(sender))
3832                }
3833                Sender::H2(mut sender) => {
3834                    let answered =
3835                        answer(sender.try_send_request(request), &exchange, window).await;
3836                    (answered, None)
3837                }
3838            };
3839            let response = match answered {
3840                Answer::Sent(Ok(response)) => response,
3841                Answer::Sent(Err(mut e)) => {
3842                    let Some(request) = e.take_message() else {
3843                        exchange.cut();
3844                        return Err(interrupted(url, with_cause(&e.into_error())));
3845                    };
3846                    // hyper gives the request back if the connection failed
3847                    // before hyper wrote a part of it. So the body is whole,
3848                    // and the request is unsent.
3849                    exchange.withdraw();
3850                    if let RequestBody::Upload(end) = request.into_body() {
3851                        *body = Some(end);
3852                    }
3853                    handed.store(false, Ordering::Relaxed);
3854                    if stale_h1 {
3855                        continue;
3856                    }
3857                    return unsent(Failure::Retry(transport(url, e.into_error())));
3858                }
3859                Answer::Aborted(reason) => return Err(interrupted(url, reason)),
3860                Answer::Silent(window) => {
3861                    return Err(interrupted(
3862                        url,
3863                        format!("no response within {window:?} of the end of the request body"),
3864                    ));
3865                }
3866            };
3867            // A head that arrived before hyper took the end of the body is an
3868            // early answer. The body is cut when the response ends, and the
3869            // cut closes the connection.
3870            let reuse = h1.filter(|_| exchange.has_ended() && !closes(&response));
3871            return Ok((response, protocol, RequestEnd { exchange }, reuse));
3872        }
3873    }
3874
3875    /// Starts the upload request against `destination`, in the form that
3876    /// `protocol` and `via` give it.
3877    ///
3878    /// [`request_head`](Fetcher::request_head) does the same for a fetch.
3879    fn upload_head(
3880        &self,
3881        destination: &Destination,
3882        plan: &UploadPlan<'_>,
3883        headers: &[(HeaderName, HeaderValue)],
3884        protocol: Protocol,
3885        via: Via<'_>,
3886    ) -> Result<Request<()>> {
3887        self.request_head(plan.method.clone(), destination, headers, protocol, via)?
3888            .body(())
3889            .map_err(|e| Error::Fetch(format!("invalid request for {}: {e}", destination.url())))
3890    }
3891
3892    /// Builds the GET for `request` against `destination`, with `headers` and
3893    /// the validators of the request.
3894    fn build_request(
3895        &self,
3896        destination: &Destination,
3897        request: &FetchRequest<'_>,
3898        headers: &[(HeaderName, HeaderValue)],
3899        protocol: Protocol,
3900        via: Via<'_>,
3901    ) -> Result<Request<RequestBody>> {
3902        let mut builder = self.request_head(Method::GET, destination, headers, protocol, via)?;
3903        if let Some(validators) = request.validators {
3904            if let Some(etag) = &validators.etag {
3905                builder = builder.header(hyper::header::IF_NONE_MATCH, etag);
3906            }
3907            if let Some(last_modified) = &validators.last_modified {
3908                builder = builder.header(hyper::header::IF_MODIFIED_SINCE, last_modified);
3909            }
3910        }
3911        builder
3912            .body(RequestBody::Empty)
3913            .map_err(|e| Error::Fetch(format!("invalid request for {}: {e}", destination.url())))
3914    }
3915
3916    /// Starts the request of `method` against `destination`, with `headers`.
3917    ///
3918    /// An HTTP/1.1 request carries the origin-form target and a `Host` header,
3919    /// as an origin server expects. The absolute form is for proxy requests,
3920    /// and a plain static-file server answers 404 to it. An HTTP/2 request
3921    /// carries the absolute URL, and hyper fills the `:scheme` and
3922    /// `:authority` pseudo-headers from it.
3923    ///
3924    /// A request to a cleartext origin over a proxy connection carries the
3925    /// absolute form, which tells the proxy where to send it. Its `Host`
3926    /// header names the origin.
3927    ///
3928    /// The request also carries the credential of the proxy, if the merged
3929    /// headers hold no `Proxy-Authorization`. A `Proxy-Authorization` header
3930    /// that the caller set states the value for the proxy. Two values of one
3931    /// name give the proxy two answers to one question.
3932    ///
3933    /// A `CONNECT` tunnel carries the proxy credential of the fetcher on the
3934    /// `CONNECT` alone. So the request over the tunnel is the request that a
3935    /// direct connection sends.
3936    fn request_head(
3937        &self,
3938        method: Method,
3939        destination: &Destination,
3940        headers: &[(HeaderName, HeaderValue)],
3941        protocol: Protocol,
3942        via: Via<'_>,
3943    ) -> Result<hyper::http::request::Builder> {
3944        let absolute = protocol == Protocol::Http2 || matches!(via, Via::Absolute(_));
3945        let url = if absolute {
3946            destination.url()
3947        } else {
3948            destination.target()
3949        };
3950        let uri =
3951            Uri::try_from(url).map_err(|e| Error::Fetch(format!("invalid url {url}: {e}")))?;
3952        let mut builder = Request::builder().method(method).uri(uri);
3953        if protocol == Protocol::Http11 {
3954            builder = builder.header(hyper::header::HOST, &destination.authority);
3955        }
3956        for (name, value) in headers {
3957            builder = builder.header(name, value);
3958        }
3959        if let Via::Absolute(proxy) = via
3960            && let Some(credential) = &proxy.credential
3961            && !headers
3962                .iter()
3963                .any(|(name, _)| *name == hyper::header::PROXY_AUTHORIZATION)
3964        {
3965            builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
3966        }
3967        Ok(builder)
3968    }
3969
3970    /// Opens a connection for `key`, and selects the protocol over ALPN if the
3971    /// origin is TLS.
3972    ///
3973    /// The key states the client configuration of the handshake. So a
3974    /// connection that presents the client certificate and a connection that
3975    /// presents none are two pool entries. The pool gives neither to the hop
3976    /// of the other.
3977    ///
3978    /// `via` states what the connection reaches. The key of a proxied
3979    /// cleartext origin is the proxy endpoint. So the socket goes where the key
3980    /// names, and the requests over it carry the absolute form.
3981    ///
3982    /// The key of a tunneled TLS origin is the origin. So the socket goes to
3983    /// the proxy, and the handshake runs over the `CONNECT` exchange.
3984    ///
3985    /// A failure states if another attempt can get a different result. A proxy
3986    /// that refuses the tunnel with 407 refuses the credential of the fetcher,
3987    /// and no round of retries changes it. Each other failure is retryable.
3988    async fn connect(&self, key: &PoolKey, via: Via<'_>) -> std::result::Result<Sender, Failure> {
3989        let origin = &key.origin;
3990        let endpoint = match via {
3991            Via::Tunnel(proxy) => &proxy.endpoint,
3992            Via::Direct | Via::Absolute(_) => origin,
3993        };
3994        let tcp = rt::TcpStream::connect(&endpoint.host, endpoint.port)
3995            .await
3996            .map_err(|e| {
3997                Failure::Retry(Error::Fetch(match via {
3998                    Via::Direct => {
3999                        format!("connect to {}:{} failed: {e}", endpoint.host, endpoint.port)
4000                    }
4001                    Via::Absolute(proxy) | Via::Tunnel(proxy) => {
4002                        format!("connect to the proxy {} failed: {e}", proxy.named)
4003                    }
4004                }))
4005            })?;
4006        if !origin.tls {
4007            // Cleartext HTTP/2 needs prior knowledge or an upgrade. The
4008            // fetcher uses neither. So a cleartext origin speaks HTTP/1.1,
4009            // over a proxy and over a direct connection.
4010            return self
4011                .handshake_h1(key, FuturesIo::new(tcp))
4012                .await
4013                .map_err(Failure::Retry);
4014        }
4015        let tcp = match via {
4016            Via::Tunnel(proxy) => self.tunnel(proxy, origin, tcp).await?,
4017            Via::Direct | Via::Absolute(_) => tcp,
4018        };
4019        let server_name =
4020            rustls::pki_types::ServerName::try_from(origin.host.clone()).map_err(|e| {
4021                Failure::Retry(Error::Fetch(format!(
4022                    "invalid server name {}: {e}",
4023                    origin.host
4024                )))
4025            })?;
4026        let config = if key.identity {
4027            &self.inner.tls.with_identity
4028        } else {
4029            &self.inner.tls.without_identity
4030        };
4031        let stream = futures_rustls::TlsConnector::from(config.clone())
4032            .connect(server_name, tcp)
4033            .await
4034            .map_err(|e| {
4035                Failure::Retry(Error::Fetch(format!(
4036                    "tls handshake with {} failed: {e}",
4037                    origin.host
4038                )))
4039            })?;
4040        let h2 = stream.get_ref().1.alpn_protocol() == Some(b"h2");
4041        let io = FuturesIo::new(stream);
4042        if h2 {
4043            self.handshake_h2(key, io).await.map_err(Failure::Retry)
4044        } else {
4045            self.handshake_h1(key, io).await.map_err(Failure::Retry)
4046        }
4047    }
4048
4049    /// Asks `proxy` for a tunnel to `origin`, and returns the socket of the
4050    /// tunnel.
4051    ///
4052    /// The `CONNECT` goes over the HTTP/1.1 client of hyper, which reads the
4053    /// answer and gives the socket back. A 2xx to a `CONNECT` is an upgrade,
4054    /// and the upgraded I/O is the stream of the handshake. The connection
4055    /// future delivers it, so the future runs in its own task and ends with the
4056    /// upgrade.
4057    ///
4058    /// Bytes in the buffer after the response fail the connect. Nothing comes
4059    /// after a `CONNECT` response before the client speaks. So a proxy that
4060    /// sent bytes does not speak the protocol of the tunnel. A TLS handshake
4061    /// over that stream starts to read after those bytes.
4062    async fn tunnel(
4063        &self,
4064        proxy: &ProxyEndpoint,
4065        origin: &Origin,
4066        tcp: rt::TcpStream,
4067    ) -> std::result::Result<rt::TcpStream, Failure> {
4068        let refused = |what: String| Failure::Retry(Error::Fetch(what));
4069        let authority = connect_authority(origin);
4070        let host = HeaderValue::try_from(&authority).map_err(|_| {
4071            Failure::Fatal(Error::Fetch(format!(
4072                "the proxy {} cannot be asked to reach {authority}, which is not a usable host",
4073                proxy.named
4074            )))
4075        })?;
4076        let mut builder = Request::builder()
4077            .method(Method::CONNECT)
4078            .uri(&authority)
4079            .header(hyper::header::HOST, host);
4080        if let Some(credential) = &proxy.credential {
4081            builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
4082        }
4083        let request = builder.body(RequestBody::Empty).map_err(|e| {
4084            refused(format!(
4085                "the connect request to the proxy {} for {authority} is invalid: {e}",
4086                proxy.named
4087            ))
4088        })?;
4089        let (mut sender, connection) = hyper::client::conn::http1::handshake(FuturesIo::new(tcp))
4090            .await
4091            .map_err(|e| {
4092                refused(format!(
4093                    "http/1.1 handshake with the proxy {} failed: {e}",
4094                    proxy.named
4095                ))
4096            })?;
4097        // The connection future delivers the upgrade, so it runs beside the
4098        // request. The future and its task end with the upgrade.
4099        drop(rt::spawn(async move {
4100            let _ = connection.with_upgrades().await;
4101        }));
4102        let response = async {
4103            sender.ready().await?;
4104            sender.send_request(request).await
4105        }
4106        .await
4107        .map_err(|e| {
4108            refused(format!(
4109                "connect to {authority} through the proxy {} failed: {e}",
4110                proxy.named
4111            ))
4112        })?;
4113        let status = response.status();
4114        if !status.is_success() {
4115            let message = format!(
4116                "the proxy {} answered the connect to {authority} with {}",
4117                proxy.named,
4118                status.as_u16()
4119            );
4120            // A 407 refuses the credential of the fetcher, or the absence of
4121            // one. Each round of retries offers the same again.
4122            return Err(match status {
4123                StatusCode::PROXY_AUTHENTICATION_REQUIRED => Failure::Fatal(Error::Fetch(message)),
4124                _ => Failure::Retry(Error::Fetch(message)),
4125            });
4126        }
4127        let upgraded = hyper::upgrade::on(response).await.map_err(|e| {
4128            refused(format!(
4129                "the proxy {} accepted the connect to {authority} without tunneling it: {e}",
4130                proxy.named
4131            ))
4132        })?;
4133        let parts = upgraded
4134            .downcast::<FuturesIo<rt::TcpStream>>()
4135            .map_err(|_| {
4136                refused(format!(
4137                    "the tunnel through the proxy {} to {authority} is not the socket it was \
4138                     opened over",
4139                    proxy.named
4140                ))
4141            })?;
4142        if !parts.read_buf.is_empty() {
4143            return Err(refused(format!(
4144                "the proxy {} sent {} bytes after the connect to {authority}, which nothing may \
4145                 follow",
4146                proxy.named,
4147                parts.read_buf.len()
4148            )));
4149        }
4150        Ok(parts.io.into_inner())
4151    }
4152
4153    /// Completes an HTTP/1.1 handshake, and runs the connection in its own
4154    /// task.
4155    async fn handshake_h1<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
4156    where
4157        S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
4158    {
4159        let (sender, connection) =
4160            hyper::client::conn::http1::handshake(io)
4161                .await
4162                .map_err(|e| {
4163                    Error::Fetch(format!(
4164                        "http/1.1 handshake with {} failed: {e}",
4165                        key.origin.host
4166                    ))
4167                })?;
4168        drop(rt::spawn(async move {
4169            // The connection ends when the last sender drops or the peer closes
4170            // it. An error here shows on the next request over it.
4171            let _ = connection.await;
4172        }));
4173        Ok(Sender::H1(sender))
4174    }
4175
4176    /// Completes an HTTP/2 handshake, runs the connection in its own task, and
4177    /// puts it in the pool.
4178    ///
4179    /// The next requests to this origin multiplex over the connection. The
4180    /// function opens the connection through the builder of hyper. Only the
4181    /// builder sets the flow-control windows and the keep-alive ping.
4182    async fn handshake_h2<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
4183    where
4184        S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
4185    {
4186        let (sender, connection) = hyper::client::conn::http2::Builder::new(RtExecutor)
4187            .timer(RtTimer)
4188            .initial_stream_window_size(H2_STREAM_WINDOW)
4189            .initial_connection_window_size(self.inner.h2_connection_window)
4190            .keep_alive_interval(H2_KEEP_ALIVE_INTERVAL)
4191            .keep_alive_timeout(H2_KEEP_ALIVE_TIMEOUT)
4192            .handshake(io)
4193            .await
4194            .map_err(|e| {
4195                Error::Fetch(format!(
4196                    "http/2 handshake with {} failed: {e}",
4197                    key.origin.host
4198                ))
4199            })?;
4200        drop(rt::spawn(async move {
4201            let _ = connection.await;
4202        }));
4203        self.inner.put_h2(key, sender.clone());
4204        Ok(Sender::H2(sender))
4205    }
4206}
4207
4208impl Inner {
4209    /// Returns a pooled connection for `key`, if one is still usable.
4210    fn take_conn(&self, key: &PoolKey) -> Option<Sender> {
4211        let mut pool = self.pool.lock().expect("fetcher pool mutex");
4212        let entry = pool.get_mut(key)?;
4213        if let Some(h2) = &entry.h2 {
4214            if h2.is_closed() {
4215                entry.h2 = None;
4216            } else {
4217                return Some(Sender::H2(h2.clone()));
4218            }
4219        }
4220        while let Some(h1) = entry.h1.pop() {
4221            if !h1.sender.is_closed() {
4222                return Some(Sender::H1(h1.sender));
4223            }
4224        }
4225        None
4226    }
4227
4228    /// Returns a pooled connection that an upload can take for `key`.
4229    ///
4230    /// This is the HTTP/2 connection. If there is none, it is the HTTP/1.1
4231    /// connection that became idle last, if it became idle less than
4232    /// [`UPLOAD_IDLE`] ago.
4233    ///
4234    /// A server can close an idle connection at any time. If hyper began to
4235    /// write a request over a connection that the server closed, the request
4236    /// counts as sent. A server closes an idle connection at the end of its
4237    /// idle timeout, which is seconds or more. So the server keeps a connection
4238    /// that became idle a short time ago.
4239    ///
4240    /// An older idle connection stays in the pool for a fetch. If a fetch over
4241    /// it fails, the fetcher sends the fetch again.
4242    fn take_upload(&self, key: &PoolKey) -> Option<Sender> {
4243        let mut pool = self.pool.lock().expect("fetcher pool mutex");
4244        let entry = pool.get_mut(key)?;
4245        match &entry.h2 {
4246            Some(h2) if h2.is_closed() => entry.h2 = None,
4247            Some(h2) => return Some(Sender::H2(h2.clone())),
4248            None => {}
4249        }
4250        while let Some(h1) = entry.h1.last() {
4251            if h1.sender.is_closed() {
4252                entry.h1.pop();
4253                continue;
4254            }
4255            if h1.since.elapsed() >= UPLOAD_IDLE {
4256                return None;
4257            }
4258            return entry.h1.pop().map(|h1| Sender::H1(h1.sender));
4259        }
4260        None
4261    }
4262
4263    /// Returns an idle HTTP/1.1 connection to the pool.
4264    ///
4265    /// The function finds the existing entry of an origin by reference. A new
4266    /// entry needs a key of its own, and the host string of that key is an
4267    /// allocation. The lookup by reference keeps that allocation off the warm
4268    /// path of each object fetch.
4269    fn put_h1(&self, key: &PoolKey, sender: H1Sender) {
4270        if sender.is_closed() {
4271            return;
4272        }
4273        let idle = IdleH1 {
4274            sender,
4275            since: Instant::now(),
4276        };
4277        let mut pool = self.pool.lock().expect("fetcher pool mutex");
4278        if let Some(entry) = pool.get_mut(key) {
4279            entry.h1.push(idle);
4280            return;
4281        }
4282        pool.entry(key.clone()).or_default().h1.push(idle);
4283    }
4284
4285    /// Records the HTTP/2 connection of the origin, and keeps a usable
4286    /// connection that is already in the pool.
4287    ///
4288    /// Two concurrent connects to one origin each complete a handshake. The
4289    /// connection that loses the race serves only the request that opened it,
4290    /// and closes with that request. So it does not replace a pooled entry
4291    /// that other requests multiplex over. A replaced entry stays open, with
4292    /// no pool reference, until its own senders drop.
4293    ///
4294    /// The function finds the existing entry of an origin by reference, as
4295    /// [`Inner::put_h1`] does.
4296    fn put_h2(&self, key: &PoolKey, sender: H2Sender) {
4297        let mut pool = self.pool.lock().expect("fetcher pool mutex");
4298        if let Some(entry) = pool.get_mut(key) {
4299            match &entry.h2 {
4300                Some(pooled) if !pooled.is_closed() => {}
4301                _ => entry.h2 = Some(sender),
4302            }
4303            return;
4304        }
4305        pool.entry(key.clone()).or_default().h2 = Some(sender);
4306    }
4307}
4308
4309/// A fetch that starts again if its body fails in transit.
4310///
4311/// A body fails in transit in these cases:
4312///
4313/// - the connection reports an error
4314/// - the peer stays silent past the
4315///   [`progress_timeout`](FetcherOptions::progress_timeout) window
4316/// - the transfer is slower than the
4317///   [`low_speed`](FetcherOptions::low_speed) rule allows.
4318///
4319/// Each refetch spends one repeat of
4320/// [`max_retries`](FetcherOptions::max_retries), the count that also limits
4321/// the rounds of the fetch. So the rounds of each fetch and the refetches
4322/// between them share one budget. A refetch asks for the whole body again,
4323/// from the first destination, and sends no `Range` request.
4324///
4325/// A body that fails in another way is not fetched again, because another
4326/// fetch fails in the same way. Examples are the size cap and a failure of
4327/// the consumer, such as a checksum mismatch.
4328pub struct Refetch<'f, 'r> {
4329    fetcher: &'f Fetcher,
4330    request: FetchRequest<'r>,
4331    /// The repeats left in the budget.
4332    left: u32,
4333    /// The repeats spent. The next delay doubles from this count.
4334    round: u32,
4335    /// The flag that the body of the latest fetch sets if it fails in transit.
4336    interrupted: Arc<AtomicBool>,
4337}
4338
4339impl Refetch<'_, '_> {
4340    /// Fetches the request, with the rest of the budget for its rounds.
4341    ///
4342    /// # Errors
4343    ///
4344    /// This method returns the errors that [`Fetcher::fetch`] returns.
4345    pub async fn fetch(&mut self) -> Result<Fetched> {
4346        self.interrupted.store(false, Ordering::Relaxed);
4347        let (mut fetched, used) = self
4348            .fetcher
4349            .fetch_budgeted(&self.request, self.left)
4350            .await?;
4351        self.left -= used;
4352        self.round += used;
4353        if let Fetched::Body(body) = &mut fetched {
4354            body.interrupted = Some(self.interrupted.clone());
4355        }
4356        Ok(fetched)
4357    }
4358
4359    /// Prepares the next refetch, or returns `error` if no refetch applies.
4360    ///
4361    /// `error` is the error that ended the consumer of the latest body, in the
4362    /// error type of the caller. If that body failed in transit and a repeat
4363    /// is left, the method spends the repeat. It then waits for the backoff
4364    /// delay before the next [`fetch`](Refetch::fetch).
4365    ///
4366    /// The consumer drops the body before it calls this method. So the delay
4367    /// holds no connection and no admission permit.
4368    ///
4369    /// # Errors
4370    ///
4371    /// Returns `error` as it is if the latest body did not fail in transit, or
4372    /// if no repeat is left.
4373    pub async fn retry<E>(&mut self, error: E) -> std::result::Result<(), E> {
4374        if !self.interrupted.load(Ordering::Relaxed) || self.left == 0 {
4375            return Err(error);
4376        }
4377        self.left -= 1;
4378        self.round += 1;
4379        rt::Timer::after(backoff(self.round)).await;
4380        Ok(())
4381    }
4382}
4383
4384/// The result of one attempt.
4385#[allow(clippy::large_enum_variant)]
4386enum Attempted {
4387    Body(Body),
4388    NotModified,
4389}
4390
4391/// A failure that ends a body. Each later read gives it again.
4392struct Failed {
4393    kind: std::io::ErrorKind,
4394    message: String,
4395}
4396
4397impl Failed {
4398    fn error(&self) -> std::io::Error {
4399        std::io::Error::new(self.kind, self.message.clone())
4400    }
4401}
4402
4403/// The response body of a fetch or of an upload.
4404///
4405/// A read gives the bytes of the response in bounded chunks. The body releases
4406/// its connection and the admission permit when it reaches its end or is
4407/// dropped. A body dropped before its end closes an HTTP/1.1 connection and
4408/// resets an HTTP/2 stream, because the rest of the response is still in
4409/// flight.
4410///
4411/// # Failures
4412///
4413/// A failure ends the body. The failed read and each later read fail with the
4414/// same error. So a consumer that reads past a failure never gets a clean end
4415/// of stream, and cannot take a truncated object for a complete one. The
4416/// failures and their error kinds are:
4417///
4418/// - the size cap: [`FileTooLarge`](std::io::ErrorKind::FileTooLarge)
4419/// - the progress window and the low-speed rule:
4420///   [`TimedOut`](std::io::ErrorKind::TimedOut)
4421/// - a transport failure: [`Other`](std::io::ErrorKind::Other).
4422///
4423/// A failure releases neither the connection nor the permit. The drop of the
4424/// body releases both.
4425pub struct Body {
4426    incoming: Incoming,
4427    /// Bytes received from the connection and not yet copied to the caller.
4428    chunk: Bytes,
4429    /// The bytes taken from the connection. The caller is behind this count by
4430    /// the bytes still in `chunk`. The size cap applies to this count.
4431    received: u64,
4432    max_size: Option<u64>,
4433    validators: Validators,
4434    content_length: Option<u64>,
4435    protocol: Protocol,
4436    inner: Arc<Inner>,
4437    /// The counters of the fetcher handle that made the request. Each data
4438    /// frame adds its bytes to each of them.
4439    counters: Arc<[Arc<AtomicU64>]>,
4440    /// The pool entry of the connection of this body. The connection goes back
4441    /// to this entry.
4442    key: PoolKey,
4443    /// The HTTP/1.1 connection to return to the pool at the end of the body.
4444    reuse: Option<H1Sender>,
4445    /// The admission permit, which the body holds while it is in flight.
4446    permit: Option<Permit>,
4447    done: bool,
4448    /// The failure that ended the body, if one did.
4449    failed: Option<Failed>,
4450    /// The time that the peer can stay silent while a read waits for it.
4451    deadline: rt::Deadline,
4452    /// `true` while the window runs, from the read that finds nothing until
4453    /// the next frame arrives.
4454    ///
4455    /// The window measures the silence since a read wanted bytes. It keeps
4456    /// running also when no read is outstanding. A body that no read found
4457    /// empty is not on the clock.
4458    waiting: bool,
4459    /// The low-speed rule of the body, if the fetcher has one.
4460    low_speed: Option<Monitor>,
4461    /// The flag that reports a failure in transit to a [`Refetch`], which
4462    /// fetches the body again. The size cap is not a failure in transit,
4463    /// because another fetch of the body grows past the cap in the same way.
4464    interrupted: Option<Arc<AtomicBool>>,
4465    /// The request body of an upload. It fails when this body ends, or when
4466    /// this body is dropped before the request body ends.
4467    request_body: Option<RequestEnd>,
4468}
4469
4470/// The low-speed state of one body: the delivered bytes, the last samples of
4471/// that count, and the time below the limit.
4472struct Monitor {
4473    rule: LowSpeed,
4474    /// The bytes that the body delivered since its first read.
4475    counted: u64,
4476    /// `counted` at the last [`RATE_SPAN`] samples. The slot of the next
4477    /// sample holds the oldest sample. A slot that no sample filled holds the
4478    /// count at the first read, which is zero.
4479    samples: [u64; RATE_SPAN],
4480    /// The samples taken since the first read.
4481    taken: u64,
4482    /// The whole seconds for which the rate stayed at or below the limit, or
4483    /// `None` while the rate is above it. A body starts below the limit, at
4484    /// zero.
4485    below: Option<u64>,
4486    /// The time to the next sample.
4487    deadline: rt::Deadline,
4488    /// `true` after the measurement starts, which is at the first read.
4489    started: bool,
4490}
4491
4492impl Monitor {
4493    /// Creates the monitor for `rule`. The measurement starts at the first
4494    /// read.
4495    fn new(rule: LowSpeed) -> Monitor {
4496        Monitor {
4497            rule,
4498            counted: 0,
4499            samples: [0; RATE_SPAN],
4500            taken: 0,
4501            below: Some(0),
4502            deadline: rt::Deadline::new(SAMPLE_PERIOD),
4503            started: false,
4504        }
4505    }
4506
4507    /// Returns `true` if the rate stayed below the limit for the time of the
4508    /// rule.
4509    ///
4510    /// Each expiry of the timer takes one sample. If the next sample is not
4511    /// due, the poll leaves the timer to wake the task at the due time.
4512    fn below_rate(&mut self, cx: &mut Context<'_>) -> bool {
4513        while self.deadline.poll_expired(cx).is_ready() {
4514            if self.sample() {
4515                return true;
4516            }
4517            self.deadline.restart();
4518        }
4519        false
4520    }
4521
4522    /// Takes one sample, and returns `true` if the rate now stayed below the
4523    /// limit for the time of the rule.
4524    fn sample(&mut self) -> bool {
4525        self.taken += 1;
4526        let slot = (self.taken % RATE_SPAN as u64) as usize;
4527        let span = self.taken.min(RATE_SPAN as u64);
4528        let carried = self.counted - self.samples[slot];
4529        self.samples[slot] = self.counted;
4530        // A sample of exactly the limit counts as below it, as in the `ostree`
4531        // command. The samples of that command span a little more than their
4532        // whole seconds.
4533        if carried > u64::from(self.rule.limit) * span {
4534            self.below = None;
4535            return false;
4536        }
4537        let below = self.below.map_or(0, |seconds| seconds + 1);
4538        self.below = Some(below);
4539        Duration::from_secs(below) >= self.rule.time
4540    }
4541}
4542
4543impl std::fmt::Debug for Body {
4544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4545        f.debug_struct("Body")
4546            .field("protocol", &self.protocol)
4547            .field("content_length", &self.content_length)
4548            .field("received", &self.received)
4549            .finish_non_exhaustive()
4550    }
4551}
4552
4553impl Body {
4554    /// Returns the validators to send on the next fetch of this target.
4555    pub fn validators(&self) -> &Validators {
4556        &self.validators
4557    }
4558
4559    /// Returns the `Content-Length` that the response declared, if it declared
4560    /// one.
4561    pub fn content_length(&self) -> Option<u64> {
4562        self.content_length
4563    }
4564
4565    /// Returns the HTTP version that carried the response.
4566    pub fn protocol(&self) -> Protocol {
4567        self.protocol
4568    }
4569
4570    /// Returns the number of bytes that the body took from the connection.
4571    ///
4572    /// The body takes a frame whole and gives it out in as many reads as the
4573    /// buffers of the caller need. So this count can be up to one frame ahead
4574    /// of the bytes that the caller read. The size cap applies to this count.
4575    /// A caller that needs the count of delivered bytes counts them in its own
4576    /// read loop.
4577    pub fn received(&self) -> u64 {
4578        self.received
4579    }
4580
4581    /// Latches a failure that ends the body, and returns it.
4582    ///
4583    /// The body keeps the connection and the permit, so the drop releases
4584    /// them. The drop closes the connection, because a response still in
4585    /// flight does not go back to the pool.
4586    fn fail(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
4587        let failed = Failed { kind, message };
4588        let error = failed.error();
4589        self.failed = Some(failed);
4590        error
4591    }
4592
4593    /// Latches a failure in transit, and returns it. A [`Refetch`] can repeat
4594    /// the fetch for such a failure.
4595    fn interrupt(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
4596        if let Some(interrupted) = &self.interrupted {
4597            interrupted.store(true, Ordering::Relaxed);
4598        }
4599        self.fail(kind, message)
4600    }
4601
4602    /// Returns the failure of the low-speed rule, if the rate stayed at or
4603    /// below the limit for the time of the rule.
4604    ///
4605    /// Returns `None` while the rate holds, or if no rule applies.
4606    fn poll_low_speed(&mut self, cx: &mut Context<'_>) -> Option<std::io::Error> {
4607        let monitor = self.low_speed.as_mut()?;
4608        if !monitor.below_rate(cx) {
4609            return None;
4610        }
4611        let LowSpeed { limit, time } = monitor.rule;
4612        Some(self.interrupt(
4613            std::io::ErrorKind::TimedOut,
4614            format!("fetched body averaged below {limit} bytes per second for {time:?}"),
4615        ))
4616    }
4617}
4618
4619/// The read trait of `futures-io`.
4620impl AsyncRead for Body {
4621    fn poll_read(
4622        self: Pin<&mut Self>,
4623        cx: &mut Context<'_>,
4624        buf: &mut [u8],
4625    ) -> Poll<std::io::Result<usize>> {
4626        if buf.is_empty() {
4627            return Poll::Ready(Ok(0));
4628        }
4629        let me = self.get_mut();
4630        if let Some(failed) = &me.failed {
4631            return Poll::Ready(Err(failed.error()));
4632        }
4633        // The low-speed measurement starts at the first read. So the time for
4634        // which a body waits for its consumer before that read is not counted.
4635        if let Some(monitor) = &mut me.low_speed
4636            && !monitor.started
4637        {
4638            monitor.deadline.restart();
4639            monitor.started = true;
4640        }
4641        loop {
4642            if !me.chunk.is_empty() {
4643                let n = me.chunk.len().min(buf.len());
4644                buf[..n].copy_from_slice(&me.chunk[..n]);
4645                me.chunk = me.chunk.slice(n..);
4646                return Poll::Ready(Ok(n));
4647            }
4648            if me.done {
4649                return Poll::Ready(Ok(0));
4650            }
4651            let frame = match Pin::new(&mut me.incoming).poll_frame(cx) {
4652                Poll::Ready(frame) => frame,
4653                Poll::Pending => {
4654                    // Nothing arrived since the last frame. So the read fails
4655                    // when the progress window runs out, or when the rate
4656                    // stayed below the low-speed limit for the time of the rule.
4657                    if let Some(error) = me.poll_low_speed(cx) {
4658                        return Poll::Ready(Err(error));
4659                    }
4660                    if !me.waiting {
4661                        me.deadline.restart();
4662                        me.waiting = true;
4663                    }
4664                    return match me.deadline.poll_expired(cx) {
4665                        Poll::Ready(()) => {
4666                            let window = me.deadline.window();
4667                            Poll::Ready(Err(me.interrupt(
4668                                std::io::ErrorKind::TimedOut,
4669                                format!("fetched body delivered nothing for {window:?}"),
4670                            )))
4671                        }
4672                        Poll::Pending => Poll::Pending,
4673                    };
4674                }
4675            };
4676            match frame {
4677                Some(Ok(frame)) => {
4678                    // The peer delivered. The window stops until the next read
4679                    // finds nothing.
4680                    me.waiting = false;
4681                    // Trailers carry no payload, so the loop polls again for
4682                    // data.
4683                    if let Ok(data) = frame.into_data() {
4684                        me.received += data.len() as u64;
4685                        for counter in me.counters.iter() {
4686                            counter.fetch_add(data.len() as u64, Ordering::Relaxed);
4687                        }
4688                        if let Some(limit) = me.max_size
4689                            && me.received > limit
4690                        {
4691                            return Poll::Ready(Err(me.fail(
4692                                std::io::ErrorKind::FileTooLarge,
4693                                format!("fetched body exceeds the {limit}-byte cap"),
4694                            )));
4695                        }
4696                        if let Some(monitor) = &mut me.low_speed {
4697                            monitor.counted += data.len() as u64;
4698                        }
4699                        me.chunk = data;
4700                        if let Some(error) = me.poll_low_speed(cx) {
4701                            return Poll::Ready(Err(error));
4702                        }
4703                    }
4704                }
4705                Some(Err(e)) => {
4706                    // hyper reports a body error once, and then reports the end
4707                    // of the body. Without the latch, the next read returns a
4708                    // clean end of stream for a truncated object.
4709                    let message = with_cause(&e);
4710                    return Poll::Ready(Err(me.interrupt(std::io::ErrorKind::Other, message)));
4711                }
4712                None => {
4713                    me.done = true;
4714                    // The whole response arrived, so the connection can serve
4715                    // the next request. The response to an upload ends its
4716                    // request body, and hyper then stops the send of that body.
4717                    if let Some(sender) = me.reuse.take() {
4718                        me.inner.put_h1(&me.key, sender);
4719                    }
4720                    me.request_body = None;
4721                    me.permit = None;
4722                    return Poll::Ready(Ok(0));
4723                }
4724            }
4725        }
4726    }
4727}
4728
4729/// The read trait of tokio.
4730#[cfg(feature = "tokio")]
4731impl rt::tokio_io::AsyncRead for Body {
4732    fn poll_read(
4733        self: Pin<&mut Self>,
4734        cx: &mut Context<'_>,
4735        buf: &mut rt::tokio_io::ReadBuf<'_>,
4736    ) -> Poll<std::io::Result<()>> {
4737        let unfilled = buf.initialize_unfilled();
4738        let n = ready!(AsyncRead::poll_read(self, cx, unfilled))?;
4739        buf.advance(n);
4740        Poll::Ready(Ok(()))
4741    }
4742}
4743
4744/// The writing end of a streamed [`UploadBody`], from
4745/// [`UploadBody::channel`].
4746///
4747/// The writer and the upload run together. So a caller writes from a task
4748/// other than the task that awaits [`Fetcher::upload`], or joins the two
4749/// futures.
4750///
4751/// # Frames
4752///
4753/// Writes fill a frame of 64 KiB. The writer gives a full frame to the
4754/// connection through a slot of one frame. If the slot is still full, a write
4755/// waits until hyper takes the frame in it.
4756///
4757/// - [`flush`](AsyncWrite::poll_flush) hands over a part-filled frame, and
4758///   waits until hyper takes it.
4759/// - [`close`](AsyncWrite::poll_close) hands over the rest, ends the body,
4760///   and waits until hyper takes the end.
4761///
4762/// A flush of less than 4 KiB hands over a copy of the bytes and keeps the
4763/// frame buffer. A larger frame moves to the connection as it is, and the next
4764/// write allocates the next buffer.
4765///
4766/// # Memory
4767///
4768/// The writer holds at most two frames: the frame that it fills and the frame
4769/// in the slot. The connection holds more for each upload in flight.
4770///
4771/// Over HTTP/1.1, hyper takes another frame while it holds fewer than 16
4772/// frames and less than 408 KiB. So it holds up to 472 KiB. Over HTTP/2, it
4773/// holds up to two frames.
4774///
4775/// # Stalls
4776///
4777/// After the upload hands its request to the connection, a frame can wait in
4778/// the slot for the [`progress_timeout`](FetcherOptions::progress_timeout) of
4779/// its fetcher. If it does, the wait fails with
4780/// [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut), and the body
4781/// fails. Before the hand-over, a wait has no bound of its own.
4782///
4783/// # Failures
4784///
4785/// If the writer is dropped before close, the body fails. So hyper ends the
4786/// request unfinished, and the server never receives a truncated body as a
4787/// whole body. A writer dropped before the hand-over leaves the request
4788/// unsent.
4789///
4790/// A write fails with
4791/// [`io::ErrorKind::BrokenPipe`](std::io::ErrorKind::BrokenPipe) in these
4792/// cases:
4793///
4794/// - after close
4795/// - after the upload is done with the body
4796/// - after the response ended before the body.
4797///
4798/// A failure is latched: each later call fails in the same way.
4799pub struct UploadWriter {
4800    exchange: Arc<Exchange>,
4801    /// The frame that the writer fills. If a frame is handed over whole, the
4802    /// buffer has no capacity, and the next write allocates the next frame.
4803    buffer: Vec<u8>,
4804    /// The timer of the stall window. The first wait on a full slot after the
4805    /// hand-over arms it. If the timer fires before the frame in the slot
4806    /// waited the whole window, the writer arms it again for the rest.
4807    stall: Option<rt::Deadline>,
4808    /// The failure that ended the writer, if one did.
4809    failed: Option<Failed>,
4810}
4811
4812impl std::fmt::Debug for UploadWriter {
4813    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4814        f.debug_struct("UploadWriter")
4815            .field("buffered", &self.buffer.len())
4816            .finish_non_exhaustive()
4817    }
4818}
4819
4820/// The message of a write after the upload is done with the body.
4821const UPLOAD_ENDED: &str = "the upload of this body has ended";
4822
4823impl UploadWriter {
4824    /// Returns `true` if the request of this body is handed over to a
4825    /// connection.
4826    ///
4827    /// The value becomes `true` at the hand-over. It becomes `false` again if
4828    /// the connection gives the request back unwritten, until the next round
4829    /// hands it over. A caller that counts the bytes that a request sent counts
4830    /// the bytes that it wrote after the hand-over.
4831    pub fn is_handed_over(&self) -> bool {
4832        self.exchange.lock().stall.is_some()
4833    }
4834
4835    /// Latches a failure that ends the writer, and returns it.
4836    fn fail(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
4837        let failed = Failed { kind, message };
4838        let error = failed.error();
4839        self.failed = Some(failed);
4840        error
4841    }
4842
4843    /// Moves the buffer into the slot as the next frame, when the slot is
4844    /// free.
4845    ///
4846    /// The function copies a frame of less than [`SMALL_FRAME`] bytes, and
4847    /// keeps the buffer for the next frames. So a small frame that waits in the
4848    /// connection holds no more memory than its bytes. A larger frame moves as
4849    /// it is, and the next write allocates the next buffer.
4850    fn poll_hand_over(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
4851        let mut slot = self.exchange.lock();
4852        if slot.gone || slot.aborted.is_some() {
4853            drop(slot);
4854            return Poll::Ready(Err(
4855                self.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
4856            ));
4857        }
4858        if slot.frame.is_some() {
4859            park(&mut slot.writer, cx);
4860            let end = slot.stall_end();
4861            drop(slot);
4862            return self.poll_stall(cx, end);
4863        }
4864        let frame = if self.buffer.len() < SMALL_FRAME {
4865            let frame = Bytes::copy_from_slice(&self.buffer);
4866            self.buffer.clear();
4867            frame
4868        } else {
4869            Bytes::from(std::mem::take(&mut self.buffer))
4870        };
4871        slot.frame = Some(frame);
4872        slot.restart_stall();
4873        let reader = slot.reader.take();
4874        drop(slot);
4875        wake(reader);
4876        Poll::Ready(Ok(()))
4877    }
4878
4879    /// Waits until hyper takes the frame in the slot.
4880    fn poll_taken(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
4881        let mut slot = self.exchange.lock();
4882        if slot.gone || slot.aborted.is_some() {
4883            drop(slot);
4884            return Poll::Ready(Err(
4885                self.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
4886            ));
4887        }
4888        if slot.frame.is_none() {
4889            return Poll::Ready(Ok(()));
4890        }
4891        park(&mut slot.writer, cx);
4892        let end = slot.stall_end();
4893        drop(slot);
4894        self.poll_stall(cx, end)
4895    }
4896
4897    /// Polls the stall window of the frame in the slot. At `end`, the frame
4898    /// waited the whole window.
4899    ///
4900    /// The poll is pending while the window runs. It gives the failure of the
4901    /// body when the window runs out. Before the hand-over, `end` is `None`.
4902    /// The poll is then pending alone, and the take of the frame wakes the
4903    /// writer.
4904    fn poll_stall(
4905        &mut self,
4906        cx: &mut Context<'_>,
4907        mut end: Option<Instant>,
4908    ) -> Poll<std::io::Result<()>> {
4909        while let Some(at) = end {
4910            ready!(poll_until(&mut self.stall, cx, at));
4911            match self.exchange.check_stall() {
4912                Ok(message) => {
4913                    return Poll::Ready(Err(self.fail(std::io::ErrorKind::TimedOut, message)));
4914                }
4915                Err(later) => end = later,
4916            }
4917        }
4918        Poll::Pending
4919    }
4920}
4921
4922/// The write trait of `futures-io`.
4923impl AsyncWrite for UploadWriter {
4924    fn poll_write(
4925        self: Pin<&mut Self>,
4926        cx: &mut Context<'_>,
4927        buf: &[u8],
4928    ) -> Poll<std::io::Result<usize>> {
4929        let me = self.get_mut();
4930        if let Some(failed) = &me.failed {
4931            return Poll::Ready(Err(failed.error()));
4932        }
4933        let slot = me.exchange.lock();
4934        let refused = if slot.gone || slot.aborted.is_some() {
4935            Some(UPLOAD_ENDED)
4936        } else if slot.closed {
4937            Some("the upload body is closed")
4938        } else {
4939            None
4940        };
4941        drop(slot);
4942        if let Some(message) = refused {
4943            return Poll::Ready(Err(me.fail(std::io::ErrorKind::BrokenPipe, message.into())));
4944        }
4945        if buf.is_empty() {
4946            return Poll::Ready(Ok(0));
4947        }
4948        if me.buffer.len() == UPLOAD_FRAME {
4949            ready!(me.poll_hand_over(cx))?;
4950        }
4951        if me.buffer.capacity() == 0 {
4952            me.buffer.reserve_exact(UPLOAD_FRAME);
4953        }
4954        let n = (UPLOAD_FRAME - me.buffer.len()).min(buf.len());
4955        me.buffer.extend_from_slice(&buf[..n]);
4956        Poll::Ready(Ok(n))
4957    }
4958
4959    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
4960        let me = self.get_mut();
4961        if let Some(failed) = &me.failed {
4962            return Poll::Ready(Err(failed.error()));
4963        }
4964        if !me.buffer.is_empty() {
4965            ready!(me.poll_hand_over(cx))?;
4966        }
4967        me.poll_taken(cx)
4968    }
4969
4970    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
4971        let me = self.get_mut();
4972        if let Some(failed) = &me.failed {
4973            return Poll::Ready(Err(failed.error()));
4974        }
4975        if !me.buffer.is_empty() {
4976            ready!(me.poll_hand_over(cx))?;
4977        }
4978        let mut slot = me.exchange.lock();
4979        let reader = if slot.closed {
4980            None
4981        } else {
4982            slot.closed = true;
4983            slot.reader.take()
4984        };
4985        if slot.ended {
4986            drop(slot);
4987            wake(reader);
4988            return Poll::Ready(Ok(()));
4989        }
4990        if slot.gone || slot.aborted.is_some() {
4991            drop(slot);
4992            return Poll::Ready(Err(
4993                me.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
4994            ));
4995        }
4996        park(&mut slot.writer, cx);
4997        // The stall window runs over a frame that waits in the slot. An empty
4998        // slot waits for hyper to poll the end, and that wait is no stall of
4999        // the body.
5000        let end = slot.stall_end();
5001        drop(slot);
5002        wake(reader);
5003        me.poll_stall(cx, end)
5004    }
5005}
5006
5007/// The write trait of tokio.
5008#[cfg(feature = "tokio")]
5009impl rt::tokio_io::AsyncWrite for UploadWriter {
5010    fn poll_write(
5011        self: Pin<&mut Self>,
5012        cx: &mut Context<'_>,
5013        buf: &[u8],
5014    ) -> Poll<std::io::Result<usize>> {
5015        AsyncWrite::poll_write(self, cx, buf)
5016    }
5017
5018    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5019        AsyncWrite::poll_flush(self, cx)
5020    }
5021
5022    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5023        AsyncWrite::poll_close(self, cx)
5024    }
5025}
5026
5027impl Drop for UploadWriter {
5028    fn drop(&mut self) {
5029        let mut slot = self.exchange.lock();
5030        if slot.closed {
5031            return;
5032        }
5033        let wakers =
5034            slot.abort(|| "the upload writer was dropped before it closed the body".into());
5035        drop(slot);
5036        wakers.into_iter().for_each(wake);
5037    }
5038}
5039
5040/// Returns `true` if a header name carries credentials, which no cleartext
5041/// destination gets.
5042///
5043/// The value of these three header names is a secret, whatever it holds. The
5044/// fetcher sends each other header as the caller wrote it, except `Host` and
5045/// the connection-layer names, which both layers refuse. A caller can put a
5046/// secret into such a header, and the fetcher cannot tell.
5047fn is_credential(name: &HeaderName) -> bool {
5048    *name == hyper::header::AUTHORIZATION
5049        || *name == hyper::header::PROXY_AUTHORIZATION
5050        || *name == hyper::header::COOKIE
5051}
5052
5053/// Returns `true` if the connection layer sets a header of this name, so that
5054/// no caller can set it.
5055///
5056/// A `HeaderName` holds its name in lower case, and [`CONNECTION_HEADERS`] is
5057/// in lower case too.
5058fn is_connection_header(name: &HeaderName) -> bool {
5059    CONNECTION_HEADERS.contains(&name.as_str())
5060}
5061
5062/// Returns the error for a layer that sets a header of the connection layer.
5063fn connection_header_refused(name: &HeaderName) -> Error {
5064    Error::Fetch(format!(
5065        "the {name} header is set by the connection layer, which frames the request and \
5066         holds its connection: drop the header"
5067    ))
5068}
5069
5070/// Checks that a request path can go after the base path of a mirror.
5071///
5072/// A target is the base path with the request path added as written. So a `?`
5073/// or a `#` in that path is a delimiter. A `?` sends its tail as a query string
5074/// that the server matches on. A `#` and its tail drop out when the URL is
5075/// built, and the request asks for a different resource.
5076fn check_path(path: &str) -> Result<()> {
5077    if let Some(at) = path.find(['?', '#']) {
5078        let found = &path[at..=at];
5079        return Err(Error::Fetch(format!(
5080            "fetch path {path} carries {found}: a path holds no query and no fragment"
5081        )));
5082    }
5083    Ok(())
5084}
5085
5086/// Checks that the query string `query` of a request for `path` can go after
5087/// the path.
5088///
5089/// The target is the path with `?` and the query added as written. So a `#`
5090/// in the query is a delimiter. The `#` and its tail drop out when the URL is
5091/// built, and the server gets a query other than the query of the caller.
5092fn check_query(path: &str, query: &str) -> Result<()> {
5093    if query.contains('#') {
5094        return Err(Error::Fetch(format!(
5095            "fetch query of {path}?{query} carries #: a query holds no fragment"
5096        )));
5097    }
5098    Ok(())
5099}
5100
5101/// Returns the headers of one request: the headers of the fetcher, with the
5102/// headers of the request merged over them.
5103///
5104/// A request header replaces the fetcher header of the same name. The
5105/// credentials of the request replace the `Authorization` of the fetcher,
5106/// whichever of the two layers set it. These credentials are basic-auth
5107/// credentials or a bearer token, never both.
5108///
5109/// Two request headers of one name both reach the wire, as two fetcher headers
5110/// do. A request that adds no header and no credentials sends the list of the
5111/// fetcher as it is. Each object fetch takes this path.
5112///
5113/// A credential value is marked sensitive. So an HTTP/2 connection never adds
5114/// it to its header compression table.
5115fn merge_headers<'a>(
5116    fetcher: &'a [(HeaderName, HeaderValue)],
5117    extra: &[(String, String)],
5118    basic_auth: Option<&BasicAuth>,
5119    bearer_token: Option<&BearerToken>,
5120) -> Result<Cow<'a, [(HeaderName, HeaderValue)]>> {
5121    if extra.is_empty() && basic_auth.is_none() && bearer_token.is_none() {
5122        return Ok(Cow::Borrowed(fetcher));
5123    }
5124    if basic_auth.is_some() && bearer_token.is_some() {
5125        return Err(Error::Fetch(BASIC_AND_BEARER.into()));
5126    }
5127    let credential = usize::from(basic_auth.is_some() || bearer_token.is_some());
5128    let mut added = Vec::with_capacity(extra.len() + credential);
5129    for (name, value) in extra {
5130        let name = HeaderName::try_from(name.as_str())
5131            .map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
5132        if name == hyper::header::HOST {
5133            return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
5134        }
5135        if is_connection_header(&name) {
5136            return Err(connection_header_refused(&name));
5137        }
5138        if name == hyper::header::AUTHORIZATION && basic_auth.is_some() {
5139            return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
5140        }
5141        if name == hyper::header::AUTHORIZATION && bearer_token.is_some() {
5142            return Err(Error::Fetch(AMBIGUOUS_BEARER.into()));
5143        }
5144        let mut value = HeaderValue::try_from(value.as_str())
5145            .map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
5146        value.set_sensitive(is_credential(&name));
5147        added.push((name, value));
5148    }
5149    if let Some(auth) = basic_auth {
5150        added.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
5151    }
5152    if let Some(token) = bearer_token {
5153        added.push((hyper::header::AUTHORIZATION, bearer_value(token)?));
5154    }
5155    let mut headers = Vec::with_capacity(fetcher.len() + added.len());
5156    headers.extend(
5157        fetcher
5158            .iter()
5159            .filter(|(name, _)| !added.iter().any(|(replaced, _)| replaced == name))
5160            .cloned(),
5161    );
5162    headers.extend(added);
5163    Ok(Cow::Owned(headers))
5164}
5165
5166/// Resolves the proxy configuration into the state that a fetch reads.
5167///
5168/// The function resolves each form once. So a fetch reads no environment and
5169/// parses no URL. A proxy URL that the fetcher cannot connect through fails
5170/// the constructor, from the options and from the environment. A value read
5171/// under a meaning of this crate sends the request to a place that the caller
5172/// did not name.
5173fn resolve_proxy(proxy: &Proxy) -> Result<Proxies> {
5174    match proxy {
5175        Proxy::None => Ok(Proxies::default()),
5176        Proxy::Environment => resolve_variables(&environment()),
5177        Proxy::Variables(variables) => resolve_variables(variables),
5178        Proxy::Url(url) => {
5179            let endpoint = Arc::new(parse_proxy(url)?);
5180            Ok(Proxies {
5181                http: Some(endpoint.clone()),
5182                https: Some(endpoint),
5183                exempt_all: false,
5184                exempt: Vec::new(),
5185            })
5186        }
5187    }
5188}
5189
5190/// Returns the proxy variables of the process environment.
5191///
5192/// An empty value counts as unset. So the function leaves it out, and
5193/// [`variable`] has one rule to apply.
5194fn environment() -> Vec<(String, String)> {
5195    PROXY_VARIABLES
5196        .iter()
5197        .filter_map(|name| {
5198            let value = std::env::var(name).ok()?;
5199            (!value.is_empty()).then(|| ((*name).to_owned(), value))
5200        })
5201        .collect()
5202}
5203
5204/// Resolves the variable forms of [`Proxy`] into the state that a fetch reads.
5205fn resolve_variables(variables: &[(String, String)]) -> Result<Proxies> {
5206    let all = variable(variables, "all_proxy", Some("ALL_PROXY"));
5207    let http = variable(variables, "http_proxy", None);
5208    let https = variable(variables, "https_proxy", Some("HTTPS_PROXY"));
5209    // The loop parses each variable that holds a value. The choice of the
5210    // proxy for each scheme comes after the loop, from the parsed values. So
5211    // the fetcher refuses a proxy URL that it cannot connect through, also if
5212    // no fetch reads it. An example is `all_proxy` beside both
5213    // scheme-specific variables.
5214    //
5215    // The loop parses one URL for both schemes once, and holds it as one
5216    // endpoint. So the pool key of a proxy connection is the same, whichever
5217    // variable named it.
5218    //
5219    // The loop refuses a value with white space at its start or end before
5220    // the parse, because the parse trims it. The rule is the same: the loop
5221    // checks each variable that it reads, also if no fetch uses it.
5222    // The message names the variable, and leaves out the value, which can hold
5223    // a password.
5224    let mut endpoints: Vec<(&str, Arc<ProxyEndpoint>)> = Vec::new();
5225    for (name, url) in [all, http, https].into_iter().flatten() {
5226        if url.trim() != url {
5227            return Err(Error::Unsupported(format!(
5228                "the proxy variable {name} has white space at the start or the end of \
5229                 its value"
5230            )));
5231        }
5232        if !endpoints.iter().any(|(named, _)| *named == url) {
5233            endpoints.push((url, Arc::new(parse_proxy(url)?)));
5234        }
5235    }
5236    let parsed = |held: Option<(&str, &str)>| {
5237        held.and_then(|(_, url)| endpoints.iter().find(|(named, _)| *named == url))
5238            .map(|(_, endpoint)| endpoint.clone())
5239    };
5240    let (http, https) = (parsed(http.or(all)), parsed(https.or(all)));
5241    let mut exempt_all = false;
5242    let mut exempt = Vec::new();
5243    for entry in variable(variables, "no_proxy", Some("NO_PROXY"))
5244        .map(|(_, value)| value)
5245        .unwrap_or_default()
5246        .split(',')
5247        .map(str::trim)
5248        .filter(|entry| !entry.is_empty())
5249    {
5250        if entry == "*" {
5251            exempt_all = true;
5252            continue;
5253        }
5254        exempt.extend(parse_exemption(entry));
5255    }
5256    Ok(Proxies {
5257        http,
5258        https,
5259        exempt_all,
5260        exempt,
5261    })
5262}
5263
5264/// Returns the name and the value of one proxy variable.
5265///
5266/// The function reads the lower-case name first, then the upper-case name if
5267/// there is one. An empty value counts as unset. Of two entries of one name,
5268/// the function reads the first entry with a value.
5269fn variable<'a>(
5270    variables: &'a [(String, String)],
5271    lower: &str,
5272    upper: Option<&str>,
5273) -> Option<(&'a str, &'a str)> {
5274    let held = |name: &str| {
5275        variables
5276            .iter()
5277            .find(|(held, value)| held == name && !value.is_empty())
5278            .map(|(held, value)| (held.as_str(), value.as_str()))
5279    };
5280    held(lower).or_else(|| upper.and_then(held))
5281}
5282
5283/// Reads one `no_proxy` entry, or returns `None` if it names no host.
5284///
5285/// An IPv6 literal holds colons of its own. So the function reads a port from
5286/// the bracketed form and from an entry with one colon. An unbracketed entry
5287/// with more colons is an address, with no port.
5288///
5289/// A port text that is not a number from 0 to 65535 leaves the whole entry as
5290/// one host text. No origin host holds that text, so the entry exempts
5291/// nothing.
5292///
5293/// The function drops an entry with no host after it removes the leading `.`
5294/// and the port. `.` and `:8080` are the two forms of such an entry. An empty
5295/// host text is the suffix of each host, so it exempts every origin if it
5296/// stays.
5297fn parse_exemption(entry: &str) -> Option<Exemption> {
5298    let (host, port) = match entry
5299        .strip_prefix('[')
5300        .and_then(|rest| rest.split_once(']'))
5301    {
5302        Some((inside, rest)) => (inside, rest.strip_prefix(':')),
5303        None => match entry.split_once(':') {
5304            Some((host, port)) if !port.contains(':') => (host, Some(port)),
5305            _ => (entry, None),
5306        },
5307    };
5308    // One leading `.` states the suffix match that the comparison makes in
5309    // all cases. So the code removes it, and the two forms of one entry are
5310    // one entry. A second `.` is part of the host text of the entry, which no
5311    // origin host holds.
5312    let named = |host: &str| host.strip_prefix('.').unwrap_or(host).to_ascii_lowercase();
5313    let (host, port) = match port.map(str::parse::<u16>) {
5314        Some(Ok(port)) => (named(host), Some(port)),
5315        Some(Err(_)) => (named(entry), None),
5316        None => (named(host), None),
5317    };
5318    (!host.is_empty()).then_some(Exemption { host, port })
5319}
5320
5321/// Reads a proxy URL into the endpoint of a connection.
5322///
5323/// The request to a proxy names the origin. So the URL names an endpoint and
5324/// nothing else. A path other than `/`, a query, or a fragment states a value
5325/// that the request has no place for, and the function refuses it. The
5326/// scheme is `http`, the one scheme of a proxy connection in this crate.
5327///
5328/// Userinfo is the credential of the proxy. The function percent-decodes it
5329/// and sends it as `Proxy-Authorization: Basic`, as a proxy that works with
5330/// other clients expects. A userinfo holds a password, so each refusal names
5331/// the URL with the userinfo left out.
5332fn parse_proxy(url: &str) -> Result<ProxyEndpoint> {
5333    let refused = |what: &str| {
5334        Error::Unsupported(format!(
5335            "proxy url {}: {what}",
5336            without_userinfo(url.trim())
5337        ))
5338    };
5339    let url = url.trim();
5340    if !url
5341        .get(..PROXY_SCHEME.len())
5342        .is_some_and(|scheme| scheme.eq_ignore_ascii_case(PROXY_SCHEME))
5343    {
5344        return Err(refused("a proxy is reached over http://host[:port] alone"));
5345    }
5346    if url.contains('#') {
5347        return Err(refused("a proxy url carries no fragment"));
5348    }
5349    let uri = Uri::try_from(url).map_err(|e| refused(&format!("invalid url: {e}")))?;
5350    // A `/` or a `?` in the userinfo moves a part of the password into the
5351    // path or the query. So these refusals do not show the path or the query.
5352    if uri.query().is_some() {
5353        return Err(refused("a proxy url carries no query string"));
5354    }
5355    if !matches!(uri.path(), "" | "/") {
5356        return Err(refused("a proxy url carries no path"));
5357    }
5358    // `Uri::host` holds an IPv6 literal in brackets. The brackets belong to
5359    // the authority. A connect resolves the bracketed form to nothing.
5360    let literal = uri.host().ok_or_else(|| refused("the url has no host"))?;
5361    let authority = uri
5362        .authority()
5363        .expect("a url holding a host holds an authority")
5364        .as_str();
5365    let credential = match authority.rsplit_once('@') {
5366        Some((userinfo, _)) => Some(proxy_credential(userinfo).ok_or_else(|| {
5367            refused(
5368                "the userinfo is not a percent-encoded user name and password the proxy can be \
5369                 sent",
5370            )
5371        })?),
5372        None => None,
5373    };
5374    let host = literal
5375        .strip_prefix('[')
5376        .and_then(|inner| inner.strip_suffix(']'))
5377        .unwrap_or(literal)
5378        .to_ascii_lowercase();
5379    // `Uri` accepts an authority whose port it cannot read, and reports no
5380    // port for it. So the code reads the port text from the authority and
5381    // refuses it. The default port does not replace it.
5382    let port_text = authority
5383        .rsplit_once('@')
5384        .map_or(authority, |(_, host)| host)
5385        .strip_prefix(literal)
5386        .and_then(|rest| rest.strip_prefix(':'));
5387    let port = match (uri.port_u16(), port_text) {
5388        (Some(port), _) => port,
5389        (None, None) => 80,
5390        (None, Some(text)) => {
5391            return Err(refused(&format!(
5392                "the port {text:?} is not a number from 0 to 65535"
5393            )));
5394        }
5395    };
5396    let named = if port == 80 {
5397        format!("{PROXY_SCHEME}{literal}")
5398    } else {
5399        format!("{PROXY_SCHEME}{literal}:{port}")
5400    };
5401    Ok(ProxyEndpoint {
5402        endpoint: Origin {
5403            tls: false,
5404            host,
5405            port,
5406        },
5407        credential,
5408        named,
5409    })
5410}
5411
5412/// Returns the `Proxy-Authorization` value of the userinfo of one proxy URL.
5413///
5414/// The function percent-decodes the two fields, because a URL states a `:` or
5415/// an `@` of a credential in that encoding. `None` states that the userinfo
5416/// holds something else: an escape that is not two hexadecimal digits, or a
5417/// field whose bytes are not text.
5418fn proxy_credential(userinfo: &str) -> Option<HeaderValue> {
5419    let (user, password) = userinfo.split_once(':').unwrap_or((userinfo, ""));
5420    let field = |text: &str| String::from_utf8(percent_decode(text)?).ok();
5421    basic_auth_value(&BasicAuth {
5422        user: field(user)?,
5423        password: field(password)?,
5424    })
5425    .ok()
5426}
5427
5428/// Percent-decodes one field of the userinfo of a proxy URL.
5429///
5430/// `%` starts an escape of exactly two hexadecimal digits. `None` states that
5431/// the field holds a different escape, which the fetcher refuses. The bytes as
5432/// written can give the proxy a credential other than the one that the caller
5433/// meant. The 407 answer to that credential names nothing.
5434fn percent_decode(field: &str) -> Option<Vec<u8>> {
5435    let bytes = field.as_bytes();
5436    let mut decoded = Vec::with_capacity(bytes.len());
5437    let mut at = 0;
5438    while at < bytes.len() {
5439        if bytes[at] != b'%' {
5440            decoded.push(bytes[at]);
5441            at += 1;
5442            continue;
5443        }
5444        let escape = bytes.get(at + 1..at + 3)?;
5445        if !escape.iter().all(u8::is_ascii_hexdigit) {
5446            return None;
5447        }
5448        let text = std::str::from_utf8(escape).ok()?;
5449        decoded.push(u8::from_str_radix(text, 16).ok()?);
5450        at += 3;
5451    }
5452    Some(decoded)
5453}
5454
5455/// Returns the `host:port` that names the target of a `CONNECT`.
5456///
5457/// The port is always written, whatever the default of the scheme. The proxy
5458/// opens a TCP connection, which names a port and reads no scheme. An IPv6
5459/// literal keeps the brackets that separate the address from the port.
5460fn connect_authority(origin: &Origin) -> String {
5461    if origin.host.contains(':') {
5462        format!("[{}]:{}", origin.host, origin.port)
5463    } else {
5464        format!("{}:{}", origin.host, origin.port)
5465    }
5466}
5467
5468/// Returns the `Authorization` value of basic credentials, marked sensitive.
5469fn basic_auth_value(auth: &BasicAuth) -> Result<HeaderValue> {
5470    let encoded =
5471        ostrya_core::base64::encode(format!("{}:{}", auth.user, auth.password).as_bytes());
5472    let mut value = HeaderValue::try_from(format!("Basic {encoded}"))
5473        .map_err(|_| Error::Fetch("invalid basic-auth credentials".into()))?;
5474    value.set_sensitive(true);
5475    Ok(value)
5476}
5477
5478/// Returns the `Authorization` value of a bearer token, marked sensitive.
5479///
5480/// The fetcher sends the token as written, so it must hold the token68 syntax
5481/// of the header. The token is a secret, so a refusal names no part of it.
5482fn bearer_value(token: &BearerToken) -> Result<HeaderValue> {
5483    let refused = || {
5484        Error::Fetch(
5485            "the bearer token is not token68: it holds letters, digits, -, ., _, ~, +, or /, \
5486             then any number of ="
5487                .into(),
5488        )
5489    };
5490    if !is_token68(&token.token) {
5491        return Err(refused());
5492    }
5493    let mut value =
5494        HeaderValue::try_from(format!("Bearer {}", token.token)).map_err(|_| refused())?;
5495    value.set_sensitive(true);
5496    Ok(value)
5497}
5498
5499/// Returns `true` if `token` holds the token68 syntax.
5500///
5501/// The syntax is one or more ASCII letters, digits, `-`, `.`, `_`, `~`, `+`,
5502/// or `/`, then any number of `=`.
5503fn is_token68(token: &str) -> bool {
5504    let body = token.trim_end_matches('=');
5505    !body.is_empty()
5506        && body
5507            .bytes()
5508            .all(|byte| byte.is_ascii_alphanumeric() || b"-._~+/".contains(&byte))
5509}
5510
5511/// Returns the origin of one absolute URL, and the authority of that origin.
5512///
5513/// The function checks the scheme before it parses the URL. So a URL that the
5514/// fetcher cannot serve gets a message that names the scheme. An example is a
5515/// `file://` URL, which is not a well-formed HTTP URL.
5516///
5517/// The function refuses userinfo. Credentials that never reach the wire get a
5518/// 401 answer, which points at nothing. `credentials` names the field that
5519/// carries them.
5520///
5521/// A userinfo holds a password. So the refusal names the scheme and the host.
5522/// A message about a URL before the parse reaches its authority names the URL
5523/// with the userinfo left out.
5524fn parse_authority(url: &str, credentials: &str) -> Result<(Uri, Origin, String)> {
5525    let scheme = url
5526        .split_once("://")
5527        .map(|(scheme, _)| scheme)
5528        .ok_or_else(|| {
5529            Error::Fetch(format!(
5530                "url {} is not an absolute http or https url",
5531                without_userinfo(url)
5532            ))
5533        })?;
5534    let tls = match scheme {
5535        _ if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
5536        _ if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
5537        other => {
5538            return Err(Error::Unsupported(format!(
5539                "fetch url scheme {other}: only http and https are fetched"
5540            )));
5541        }
5542    };
5543    let scheme = if tls { "https" } else { "http" };
5544    let uri = Uri::try_from(url)
5545        .map_err(|e| Error::Fetch(format!("invalid url {}: {e}", without_userinfo(url))))?;
5546    // `Uri::host` puts an IPv6 literal in brackets. The brackets belong to the
5547    // authority, and the `Host` header and the absolute URL carry them. A
5548    // connect resolves the bracketed form to nothing, and a TLS server name
5549    // cannot come from it.
5550    let literal = uri
5551        .host()
5552        .ok_or_else(|| Error::Fetch(format!("url {} has no host", without_userinfo(url))))?;
5553    if uri
5554        .authority()
5555        .is_some_and(|authority| authority.as_str().contains('@'))
5556    {
5557        return Err(Error::Fetch(format!(
5558            "the {scheme} url for {literal} carries userinfo, which the fetcher does not send: \
5559             pass credentials as {credentials}"
5560        )));
5561    }
5562    // A host is one origin in each case of its letters. So the pool key holds
5563    // it in lower case. A `Location` header repeats the case that the origin
5564    // server wrote. With two cases of one host in the pool, the fetcher opens
5565    // two connections and two HTTP/2 sessions to it.
5566    let host = literal
5567        .strip_prefix('[')
5568        .and_then(|inner| inner.strip_suffix(']'))
5569        .unwrap_or(literal)
5570        .to_ascii_lowercase();
5571    // `Uri` accepts an authority whose port it cannot read, and reports no
5572    // port for it. Examples are `h:99999`, `h:`, and `h:abc`. A fallback to the
5573    // default of the scheme serves the request from a port that the caller did
5574    // not name. The rebuilt authority also drops the port. So the code reads
5575    // the port text from the authority and refuses it.
5576    //
5577    // `Uri` also reads the port with the integer parse of `std`, which takes a
5578    // leading `+`. A port is ASCII digits alone, so the code refuses a port
5579    // text with any other byte. Leading zeros are digits, and `080` names the
5580    // port 80.
5581    let port_text = uri
5582        .authority()
5583        .and_then(|authority| authority.as_str().strip_prefix(literal))
5584        .and_then(|rest| rest.strip_prefix(':'));
5585    let default_port = if tls { 443 } else { 80 };
5586    let digits = port_text.is_none_or(|text| text.bytes().all(|b| b.is_ascii_digit()));
5587    let port = match (uri.port_u16().filter(|_| digits), port_text) {
5588        (Some(port), _) => port,
5589        (None, None) => default_port,
5590        (None, Some(text)) => {
5591            // A password with a `?` or a `#` ends the authority before the
5592            // `@`. So the userinfo check passes, and a URL with userinfo can
5593            // get this message.
5594            return Err(Error::Fetch(format!(
5595                "url {} names the port {text:?}, which is not a number from 0 to 65535",
5596                without_userinfo(url)
5597            )));
5598        }
5599    };
5600    let authority = if port == default_port {
5601        literal.to_string()
5602    } else {
5603        format!("{literal}:{port}")
5604    };
5605    Ok((uri, Origin { tls, host, port }, authority))
5606}
5607
5608/// Returns the form of a URL for a message, before the parse reaches the
5609/// authority and refuses the userinfo.
5610///
5611/// Userinfo holds a password, so the function leaves out the part of the
5612/// authority before the `@`. The password arrives as the caller wrote it. It
5613/// can hold a `/`, a `?`, or a `#`, which are the characters that end an
5614/// authority. So the end of the authority is known only after the userinfo is
5615/// found.
5616///
5617/// The function reads an `@` at any position after the scheme as the end of a
5618/// userinfo. It leaves out all text up to the last `@`, so no password of any
5619/// form reaches the message. When the text has no valid scheme before the
5620/// first `://`, the userinfo starts at the start of the text.
5621///
5622/// If a URL has an `@` in its path and no userinfo, the message loses its
5623/// host. A redaction that reads no well-formed authority has this cost.
5624fn without_userinfo(url: &str) -> Cow<'_, str> {
5625    let start = scheme_len(url);
5626    match url[start..].rfind('@') {
5627        Some(at) => Cow::Owned(format!("{}{}", &url[..start], &url[start + at + 1..])),
5628        None => Cow::Borrowed(url),
5629    }
5630}
5631
5632/// Returns the length of the `<scheme>://` prefix of `url`, or 0.
5633///
5634/// The prefix counts only when the text before the first `://` is a valid
5635/// scheme: an ASCII letter, then ASCII letters, digits, `+`, `-`, or `.`.
5636fn scheme_len(url: &str) -> usize {
5637    let Some(end) = url.find("://") else {
5638        return 0;
5639    };
5640    let mut chars = url[..end].chars();
5641    let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
5642        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
5643    if valid { end + 3 } else { 0 }
5644}
5645
5646/// Returns the `Host` header value of one authority.
5647fn host_header(url: &str, authority: &str) -> Result<HeaderValue> {
5648    HeaderValue::try_from(authority).map_err(|_| {
5649        Error::Fetch(format!(
5650            "url {} has an unusable host",
5651            without_userinfo(url)
5652        ))
5653    })
5654}
5655
5656/// Checks that `url` is a base URL that a fetcher takes as a mirror.
5657///
5658/// The check opens no connection and reads no file. It refuses these parts:
5659///
5660/// - a scheme other than `http` and `https`
5661/// - userinfo
5662/// - a query string
5663/// - a fragment
5664/// - an empty host
5665/// - a port that is not a number from 0 to 65535 in ASCII digits.
5666///
5667/// A port with leading zeros is the number that its digits give.
5668///
5669/// The check refuses an `@` at any position, also in the path and in the
5670/// query. The authority of a URL ends at the first `/`, `?`, or `#`. So a
5671/// password with one of those ends the authority before the `@`. The rest of
5672/// the userinfo then reads as a path or a query.
5673///
5674/// No refusal names the part of the URL before the last `@`.
5675///
5676/// # Errors
5677///
5678/// - [`Error::Fetch`] if `url` holds a `#` or an `@`.
5679/// - [`Error::Unsupported`] if the scheme is neither `http` nor `https`.
5680/// - [`Error::Fetch`] if `url` is not a valid absolute URL, or has no host.
5681/// - [`Error::Fetch`] if `url` holds a query string, or names a port that is
5682///   not valid.
5683/// - [`Error::Fetch`] if a `Host` header cannot hold the authority.
5684pub fn check_base_url(url: &str) -> Result<()> {
5685    if url.contains('#') {
5686        return Err(Error::Fetch(format!(
5687            "url {} carries a fragment, which no request sends",
5688            without_userinfo(url)
5689        )));
5690    }
5691    if url.contains('@') {
5692        return Err(Error::Fetch(format!(
5693            "url {} holds an '@', which can mark userinfo: a base url carries no userinfo, so \
5694             pass the credential in the options and not in the url",
5695            without_userinfo(url)
5696        )));
5697    }
5698    let mirror = parse_mirror(url)?;
5699    if mirror.origin.host.is_empty() {
5700        return Err(Error::Fetch(format!(
5701            "url {} has no host",
5702            without_userinfo(url)
5703        )));
5704    }
5705    Ok(())
5706}
5707
5708/// Parses one base URL into a [`Mirror`].
5709fn parse_mirror(url: &str) -> Result<Mirror> {
5710    let (uri, origin, authority) = parse_authority(url, "FetcherOptions::basic_auth")?;
5711    // A request target is the base path of the mirror with the object path
5712    // added. So a query string of the base URL drops out with no message. The
5713    // code refuses it. A presigned URL that lost its signature gets a 403
5714    // answer, which does not point at the URL that caused it.
5715    //
5716    // A password with a `?` ends the authority there, and the rest of the
5717    // userinfo reads as the query. So the message names the URL with the
5718    // userinfo left out, and does not quote the query.
5719    if uri.query().is_some() {
5720        return Err(Error::Fetch(format!(
5721            "mirror url {} carries a query string, which the fetcher does not send",
5722            without_userinfo(url)
5723        )));
5724    }
5725    let scheme = if origin.tls { "https" } else { "http" };
5726    Ok(Mirror {
5727        authority: host_header(url, &authority)?,
5728        prefix: format!("{scheme}://{authority}"),
5729        base: uri.path().trim_end_matches('/').to_string(),
5730        origin,
5731    })
5732}
5733
5734/// Parses the absolute URL of a request into its [`Destination`].
5735///
5736/// The query string is part of the name of the request, so it reaches the
5737/// wire as written. The function refuses a fragment. A fragment is never sent,
5738/// so a URL with one asks for a resource other than the resource that the
5739/// caller named.
5740fn parse_url(url: &str) -> Result<Destination> {
5741    if url.contains('#') {
5742        return Err(Error::Fetch(format!(
5743            "fetch url {} carries a fragment, which no request sends",
5744            without_userinfo(url)
5745        )));
5746    }
5747    let (uri, origin, authority) = parse_authority(url, "FetchRequest::basic_auth")?;
5748    let scheme = if origin.tls { "https" } else { "http" };
5749    let path_and_query = uri.path_and_query().map_or("/", |pq| pq.as_str());
5750    // The code builds the one string of the destination from the parts of the
5751    // parse. The whole string is the absolute URL. Its tail from the prefix
5752    // length is the origin-form target.
5753    let mut text =
5754        String::with_capacity(scheme.len() + 3 + authority.len() + 1 + path_and_query.len());
5755    text.push_str(scheme);
5756    text.push_str("://");
5757    text.push_str(&authority);
5758    let path_at = text.len();
5759    if !path_and_query.starts_with('/') {
5760        text.push('/');
5761    }
5762    text.push_str(path_and_query);
5763    Ok(Destination {
5764        authority: host_header(url, &authority)?,
5765        url: text,
5766        path_at,
5767        origin,
5768    })
5769}
5770
5771/// Returns `true` if `response` closes its HTTP/1.1 connection when it ends.
5772///
5773/// This is an HTTP/1.0 response, or a response whose `Connection` header holds
5774/// `close`.
5775fn closes(response: &Response<Incoming>) -> bool {
5776    response.version() != Version::HTTP_11
5777        || response
5778            .headers()
5779            .get_all(hyper::header::CONNECTION)
5780            .iter()
5781            .filter_map(|value| value.to_str().ok())
5782            .flat_map(|value| value.split(','))
5783            .any(|token| token.trim().eq_ignore_ascii_case("close"))
5784}
5785
5786/// Returns the `Content-Length` that a response declared, if it is usable.
5787fn content_length(headers: &hyper::HeaderMap) -> Option<u64> {
5788    headers
5789        .get(hyper::header::CONTENT_LENGTH)?
5790        .to_str()
5791        .ok()?
5792        .parse()
5793        .ok()
5794}
5795
5796/// Returns the coding that a response declared, if the body needs a decode.
5797///
5798/// `Content-Encoding` codes the content, and `Transfer-Encoding` codes the
5799/// message that carries the content. A body under either holds bytes other
5800/// than the bytes that the remote stores, so the function reads both headers.
5801/// If a response declares both, the function returns its content coding.
5802fn declared_coding(headers: &hyper::HeaderMap) -> Option<String> {
5803    coding(headers, hyper::header::CONTENT_ENCODING, &[IDENTITY]).or_else(|| {
5804        coding(
5805            headers,
5806            hyper::header::TRANSFER_ENCODING,
5807            &[IDENTITY, CHUNKED],
5808        )
5809    })
5810}
5811
5812/// Returns the coding that a response declared under `name`, if it is not in
5813/// `undone`.
5814///
5815/// `undone` holds the codings that leave the body as the remote wrote it. A
5816/// value is a comma-separated list of codings, and several headers of one name
5817/// state one list together. So the function reads each token of each value.
5818///
5819/// A value whose tokens are all empty names no coding. The function adds it
5820/// to no result, so a stray separator reaches no message. The result is the
5821/// text of the response, in its order, so the refusal names the value of the
5822/// server. A response with nothing to refuse builds no string.
5823fn coding(headers: &hyper::HeaderMap, name: HeaderName, undone: &[&str]) -> Option<String> {
5824    let declared = || {
5825        headers
5826            .get_all(&name)
5827            .iter()
5828            .map(|value| String::from_utf8_lossy(value.as_bytes()))
5829            .filter(|value| value.split(',').any(|token| !token.trim().is_empty()))
5830    };
5831    if !declared().any(|value| value.split(',').any(|token| names_a_coding(token, undone))) {
5832        return None;
5833    }
5834    Some(declared().collect::<Vec<_>>().join(", "))
5835}
5836
5837/// Returns `true` if one token of a coding list names a coding that is not in
5838/// `undone`.
5839///
5840/// The comparison ignores case and the space around the token. An empty token
5841/// names nothing.
5842fn names_a_coding(token: &str, undone: &[&str]) -> bool {
5843    let token = token.trim();
5844    !token.is_empty() && !undone.iter().any(|name| token.eq_ignore_ascii_case(name))
5845}
5846
5847/// Reads the cache validators of a response.
5848fn read_validators(headers: &hyper::HeaderMap) -> Validators {
5849    let text = |name: HeaderName| {
5850        headers
5851            .get(name)
5852            .and_then(|v| v.to_str().ok())
5853            .map(str::to_string)
5854    };
5855    Validators {
5856        etag: text(hyper::header::ETAG),
5857        last_modified: text(hyper::header::LAST_MODIFIED),
5858    }
5859}
5860
5861/// Returns `true` if a response with this status sends the attempt to another
5862/// URL.
5863fn is_redirect(status: StatusCode) -> bool {
5864    REDIRECTS.contains(&status)
5865}
5866
5867/// Returns the URL of a `Location` header, resolved against `from`, the URL of
5868/// the response that carried it.
5869///
5870/// A `Location` can be an absolute URL, a URL relative to the URL of the
5871/// response, or a scheme-relative URL. The resolution is the one that the URL
5872/// specification states. The function drops a fragment of the result. A
5873/// fragment names a part of a representation and reaches no request, and the
5874/// HTTP specification tells a redirect to drop it.
5875///
5876/// The resolution normalizes its result. A [`Target::Url`] reaches the wire as
5877/// the caller wrote it. The changes are:
5878///
5879/// - it resolves dot segments: `/deep/../root` becomes `/root`, and `/./p`
5880///   becomes `/p`
5881/// - it reads a backslash as a path separator: `/a\b` becomes `/a/b`
5882/// - it removes tabs and newlines
5883/// - it percent-encodes a character that a path or a query cannot carry:
5884///   `?q='x'` becomes `?q=%27x%27`
5885/// - it puts an IPv4 or an IPv6 host in canonical form: `2130706433` and
5886///   `0177.0.0.1` both become `127.0.0.1`.
5887///
5888/// If the signature of a signed request target covers one of those
5889/// characters, the target reaches the server in a new encoding. The server
5890/// reads it as a different target, and answers 403.
5891///
5892/// `None` states that the header holds no URL for a request. This covers a
5893/// value that is not text, an empty value, and a value that the resolution
5894/// cannot read. A value that resolves to the URL of the response itself, a
5895/// fragment alone such as `#frag`, is a hop of its own. It spends one of the
5896/// hops of the attempt.
5897fn resolve_location(from: &str, location: &HeaderValue) -> Option<String> {
5898    let location = location.to_str().ok()?;
5899    // An empty value resolves to the URL of the response that carried it. The
5900    // attempt then follows the hop that it just made, so the code returns
5901    // `None` for it.
5902    if location.is_empty() {
5903        return None;
5904    }
5905    let mut resolved = url::Url::parse(from).ok()?.join(location).ok()?;
5906    resolved.set_fragment(None);
5907    Some(resolved.into())
5908}
5909
5910/// Reads the URL that a redirect named into the destination of the next hop.
5911///
5912/// The function refuses two hops. Both refusals name the URL that redirected
5913/// and the URL that it named:
5914///
5915/// - a scheme other than `http` or `https`, under which the fetcher serves
5916///   nothing
5917/// - a hop from `https` to `http`, which puts a request that the caller made
5918///   over TLS on the wire in the clear.
5919///
5920/// The function follows a hop from `http` to `https`.
5921///
5922/// The input is the resolved URL, normalized by [`resolve_location`]. The
5923/// parse reads it as it reads a [`Target::Url`]. So that parse refuses
5924/// userinfo and a port that the URL parser cannot read, with its own message.
5925/// A userinfo holds a password, so the two refusals of this function name the
5926/// URL with the userinfo left out.
5927fn redirect_destination(from: &Destination, to: &str) -> Result<Destination> {
5928    let refused = |what: &str| {
5929        Error::Fetch(format!(
5930            "{} redirects to {}, {what}",
5931            from.url(),
5932            without_userinfo(to)
5933        ))
5934    };
5935    let tls = match to.split_once("://").map(|(scheme, _)| scheme) {
5936        Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
5937        Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
5938        _ => return Err(refused("which is not an absolute http or https url")),
5939    };
5940    if from.origin.tls && !tls {
5941        return Err(refused(
5942            "which is cleartext: a request made over tls is not followed onto http",
5943        ));
5944    }
5945    parse_url(to)
5946}
5947
5948/// Returns the error of a fetch of a TLS origin on a fetcher that holds no
5949/// trust anchors.
5950///
5951/// The route or a redirect hop can name the origin.
5952fn no_trust_anchors(origin: &str) -> Error {
5953    Error::Fetch(format!(
5954        "the certificate of the tls origin {origin} has nothing to verify against: the \
5955         fetcher holds no trust anchors, so set TlsOptions::roots"
5956    ))
5957}
5958
5959/// Classifies an unsuccessful status as retryable or definitive.
5960fn classify(status: StatusCode, url: &str) -> Failure {
5961    let error = Error::HttpStatus {
5962        status: status.as_u16(),
5963        url: url.to_string(),
5964    };
5965    if status.is_server_error()
5966        || status == StatusCode::REQUEST_TIMEOUT
5967        || status == StatusCode::TOO_MANY_REQUESTS
5968    {
5969        Failure::Retry(error)
5970    } else {
5971        Failure::Fatal(error)
5972    }
5973}
5974
5975/// Returns the error of a transport failure against one URL.
5976fn transport(url: &str, error: hyper::Error) -> Error {
5977    Error::Fetch(format!("{url}: {error}"))
5978}
5979
5980/// Returns the error of a response that did not deliver its head within the
5981/// progress window.
5982fn stalled(url: &str, limit: Duration) -> Error {
5983    Error::Fetch(format!("{url}: no response after {limit:?}"))
5984}
5985
5986/// Returns the error of a connect that did not complete within `limit`.
5987///
5988/// The window covers the connect to the endpoint of the hop. So the error of
5989/// a proxied hop names the proxy. The fetcher reaches the origin over that
5990/// connection, and nothing contacts the origin before the connection is open.
5991fn connect_timed_out(origin: &Origin, via: Via<'_>, limit: Duration) -> Error {
5992    Error::Fetch(match via {
5993        Via::Direct => format!(
5994            "connect to {}:{} timed out after {limit:?}",
5995            origin.host, origin.port
5996        ),
5997        Via::Absolute(proxy) | Via::Tunnel(proxy) => format!(
5998            "connect to the proxy {} timed out after {limit:?}",
5999            proxy.named
6000        ),
6001    })
6002}
6003
6004/// Returns the error of an upload whose body failed before the hand-over. The
6005/// request was never sent.
6006fn not_sent(url: &str, reason: String) -> Error {
6007    Error::Fetch(format!("upload to {url} not sent: {reason}"))
6008}
6009
6010/// Returns the failure of an upload that failed after hyper took its request.
6011fn interrupted(url: &str, message: String) -> UploadFailure {
6012    UploadFailure::Sent {
6013        url: url.to_string(),
6014        message,
6015    }
6016}
6017
6018/// Returns the failure of an upload that does not deliver its response, for
6019/// `cause`.
6020///
6021/// hyper took the request, so the upload is interrupted. The message names
6022/// the cause.
6023fn undelivered(url: &str, cause: Error) -> UploadFailure {
6024    interrupted(url, cause.to_string())
6025}
6026
6027/// Returns the message of an error and of its cause.
6028///
6029/// The message of a hyper error is generic, and its cause names what the
6030/// connection did.
6031fn with_cause(error: &dyn std::error::Error) -> String {
6032    match error.source() {
6033        Some(cause) => format!("{error}: {cause}"),
6034        None => error.to_string(),
6035    }
6036}
6037
6038/// Returns the error of a response that did not deliver its head within the
6039/// time of the low-speed rule.
6040fn too_slow(url: &str, rule: LowSpeed) -> Error {
6041    let LowSpeed { limit, time } = rule;
6042    Error::Fetch(format!(
6043        "{url}: transfer below {limit} bytes per second for {time:?}"
6044    ))
6045}
6046
6047/// Runs `future` under a deadline, and returns `None` if `limit` expires
6048/// first.
6049///
6050/// The function drops the future on expiry, which cancels its work.
6051async fn within<F: Future>(limit: Duration, future: F) -> Option<F::Output> {
6052    // The future is pinned before the race. So the block that awaits it holds
6053    // a pointer, and no second copy of it. A caller that fetches many objects
6054    // holds one such future for each object in flight, and its size is a cost
6055    // on the stack.
6056    let mut future = core::pin::pin!(future);
6057    futures_lite::future::or(async { Some(future.as_mut().await) }, async {
6058        rt::Timer::after(limit).await;
6059        None
6060    })
6061    .await
6062}
6063
6064/// Runs `future` under a deadline of `limit` that applies while `handed` is
6065/// `false`, and returns `None` if the deadline expires first.
6066///
6067/// The deadline runs from the call. An upload sets `handed` when hyper takes
6068/// the request. The request then has deadlines of its own, and the function
6069/// drops the timer. A request that comes back unsent clears `handed`, and the
6070/// function arms the timer again for the rest of the deadline.
6071async fn before_hand_over<F: Future>(
6072    limit: Duration,
6073    handed: &AtomicBool,
6074    future: F,
6075) -> Option<F::Output> {
6076    let mut future = core::pin::pin!(future);
6077    let end = Instant::now().checked_add(limit);
6078    let mut deadline: Option<rt::Deadline> = None;
6079    std::future::poll_fn(|cx| {
6080        if let Poll::Ready(output) = future.as_mut().poll(cx) {
6081            return Poll::Ready(Some(output));
6082        }
6083        if handed.load(Ordering::Relaxed) {
6084            deadline = None;
6085            return Poll::Pending;
6086        }
6087        // An end past the range of the clock is never reached. A timer of the
6088        // whole limit stands for it.
6089        let deadline = deadline.get_or_insert_with(|| {
6090            rt::Deadline::new(
6091                end.map_or(limit, |end| end.saturating_duration_since(Instant::now())),
6092            )
6093        });
6094        deadline.poll_expired(cx).map(|()| None)
6095    })
6096    .await
6097}
6098
6099/// Waits for the answer to a request that hyper took.
6100///
6101/// While a streamed body streams, nothing bounds the wait here, because the
6102/// stall window of the writer bounds the body. A body given whole has no
6103/// writer, so its stall window runs here. A frame that hyper does not take
6104/// within the window fails the body and ends the wait.
6105///
6106/// A body that fails ends the wait at once, also if hyper does not poll it
6107/// again. The window for the response head starts when hyper takes the end of
6108/// the body.
6109async fn answer<F: Future>(send: F, exchange: &Exchange, window: Duration) -> Answer<F::Output> {
6110    let mut send = core::pin::pin!(send);
6111    let mut head: Option<rt::Deadline> = None;
6112    let mut stall: Option<rt::Deadline> = None;
6113    std::future::poll_fn(|cx| {
6114        if let Poll::Ready(output) = send.as_mut().poll(cx) {
6115            return Poll::Ready(Answer::Sent(output));
6116        }
6117        while head.is_none() {
6118            match exchange.watch(cx) {
6119                Watch::Streaming(None) => return Poll::Pending,
6120                Watch::Streaming(Some(end)) => {
6121                    if poll_until(&mut stall, cx, end).is_pending() {
6122                        return Poll::Pending;
6123                    }
6124                    if let Ok(reason) = exchange.check_stall() {
6125                        return Poll::Ready(Answer::Aborted(reason));
6126                    }
6127                }
6128                Watch::Aborted(reason) => return Poll::Ready(Answer::Aborted(reason)),
6129                Watch::Ended => {
6130                    stall = None;
6131                    head = Some(rt::Deadline::new(window));
6132                }
6133            }
6134        }
6135        head.as_mut()
6136            .expect("the head window runs once the body has ended")
6137            .poll_expired(cx)
6138            .map(|()| Answer::Silent(window))
6139    })
6140    .await
6141}
6142
6143/// Returns the delay before retry round `round`: 250 ms, doubled for each
6144/// round, up to 2 seconds.
6145fn backoff(round: u32) -> Duration {
6146    let ms = 250u64 << (round - 1).min(3);
6147    Duration::from_millis(ms)
6148}
6149
6150// The fetcher, its bodies, and the parts of an upload move freely across tasks
6151// and threads.
6152const _: fn() = || {
6153    fn assert_send_sync<T: Send + Sync>() {}
6154    assert_send_sync::<Fetcher>();
6155    assert_send_sync::<Body>();
6156    assert_send_sync::<Fetched>();
6157    assert_send_sync::<BearerToken>();
6158    assert_send_sync::<UploadBody>();
6159    assert_send_sync::<UploadWriter>();
6160    assert_send_sync::<UploadRequest<'static>>();
6161    assert_send_sync::<Uploaded>();
6162};
6163
6164#[cfg(test)]
6165mod tests {
6166    use super::*;
6167
6168    /// The connection window holds one stream window for each request that
6169    /// the fetcher admits, and stops at the ceiling of the protocol.
6170    #[test]
6171    fn the_connection_window_covers_every_admitted_stream() {
6172        assert_eq!(h2_connection_window(1), H2_STREAM_WINDOW);
6173        assert_eq!(h2_connection_window(8), 8 * H2_STREAM_WINDOW);
6174        assert_eq!(h2_connection_window(usize::MAX), H2_MAX_WINDOW);
6175    }
6176
6177    #[test]
6178    fn mirror_urls_join_base_and_path() {
6179        let mirror = parse_mirror("https://example.com/repo/").unwrap();
6180        assert_eq!(
6181            mirror.destination("objects/ab/cd.filez", None).url(),
6182            "https://example.com/repo/objects/ab/cd.filez"
6183        );
6184        assert_eq!(mirror.origin.port, 443);
6185        assert!(mirror.origin.tls);
6186
6187        let root = parse_mirror("http://example.com").unwrap();
6188        assert_eq!(
6189            root.destination("summary", None).url(),
6190            "http://example.com/summary"
6191        );
6192        assert_eq!(root.origin.port, 80);
6193        assert!(!root.origin.tls);
6194
6195        // A non-default port stays in the URL and in the host header. A leading
6196        // slash on the path is not doubled.
6197        let ported = parse_mirror("http://127.0.0.1:8080/r").unwrap();
6198        let config = ported.destination("/config", None);
6199        assert_eq!(config.url(), "http://127.0.0.1:8080/r/config");
6200        assert_eq!(config.target(), "/r/config");
6201        assert_eq!(ported.authority, "127.0.0.1:8080");
6202        assert_eq!(root.authority, "example.com");
6203    }
6204
6205    /// A query string goes after the request path, as written, in the URL
6206    /// and in the origin-form target.
6207    #[test]
6208    fn mirror_urls_join_base_path_and_query() {
6209        let mirror = parse_mirror("http://127.0.0.1:8080/base/").unwrap();
6210        let destination = mirror.destination("_ostrya/refs/v1", Some("pattern=a%2Fb&pattern=c"));
6211        assert_eq!(
6212            destination.url(),
6213            "http://127.0.0.1:8080/base/_ostrya/refs/v1?pattern=a%2Fb&pattern=c"
6214        );
6215        assert_eq!(
6216            destination.target(),
6217            "/base/_ostrya/refs/v1?pattern=a%2Fb&pattern=c"
6218        );
6219        // An empty query keeps its `?`.
6220        let root = parse_mirror("https://example.com").unwrap();
6221        assert_eq!(
6222            root.destination("/p", Some("")).url(),
6223            "https://example.com/p?"
6224        );
6225    }
6226
6227    /// An IPv6 literal has brackets in the authority, and has none where the
6228    /// address itself is used. The brackets reach neither the connect nor the
6229    /// TLS server name, and both fail on them.
6230    #[test]
6231    fn an_ipv6_literal_keeps_its_brackets_only_in_the_authority() {
6232        let ported = parse_mirror("http://[::1]:8080/r").unwrap();
6233        assert_eq!(ported.origin.host, "::1");
6234        assert_eq!(ported.origin.port, 8080);
6235        assert_eq!(ported.authority, "[::1]:8080");
6236        assert_eq!(
6237            ported.destination("summary", None).url(),
6238            "http://[::1]:8080/r/summary"
6239        );
6240
6241        let tls = parse_mirror("https://[2001:db8::1]/repo").unwrap();
6242        assert_eq!(tls.origin.host, "2001:db8::1");
6243        assert_eq!(tls.origin.port, 443);
6244        assert_eq!(tls.authority, "[2001:db8::1]");
6245        assert_eq!(
6246            tls.destination("summary", None).url(),
6247            "https://[2001:db8::1]/repo/summary"
6248        );
6249        // The server name the TLS handshake is opened with comes from the same
6250        // field, and rejects the bracketed form.
6251        rustls::pki_types::ServerName::try_from(tls.origin.host.clone()).unwrap();
6252    }
6253
6254    #[test]
6255    fn mirror_urls_are_validated() {
6256        let err = parse_mirror("file:///srv/repo").unwrap_err();
6257        assert!(matches!(err, Error::Unsupported(_)), "{err}");
6258        let err = parse_mirror("/srv/repo").unwrap_err();
6259        assert!(err.to_string().contains("not an absolute"), "{err}");
6260        let err = parse_mirror("http://").unwrap_err();
6261        assert!(err.to_string().contains("invalid url"), "{err}");
6262
6263        // Neither a query nor userinfo reaches the wire. So the parse refuses
6264        // a URL with one, and does not serve it with the part missing.
6265        let err = parse_mirror("https://host/repo?X-Amz-Signature=deadbeef").unwrap_err();
6266        assert!(err.to_string().contains("query string"), "{err}");
6267        let err = parse_mirror("https://user:pass@host/repo").unwrap_err();
6268        assert!(err.to_string().contains("userinfo"), "{err}");
6269        // A bare user with no password is userinfo too.
6270        let err = parse_mirror("http://user@host/repo").unwrap_err();
6271        assert!(err.to_string().contains("userinfo"), "{err}");
6272    }
6273
6274    /// A base URL check takes each URL a mirror takes, and refuses a
6275    /// fragment and an empty host as well. A refusal holds no password.
6276    #[test]
6277    fn a_base_url_check_refuses_what_a_mirror_cannot_carry() {
6278        for url in [
6279            "http://host",
6280            "https://host/repo/",
6281            "http://127.0.0.1:8080/r",
6282            "https://[::1]:8443/",
6283            "HTTPS://host/repo",
6284        ] {
6285            check_base_url(url).unwrap();
6286        }
6287        let refused = |url: &str, part: &str| {
6288            let err = check_base_url(url).unwrap_err();
6289            let text = err.to_string();
6290            assert!(text.contains(part), "{url}: {text}");
6291            assert!(!text.contains("secret"), "{url}: {text}");
6292        };
6293        refused("https://user:secret@host/repo", "userinfo");
6294        refused("https://host/repo?q=1", "query string");
6295        refused("https://host/repo#part", "fragment");
6296        refused("https://u:secret@host/repo#part", "fragment");
6297        refused("http://", "invalid url");
6298        refused("http:///repo", "invalid url");
6299        refused("http://:80/repo", "has no host");
6300        refused("http://host:99999/repo", "not a number");
6301        refused("http://host:x/repo", "not a number");
6302        refused("ftp://host/repo", "scheme ftp");
6303        refused("host/repo", "not an absolute");
6304        // A password that holds a `/` or a `?` ends the authority before the
6305        // `@`. So the rest of the userinfo reads as the path or the query.
6306        refused("https://user:443/pw-secret@host/repo", "userinfo");
6307        refused("https://user:1234?pw-secret@host/", "userinfo");
6308        refused("https://host/repo@v1", "userinfo");
6309        // A port is ASCII digits alone. Leading zeros are digits.
6310        refused("http://h:+80/", "not a number");
6311        refused("http://h:-80/", "not a number");
6312        check_base_url("http://h:080/").unwrap();
6313        assert_eq!(parse_mirror("http://h:080/r").unwrap().prefix, "http://h");
6314        assert_eq!(
6315            parse_mirror("http://h:0808/r").unwrap().prefix,
6316            "http://h:808"
6317        );
6318    }
6319
6320    /// No refusal of a mirror URL names the userinfo that a password holding
6321    /// a `?` hides in the query.
6322    #[test]
6323    fn a_mirror_refusal_names_no_userinfo() {
6324        let err = parse_mirror("https://user:1234?pw-secret@host/").unwrap_err();
6325        let text = err.to_string();
6326        assert!(text.contains("query string"), "{text}");
6327        assert!(!text.contains("secret"), "{text}");
6328        let err = parse_mirror("http://h:+80/x").unwrap_err();
6329        assert!(err.to_string().contains("not a number"), "{err}");
6330    }
6331
6332    #[test]
6333    fn options_are_validated_at_construction() {
6334        rt::block_on(async {
6335            let mut options = direct_options("http://example.com");
6336            options.headers = vec![("not a header".into(), "v".into())];
6337            let err = Fetcher::new(options).await.unwrap_err();
6338            assert!(err.to_string().contains("invalid header name"), "{err}");
6339
6340            // The host header comes from the url of the request, so a host
6341            // header from the caller collides with it.
6342            let mut options = direct_options("http://example.com");
6343            options.headers = vec![("host".into(), "elsewhere".into())];
6344            let err = Fetcher::new(options).await.unwrap_err();
6345            assert!(err.to_string().contains("host header"), "{err}");
6346
6347            // Credentials and an authorization header both set the same
6348            // header, and which of the two to send is not stated.
6349            let mut options = tls_options("https://example.com");
6350            options.headers = vec![("authorization".into(), "Basic aaa".into())];
6351            options.basic_auth = Some(BasicAuth {
6352                user: "u".into(),
6353                password: "p".into(),
6354            });
6355            let err = Fetcher::new(options).await.unwrap_err();
6356            assert!(err.to_string().contains("pass one of them"), "{err}");
6357
6358            // A low-speed rule with a zero measures nothing. The constructor
6359            // refuses it, and does not read it as no rule.
6360            for low_speed in [
6361                LowSpeed {
6362                    limit: 0,
6363                    time: Duration::from_secs(30),
6364                },
6365                LowSpeed {
6366                    limit: 1000,
6367                    time: Duration::ZERO,
6368                },
6369            ] {
6370                let mut options = direct_options("http://example.com");
6371                options.low_speed = Some(low_speed);
6372                let err = Fetcher::new(options).await.unwrap_err();
6373                assert!(err.to_string().contains("neither may be zero"), "{err}");
6374            }
6375        });
6376    }
6377
6378    /// A low-speed time is rounded up to whole seconds, and saturates at the
6379    /// maximum with no wrap.
6380    #[test]
6381    fn a_low_speed_time_rounds_up_to_whole_seconds() {
6382        let rule = |time| LowSpeed { limit: 1000, time };
6383        let secs = Duration::from_secs;
6384        assert_eq!(rule(secs(30)).whole_seconds(), secs(30));
6385        assert_eq!(rule(Duration::from_millis(200)).whole_seconds(), secs(1));
6386        assert_eq!(rule(Duration::from_millis(1500)).whole_seconds(), secs(2));
6387        assert_eq!(rule(Duration::MAX).whole_seconds(), secs(u64::MAX));
6388    }
6389
6390    /// The second at which the low-speed rule fails a body that delivers
6391    /// `bursts`. Each burst is a byte count at a whole second after the first
6392    /// read. `None` states that the rule does not fail the body within
6393    /// `seconds`.
6394    fn low_speed_failure(time: u64, bursts: &[(u64, u64)], seconds: u64) -> Option<u64> {
6395        let mut monitor = Monitor::new(LowSpeed {
6396            limit: 1000,
6397            time: Duration::from_secs(time),
6398        });
6399        (1..=seconds).find(|&second| {
6400            let arrived: u64 = bursts
6401                .iter()
6402                .filter(|(at, _)| *at == second - 1)
6403                .map(|(_, bytes)| bytes)
6404                .sum();
6405            monitor.counted += arrived;
6406            monitor.sample()
6407        })
6408    }
6409
6410    /// The low-speed rule fails a body at the second at which the `ostree`
6411    /// command fails the same transfer. The limit is 1000 bytes per second,
6412    /// and the time is 2 seconds.
6413    #[test]
6414    fn the_low_speed_rule_fails_where_the_tool_fails() {
6415        rt::block_on(async {
6416            // Nothing arrives: the rate is below the limit from the start.
6417            assert_eq!(low_speed_failure(2, &[], 20), Some(2));
6418            assert_eq!(low_speed_failure(3, &[], 20), Some(3));
6419            // One burst and then nothing. The rate falls below the limit when
6420            // the burst ages out of the five-second span. It also falls below
6421            // when the burst over the seconds so far is below the limit. A
6422            // sample of exactly the limit counts as below it.
6423            assert_eq!(low_speed_failure(2, &[(0, 1_000)], 20), Some(2));
6424            assert_eq!(low_speed_failure(2, &[(0, 3_000)], 20), Some(5));
6425            assert_eq!(low_speed_failure(2, &[(0, 5_000)], 20), Some(7));
6426            assert_eq!(low_speed_failure(2, &[(0, 20_000)], 20), Some(8));
6427            assert_eq!(low_speed_failure(2, &[(0, 8_000)], 20), Some(8));
6428            assert_eq!(low_speed_failure(2, &[(0, 3_500)], 20), Some(6));
6429            // A second burst that arrives before the rate stays below the
6430            // limit for 2 seconds starts the count again. The body ends with
6431            // the second burst.
6432            let second = |at| [(0, 6_000), (at, 6_000)];
6433            assert_eq!(low_speed_failure(2, &second(6), 7), None);
6434            assert_eq!(low_speed_failure(2, &second(7), 8), None);
6435            assert_eq!(low_speed_failure(2, &second(8), 9), Some(8));
6436            // Bursts whose average is above the limit pass, though some whole
6437            // seconds carry nothing.
6438            let bursts: Vec<(u64, u64)> = (0..20).step_by(2).map(|at| (at, 2_100)).collect();
6439            assert_eq!(low_speed_failure(1, &bursts, 20), None);
6440        });
6441    }
6442
6443    /// A fetcher with no mirror serves the URLs its requests name. A path
6444    /// target has nowhere to go there, and is refused before admission.
6445    #[test]
6446    fn a_path_target_needs_a_mirror() {
6447        rt::block_on(async {
6448            let fetcher = Fetcher::new(mirrorless_options()).await.unwrap();
6449            let err = fetcher.route(Target::Path("summary")).unwrap_err();
6450            assert!(err.to_string().contains("no mirror is configured"), "{err}");
6451            let route = fetcher
6452                .route(Target::Url("https://example.com/summary"))
6453                .unwrap();
6454            let Route::One(destination) = route else {
6455                panic!("a url target names one destination");
6456            };
6457            assert_eq!(destination.url(), "https://example.com/summary");
6458        });
6459    }
6460
6461    /// A request path is added to the base path as written. So a `?` or a `#`
6462    /// in it is a delimiter, and the target is not the target that the caller
6463    /// asked for.
6464    #[test]
6465    fn a_query_or_a_fragment_in_a_path_is_rejected() {
6466        for path in ["refs/heads/a?b=c", "refs/heads/a#frag"] {
6467            let Err(err) = check_path(path) else {
6468                panic!("{path} was accepted as a request path");
6469            };
6470            assert!(
6471                err.to_string().contains("no query and no fragment"),
6472                "{path}: {err}"
6473            );
6474        }
6475        check_path("refs/heads/a").unwrap();
6476    }
6477
6478    /// A path with a query goes to the mirrors. The path has the rules of a
6479    /// path target, and a `#` in the query is refused before admission.
6480    #[test]
6481    fn a_path_query_target_is_checked_and_goes_to_the_mirrors() {
6482        rt::block_on(async {
6483            let fetcher = Fetcher::new(direct_options("http://example.com/r"))
6484                .await
6485                .unwrap();
6486            let route = fetcher
6487                .route(Target::PathQuery {
6488                    path: "_ostrya/refs/v1",
6489                    query: "pattern=a",
6490                })
6491                .unwrap();
6492            let Route::Mirrors { path, query } = route else {
6493                panic!("a path query target goes to the mirrors");
6494            };
6495            assert_eq!((path, query), ("_ostrya/refs/v1", Some("pattern=a")));
6496
6497            let refused = [
6498                ("p?x", "q", "no query and no fragment"),
6499                ("p#x", "q", "no query and no fragment"),
6500                ("p", "q#x", "a query holds no fragment"),
6501            ];
6502            for (path, query, message) in refused {
6503                let err = fetcher
6504                    .route(Target::PathQuery { path, query })
6505                    .unwrap_err();
6506                assert!(matches!(err, Error::Fetch(_)), "{err:?}");
6507                assert!(err.to_string().contains(message), "{path}?{query}: {err}");
6508            }
6509
6510            let fetcher = Fetcher::new(mirrorless_options()).await.unwrap();
6511            let err = fetcher
6512                .route(Target::PathQuery {
6513                    path: "p",
6514                    query: "q",
6515                })
6516                .unwrap_err();
6517            assert!(
6518                err.to_string().contains("path p?q has nowhere to go"),
6519                "{err}"
6520            );
6521        });
6522    }
6523
6524    /// The request path is added to the base path of the mirror, and the
6525    /// target carries the origin form for HTTP/1.1.
6526    #[test]
6527    fn a_request_target_appends_the_path_to_the_base() {
6528        rt::block_on(async {
6529            let fetcher = Fetcher::new(direct_options("http://example.com/r"))
6530                .await
6531                .unwrap();
6532            let mirror = &fetcher.inner.mirrors[0];
6533            let destination = mirror.destination("refs/heads/a", None);
6534            let request = fetcher
6535                .build_request(
6536                    &destination,
6537                    &FetchRequest::path("refs/heads/a"),
6538                    &fetcher.inner.headers,
6539                    Protocol::Http11,
6540                    Via::Direct,
6541                )
6542                .unwrap();
6543            assert_eq!(request.uri(), "/r/refs/heads/a");
6544        });
6545    }
6546
6547    /// A `Location` is resolved against the URL of the response that carried
6548    /// it. So it reads as an absolute URL, a relative URL, or a
6549    /// scheme-relative URL. A fragment names a part of a representation and
6550    /// reaches no request, so a redirect drops it.
6551    #[test]
6552    fn a_location_resolves_against_the_response_that_carried_it() {
6553        let resolved = |value: &str| {
6554            resolve_location(
6555                "https://example.com/repo/objects/summary?x=1",
6556                &HeaderValue::try_from(value).unwrap(),
6557            )
6558        };
6559        for (value, hop) in [
6560            // Absolute, at another origin and at another port.
6561            ("http://other.example/p", "http://other.example/p"),
6562            (
6563                "https://other.example:8443/p?q=2",
6564                "https://other.example:8443/p?q=2",
6565            ),
6566            // Relative: rooted at the origin, and a sibling of the path the
6567            // response was answered at.
6568            ("/other/path", "https://example.com/other/path"),
6569            ("sibling", "https://example.com/repo/objects/sibling"),
6570            // Scheme-relative, which takes the scheme of the response that
6571            // redirected.
6572            ("//host.example/path", "https://host.example/path"),
6573            // A fragment is dropped, and the resolution does not refuse it.
6574            ("/other/path#frag", "https://example.com/other/path"),
6575            ("http://other.example/p#frag", "http://other.example/p"),
6576            // A scheme under which the fetcher serves nothing resolves here.
6577            // The hop check refuses it.
6578            ("file:///srv/repo", "file:///srv/repo"),
6579        ] {
6580            assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
6581        }
6582
6583        // A value that the resolution cannot read holds no URL for a request.
6584        // An empty value holds none either, because it resolves to the URL of
6585        // the response itself.
6586        assert_eq!(resolved("http://"), None);
6587        assert_eq!(resolved(""), None);
6588
6589        // A fragment alone resolves to the URL of the response itself, which is
6590        // a hop of its own.
6591        assert_eq!(
6592            resolved("#frag").as_deref(),
6593            Some("https://example.com/repo/objects/summary?x=1")
6594        );
6595
6596        // The resolution normalizes its result. A dot segment is resolved
6597        // away, a backslash reads as a path separator, and a tab is removed. A
6598        // character that a query cannot carry is percent-encoded, and an IPv4
6599        // host is canonicalized.
6600        for (value, hop) in [
6601            ("/deep/../root", "https://example.com/root"),
6602            ("/./p", "https://example.com/p"),
6603            ("/a\\b", "https://example.com/a/b"),
6604            ("/pa\tth", "https://example.com/path"),
6605            ("/p?q='x'", "https://example.com/p?q=%27x%27"),
6606            ("http://2130706433/p", "http://127.0.0.1/p"),
6607        ] {
6608            assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
6609        }
6610    }
6611
6612    /// A hop is read as a URL target is. Two hops are refused with both URLs
6613    /// named: a scheme under which the fetcher serves nothing, and a hop from
6614    /// `https` to `http`. A hop from `http` to `https` is followed.
6615    #[test]
6616    fn a_redirect_hop_is_validated_against_the_url_that_redirected() {
6617        let secure = parse_url("https://example.com/repo/summary").unwrap();
6618        let cleartext = parse_url("http://example.com/repo/summary").unwrap();
6619
6620        // A hop at another origin, and one at the origin that redirected.
6621        let hop = redirect_destination(&secure, "https://other.example/p?q=1").unwrap();
6622        assert_eq!(hop.url(), "https://other.example/p?q=1");
6623        assert_eq!(hop.origin.host, "other.example");
6624        let hop = redirect_destination(&secure, "https://example.com/elsewhere").unwrap();
6625        assert_eq!(hop.origin, secure.origin);
6626        // A hop from cleartext to tls is followed, and so is one that stays
6627        // cleartext.
6628        let hop = redirect_destination(&cleartext, "https://example.com/elsewhere").unwrap();
6629        assert!(hop.origin.tls);
6630        redirect_destination(&cleartext, "http://other.example/p").unwrap();
6631
6632        // A hop from tls to cleartext is refused, and both URLs are named.
6633        let err = redirect_destination(&secure, "http://other.example/p").unwrap_err();
6634        let message = err.to_string();
6635        assert!(
6636            message.contains("https://example.com/repo/summary"),
6637            "{message}"
6638        );
6639        assert!(message.contains("http://other.example/p"), "{message}");
6640        assert!(message.contains("cleartext"), "{message}");
6641
6642        // A scheme under which the fetcher serves nothing, named in the same
6643        // way.
6644        let err = redirect_destination(&secure, "file:///srv/repo").unwrap_err();
6645        let message = err.to_string();
6646        assert!(
6647            message.contains("https://example.com/repo/summary"),
6648            "{message}"
6649        );
6650        assert!(message.contains("file:///srv/repo"), "{message}");
6651        assert!(
6652            message.contains("not an absolute http or https url"),
6653            "{message}"
6654        );
6655
6656        // Userinfo is refused, and the password reaches no message.
6657        let err =
6658            redirect_destination(&secure, "https://alice:sup3rs3cret@other.example/p").unwrap_err();
6659        let message = err.to_string();
6660        assert!(message.contains("userinfo"), "{message}");
6661        assert!(!message.contains("sup3rs3cret"), "{message}");
6662    }
6663
6664    /// The statuses that send a fetch to another URL. A fetch is a GET, so the
6665    /// statuses that differ on the method are one case.
6666    #[test]
6667    fn the_followed_statuses_are_the_five_redirects() {
6668        for status in [301u16, 302, 303, 307, 308] {
6669            assert!(
6670                is_redirect(StatusCode::from_u16(status).unwrap()),
6671                "{status}"
6672            );
6673        }
6674        for status in [200u16, 300, 304, 305, 306, 400, 404, 500] {
6675            assert!(
6676                !is_redirect(StatusCode::from_u16(status).unwrap()),
6677                "{status}"
6678            );
6679        }
6680    }
6681
6682    #[test]
6683    fn retryable_statuses_are_classified() {
6684        for status in [500u16, 502, 503, 408, 429] {
6685            let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
6686            assert!(matches!(failure, Failure::Retry(_)), "{status}");
6687        }
6688        for status in [400u16, 401, 403, 404, 410] {
6689            let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
6690            assert!(matches!(failure, Failure::Fatal(_)), "{status}");
6691        }
6692    }
6693
6694    #[test]
6695    fn backoff_doubles_and_stops_at_two_seconds() {
6696        assert_eq!(backoff(1), Duration::from_millis(250));
6697        assert_eq!(backoff(2), Duration::from_millis(500));
6698        assert_eq!(backoff(3), Duration::from_secs(1));
6699        assert_eq!(backoff(4), Duration::from_secs(2));
6700        assert_eq!(backoff(9), Duration::from_secs(2));
6701    }
6702
6703    #[test]
6704    fn basic_auth_and_extra_headers_reach_the_header_list() {
6705        let mut options = tls_options("https://example.com");
6706        options.basic_auth = Some(BasicAuth {
6707            user: "u".into(),
6708            password: "p".into(),
6709        });
6710        options.headers = vec![("x-trace".into(), "abc".into())];
6711        let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
6712        let headers = &fetcher.inner.headers;
6713        let value = |name: HeaderName| {
6714            headers
6715                .iter()
6716                .find(|(n, _)| *n == name)
6717                .map(|(_, v)| v.to_str().unwrap().to_string())
6718        };
6719        assert_eq!(
6720            value(hyper::header::USER_AGENT).as_deref(),
6721            Some(USER_AGENT)
6722        );
6723        assert_eq!(
6724            value(HeaderName::from_static("x-trace")).as_deref(),
6725            Some("abc")
6726        );
6727        // base64("u:p")
6728        assert_eq!(
6729            value(hyper::header::AUTHORIZATION).as_deref(),
6730            Some("Basic dTpw")
6731        );
6732    }
6733
6734    /// Options for a fetcher with no mirror, which serves the URLs its
6735    /// requests name. The anchors come from the fixture authority, so the
6736    /// constructor reads no host trust store, which an empty mirror list
6737    /// otherwise demands.
6738    fn mirrorless_options() -> FetcherOptions {
6739        FetcherOptions {
6740            mirrors: Vec::new(),
6741            ..tls_options("unused")
6742        }
6743    }
6744
6745    /// Options for a fetcher at `url` that reaches every origin directly.
6746    ///
6747    /// A test that is not about the proxy states this. So the proxy variables
6748    /// of the host that runs the suite have no effect. The default form reads
6749    /// them, and a fetcher built under one goes to a proxy that no test
6750    /// started.
6751    fn direct_options(url: impl Into<String>) -> FetcherOptions {
6752        FetcherOptions {
6753            proxy: Proxy::None,
6754            ..FetcherOptions::new(url)
6755        }
6756    }
6757
6758    /// Options for an `https` mirror whose anchors come from the fixture
6759    /// authority, so the constructor reads no host trust store.
6760    fn tls_options(url: &str) -> FetcherOptions {
6761        FetcherOptions {
6762            tls: TlsOptions {
6763                roots: TrustRoots::Pem(
6764                    include_bytes!("../../../tests/fixtures/tls/ca.pem").to_vec(),
6765                ),
6766                ..TlsOptions::default()
6767            },
6768            ..direct_options(url)
6769        }
6770    }
6771
6772    /// A credential reaches every mirror, so one cleartext mirror is enough to
6773    /// refuse the configuration. Credentials named in `headers` are refused in
6774    /// the same way. Any other header is sent, whatever the scheme.
6775    #[test]
6776    fn credentials_alongside_a_cleartext_mirror_are_refused() {
6777        let auth = || {
6778            Some(BasicAuth {
6779                user: "u".into(),
6780                password: "p".into(),
6781            })
6782        };
6783
6784        // The message names the cleartext mirror, also if it is one entry among
6785        // https entries.
6786        for mirrors in [
6787            vec!["http://cleartext.example/repo".to_owned()],
6788            vec![
6789                "https://secure.example/repo".to_owned(),
6790                "http://cleartext.example/repo".to_owned(),
6791            ],
6792        ] {
6793            let options = FetcherOptions {
6794                mirrors,
6795                basic_auth: auth(),
6796                ..tls_options("unused")
6797            };
6798            let err = rt::block_on(Fetcher::new(options)).unwrap_err();
6799            let message = err.to_string();
6800            assert!(message.contains("basic-auth credentials"), "{message}");
6801            assert!(
6802                message.contains("http://cleartext.example/repo"),
6803                "{message}"
6804            );
6805        }
6806
6807        // Each header name that carries a credential, refused in the same way.
6808        for name in ["authorization", "proxy-authorization", "cookie"] {
6809            let options = FetcherOptions {
6810                headers: vec![(name.to_owned(), "secret".to_owned())],
6811                ..direct_options("http://cleartext.example/repo")
6812            };
6813            let err = rt::block_on(Fetcher::new(options)).unwrap_err();
6814            let message = err.to_string();
6815            assert!(message.contains(name), "{message}");
6816            assert!(message.contains("carries credentials"), "{message}");
6817        }
6818
6819        // A header that is not a credential reaches a cleartext mirror.
6820        let options = FetcherOptions {
6821            headers: vec![("x-trace".to_owned(), "abc".to_owned())],
6822            ..direct_options("http://cleartext.example/repo")
6823        };
6824        rt::block_on(Fetcher::new(options)).unwrap();
6825
6826        // With every mirror on https, both kinds are accepted.
6827        let options = FetcherOptions {
6828            mirrors: vec![
6829                "https://one.example/repo".to_owned(),
6830                "https://two.example/repo".to_owned(),
6831            ],
6832            basic_auth: auth(),
6833            headers: vec![("cookie".to_owned(), "session=1".to_owned())],
6834            ..tls_options("unused")
6835        };
6836        rt::block_on(Fetcher::new(options)).unwrap();
6837    }
6838
6839    /// A request URL is served as it is written. The query string is part of
6840    /// the name of the request, and reaches the wire. Userinfo and a fragment
6841    /// are never sent, so the parse refuses them. The absolute URL, the
6842    /// origin-form target, the authority, and the origin all come from the one
6843    /// string of the destination.
6844    #[test]
6845    fn url_targets_are_parsed_and_validated() {
6846        // Every row states the URL, then the absolute URL, the origin-form
6847        // target, the authority, and the origin the parse produces.
6848        let rows = [
6849            (
6850                "https://example.com/repo/summary?sig=a%2Fb&x=1",
6851                "https://example.com/repo/summary?sig=a%2Fb&x=1",
6852                "/repo/summary?sig=a%2Fb&x=1",
6853                "example.com",
6854                "https://example.com",
6855            ),
6856            // A URL with no path of its own asks for the root, with or without
6857            // the trailing slash.
6858            ("http://h", "http://h/", "/", "h", "http://h"),
6859            ("http://h/", "http://h/", "/", "h", "http://h"),
6860            // An empty query is part of what the request names.
6861            ("http://h/p?", "http://h/p?", "/p?", "h", "http://h"),
6862            (
6863                "http://h/p?a=%2F&b=1",
6864                "http://h/p?a=%2F&b=1",
6865                "/p?a=%2F&b=1",
6866                "h",
6867                "http://h",
6868            ),
6869            // The default port of the scheme is left out of the authority, also
6870            // if the URL wrote it. The scheme is held in lower case.
6871            ("https://h:443/p", "https://h/p", "/p", "h", "https://h"),
6872            ("HTTP://h/p", "http://h/p", "/p", "h", "http://h"),
6873            // An IPv6 literal keeps its brackets in the authority, and a
6874            // non-default port stays with it.
6875            (
6876                "http://[2001:db8::1]:8080/r/config",
6877                "http://[2001:db8::1]:8080/r/config",
6878                "/r/config",
6879                "[2001:db8::1]:8080",
6880                "http://[2001:db8::1]:8080",
6881            ),
6882        ];
6883        for (url, absolute, target, authority, origin) in rows {
6884            let dest = parse_url(url).unwrap();
6885            assert_eq!(dest.url(), absolute, "{url}");
6886            assert_eq!(dest.target(), target, "{url}");
6887            assert_eq!(dest.authority, authority, "{url}");
6888            assert_eq!(dest.origin_url(), origin, "{url}");
6889        }
6890
6891        let dest = parse_url("https://example.com/repo/summary?sig=a%2Fb&x=1").unwrap();
6892        assert_eq!(dest.origin.port, 443);
6893        assert!(dest.origin.tls);
6894        let root = parse_url("http://example.com").unwrap();
6895        assert_eq!(root.origin.port, 80);
6896        assert!(!root.origin.tls);
6897        // The address is held without the brackets of the authority.
6898        let ported = parse_url("http://[::1]:8080/r/config").unwrap();
6899        assert_eq!(ported.origin.host, "::1");
6900        assert_eq!(ported.origin.port, 8080);
6901
6902        // The refusal names the scheme and the host, and leaves the password
6903        // out of a message a caller logs.
6904        let err = parse_url("https://alice:sup3rs3cret@example.com/p").unwrap_err();
6905        let message = err.to_string();
6906        assert!(message.contains("userinfo"), "{message}");
6907        assert!(message.contains("https url for example.com"), "{message}");
6908        assert!(message.contains("FetchRequest::basic_auth"), "{message}");
6909        assert!(!message.contains("sup3rs3cret"), "{message}");
6910
6911        let err = parse_url("https://example.com/p#frag").unwrap_err();
6912        assert!(err.to_string().contains("fragment"), "{err}");
6913        let err = parse_url("file:///srv/repo").unwrap_err();
6914        assert!(matches!(err, Error::Unsupported(_)), "{err}");
6915        let err = parse_url("/srv/repo").unwrap_err();
6916        assert!(err.to_string().contains("not an absolute"), "{err}");
6917    }
6918
6919    /// Each message about a URL whose authority the parse did not read yet
6920    /// leaves out the userinfo.
6921    #[test]
6922    fn a_password_reaches_no_message() {
6923        for url in [
6924            "https://alice:sup3rs3cret@example.com/p",
6925            "https://alice:sup3rs3cret@example.com/p#frag",
6926            "http://alice:sup3rs3cret@example.com/ p",
6927            "http://alice:sup3rs3cret@",
6928            "alice:sup3rs3cret@example.com/p",
6929        ] {
6930            let err = parse_url(url).unwrap_err();
6931            let message = err.to_string();
6932            assert!(!message.contains("sup3rs3cret"), "{url}: {message}");
6933        }
6934
6935        // A password with a `/`, a `?`, or a `#` ends the authority before the
6936        // `@`. The userinfo is left out also in this case.
6937        for password in ["pa#ss", "pa?ss", "p/ss"] {
6938            let url = format!("https://alice:{password}@example.com/p");
6939            let message = parse_url(&url).unwrap_err().to_string();
6940            assert!(!message.contains(password), "{password}: {message}");
6941        }
6942    }
6943
6944    /// `Uri` accepts an authority whose port it cannot read, and reports no
6945    /// port for it. So the parse refuses a URL that names such a port, and does
6946    /// not serve it from the default of the scheme.
6947    #[test]
6948    fn a_port_the_url_parser_cannot_read_is_refused() {
6949        for (url, text) in [
6950            ("http://h:99999/x", "99999"),
6951            ("http://h:65536/x", "65536"),
6952            ("http://h:abc/x", "abc"),
6953            ("http://h:/x", ""),
6954            // The integer parse of `std` takes a leading `+`, and a port is
6955            // ASCII digits alone.
6956            ("http://h:+80/x", "+80"),
6957        ] {
6958            let err = parse_url(url).unwrap_err();
6959            let message = err.to_string();
6960            assert!(message.contains(url), "{url}: {message}");
6961            assert!(message.contains(text), "{url}: {message}");
6962            assert!(message.contains("not a number"), "{url}: {message}");
6963            // A mirror URL is read by the same parse.
6964            assert!(parse_mirror(url).is_err(), "{url}");
6965        }
6966
6967        // A URL with no port at all takes the scheme default, and a port the
6968        // parser reads is kept.
6969        let default = parse_url("http://h/x").unwrap();
6970        assert_eq!(default.origin.port, 80);
6971        assert_eq!(default.url(), "http://h/x");
6972        let ported = parse_url("http://h:8080/x").unwrap();
6973        assert_eq!(ported.origin.port, 8080);
6974        assert_eq!(ported.url(), "http://h:8080/x");
6975        // Leading zeros are digits: the port is the number they give.
6976        let zeros = parse_url("http://h:0080/x").unwrap();
6977        assert_eq!(zeros.origin.port, 80);
6978        assert_eq!(zeros.url(), "http://h/x");
6979    }
6980
6981    /// A host is one origin in each case of its letters, so two spellings of
6982    /// one origin are one pool key.
6983    #[test]
6984    fn a_host_in_another_case_is_one_origin() {
6985        let upper = parse_url("http://LOCALHOST:8080/x").unwrap();
6986        let lower = parse_url("http://localhost:8080/x").unwrap();
6987        assert_eq!(upper.origin, lower.origin);
6988        assert_eq!(upper.origin.host, "localhost");
6989        // The authority reaches the wire as the caller wrote it.
6990        assert_eq!(upper.authority, "LOCALHOST:8080");
6991        assert_eq!(upper.url(), "http://LOCALHOST:8080/x");
6992    }
6993
6994    /// The rendering of a struct with credentials leaves out the password.
6995    #[test]
6996    fn basic_auth_debug_holds_no_password() {
6997        let auth = BasicAuth {
6998            user: "alice".into(),
6999            password: "sup3rs3cret".into(),
7000        };
7001        let rendered = format!("{auth:?}");
7002        assert!(rendered.contains("alice"), "{rendered}");
7003        assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
7004
7005        let request = FetchRequest {
7006            basic_auth: Some(&auth),
7007            ..FetchRequest::path("summary")
7008        };
7009        let rendered = format!("{request:?}");
7010        assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
7011
7012        let options = FetcherOptions {
7013            basic_auth: Some(auth),
7014            ..direct_options("https://example.com")
7015        };
7016        let rendered = format!("{options:?}");
7017        assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
7018    }
7019
7020    /// The origin of one absolute URL, which is what a proxy decision reads.
7021    fn origin_of(url: &str) -> Origin {
7022        parse_url(url).unwrap().origin
7023    }
7024
7025    /// How a hop at `url` is reached: the proxy that it names, and the request
7026    /// form, which is the absolute form or a tunnel.
7027    fn via_of(proxies: &Proxies, url: &str) -> Option<(String, bool)> {
7028        match proxies.via(&origin_of(url)) {
7029            Via::Direct => None,
7030            Via::Absolute(proxy) => Some((proxy.named.clone(), false)),
7031            Via::Tunnel(proxy) => Some((proxy.named.clone(), true)),
7032        }
7033    }
7034
7035    /// The variable list one test states, as the options carry it.
7036    fn variables(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
7037        pairs
7038            .iter()
7039            .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
7040            .collect()
7041    }
7042
7043    /// A proxy URL names an endpoint and nothing else. A path, a query, a
7044    /// fragment, or a scheme other than `http` states a value that a proxy
7045    /// connection has no place for. The constructor refuses each of them.
7046    #[test]
7047    fn a_proxy_url_names_an_http_endpoint() {
7048        // Every row states the URL, then the endpoint host, the port, and how a
7049        // diagnostic names the proxy.
7050        for (url, host, port, named) in [
7051            (
7052                "http://proxy.example",
7053                "proxy.example",
7054                80,
7055                "http://proxy.example",
7056            ),
7057            (
7058                "http://proxy.example:3128",
7059                "proxy.example",
7060                3128,
7061                "http://proxy.example:3128",
7062            ),
7063            // A path of `/` alone is the root, which is no path at all.
7064            (
7065                "http://proxy.example/",
7066                "proxy.example",
7067                80,
7068                "http://proxy.example",
7069            ),
7070            (
7071                "HTTP://Proxy.Example:3128",
7072                "proxy.example",
7073                3128,
7074                "http://Proxy.Example:3128",
7075            ),
7076            // An environment variable can carry space around its value. The
7077            // endpoint is read without it.
7078            (
7079                " http://proxy.example:3128 ",
7080                "proxy.example",
7081                3128,
7082                "http://proxy.example:3128",
7083            ),
7084            // An IPv6 literal keeps its brackets in the authority, and is held
7085            // without them. The connect resolves the bracketed form to nothing.
7086            ("http://[::1]:3128", "::1", 3128, "http://[::1]:3128"),
7087            (
7088                "http://alice:s3cret@proxy.example:3128",
7089                "proxy.example",
7090                3128,
7091                "http://proxy.example:3128",
7092            ),
7093        ] {
7094            let proxy = parse_proxy(url).unwrap_or_else(|e| panic!("{url}: {e}"));
7095            assert_eq!(proxy.endpoint.host, host, "{url}");
7096            assert_eq!(proxy.endpoint.port, port, "{url}");
7097            assert!(!proxy.endpoint.tls, "{url}");
7098            assert_eq!(proxy.named, named, "{url}");
7099        }
7100
7101        // Userinfo is the credential of the proxy, after the percent-decode:
7102        // base64("alice:s3cret") and base64("al:ce:p@ss").
7103        let credential = |url: &str| {
7104            parse_proxy(url)
7105                .unwrap()
7106                .credential
7107                .map(|value| value.to_str().unwrap().to_owned())
7108        };
7109        assert_eq!(credential("http://proxy.example"), None);
7110        assert_eq!(
7111            credential("http://alice:s3cret@proxy.example").as_deref(),
7112            Some("Basic YWxpY2U6czNjcmV0")
7113        );
7114        assert_eq!(
7115            credential("http://al%3Ace:p%40ss@proxy.example").as_deref(),
7116            Some("Basic YWw6Y2U6cEBzcw==")
7117        );
7118        // A user with no password is userinfo too, and it is sent with the
7119        // empty password an `Authorization` value holds: base64("alice:").
7120        assert_eq!(
7121            credential("http://alice@proxy.example").as_deref(),
7122            Some("Basic YWxpY2U6")
7123        );
7124
7125        // Every row states a URL the fetcher cannot connect through and a word
7126        // its refusal carries.
7127        for (url, says) in [
7128            ("socks5://proxy.example:1080", "http://host[:port] alone"),
7129            ("https://proxy.example:3128", "http://host[:port] alone"),
7130            ("proxy.example:3128", "http://host[:port] alone"),
7131            ("http://proxy.example/squid", "carries no path"),
7132            ("http://proxy.example/?upstream=1", "carries no query"),
7133            ("http://proxy.example/#frag", "carries no fragment"),
7134            ("http://", "invalid url"),
7135            ("http://proxy.example:99999", "not a number"),
7136            ("http://proxy.example:abc", "not a number"),
7137            ("http://alice:p%zz@proxy.example", "percent-encoded"),
7138            ("http://alice:p%4@proxy.example", "percent-encoded"),
7139        ] {
7140            let err = parse_proxy(url).unwrap_err();
7141            assert!(matches!(err, Error::Unsupported(_)), "{url}: {err}");
7142            let message = err.to_string();
7143            assert!(message.contains(says), "{url}: {message}");
7144        }
7145    }
7146
7147    /// `http_proxy` serves cleartext origins, and `https_proxy` serves TLS
7148    /// origins. `all_proxy` serves both schemes if the scheme-specific variable
7149    /// is unset. Lower case wins over upper case, and an empty value counts as
7150    /// unset. Nothing reads `HTTP_PROXY`.
7151    #[test]
7152    fn the_proxy_variables_are_read_per_scheme() {
7153        let cleartext = "http://origin.example/summary";
7154        let tls = "https://origin.example/summary";
7155        let absolute = |named: &str| Some((named.to_owned(), false));
7156        let tunnel = |named: &str| Some((named.to_owned(), true));
7157
7158        // Each scheme is served by its own variable, and the request form
7159        // follows the origin. Cleartext uses the absolute form over a proxy
7160        // connection, and TLS uses a tunnel.
7161        let proxies = resolve_variables(&variables(&[
7162            ("http_proxy", "http://plain.example:3128"),
7163            ("https_proxy", "http://secure.example:3128"),
7164        ]))
7165        .unwrap();
7166        assert_eq!(
7167            via_of(&proxies, cleartext),
7168            absolute("http://plain.example:3128")
7169        );
7170        assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
7171
7172        // One variable serves its own scheme alone.
7173        let proxies =
7174            resolve_variables(&variables(&[("http_proxy", "http://plain.example:3128")])).unwrap();
7175        assert_eq!(
7176            via_of(&proxies, cleartext),
7177            absolute("http://plain.example:3128")
7178        );
7179        assert_eq!(via_of(&proxies, tls), None);
7180        let proxies =
7181            resolve_variables(&variables(&[("https_proxy", "http://secure.example:3128")]))
7182                .unwrap();
7183        assert_eq!(via_of(&proxies, cleartext), None);
7184        assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
7185
7186        // `all_proxy` serves either scheme, and the scheme-specific variable
7187        // takes the scheme it names.
7188        let proxies =
7189            resolve_variables(&variables(&[("all_proxy", "http://any.example:3128")])).unwrap();
7190        assert_eq!(
7191            via_of(&proxies, cleartext),
7192            absolute("http://any.example:3128")
7193        );
7194        assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
7195        let proxies = resolve_variables(&variables(&[
7196            ("all_proxy", "http://any.example:3128"),
7197            ("https_proxy", "http://secure.example:3128"),
7198        ]))
7199        .unwrap();
7200        assert_eq!(
7201            via_of(&proxies, cleartext),
7202            absolute("http://any.example:3128")
7203        );
7204        assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
7205
7206        // The upper-case name is read for each variable except `http_proxy`. A
7207        // CGI gateway gives a request header called `Proxy` to its program
7208        // under that name.
7209        let proxies = resolve_variables(&variables(&[
7210            ("HTTP_PROXY", "http://cgi.example:3128"),
7211            ("HTTPS_PROXY", "http://secure.example:3128"),
7212        ]))
7213        .unwrap();
7214        assert_eq!(via_of(&proxies, cleartext), None);
7215        assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
7216        let proxies =
7217            resolve_variables(&variables(&[("ALL_PROXY", "http://any.example:3128")])).unwrap();
7218        assert_eq!(
7219            via_of(&proxies, cleartext),
7220            absolute("http://any.example:3128")
7221        );
7222
7223        // Lower case wins over upper case, and an empty value counts as unset.
7224        // So the upper-case name is the one that is read.
7225        let proxies = resolve_variables(&variables(&[
7226            ("https_proxy", "http://lower.example:3128"),
7227            ("HTTPS_PROXY", "http://upper.example:3128"),
7228        ]))
7229        .unwrap();
7230        assert_eq!(via_of(&proxies, tls), tunnel("http://lower.example:3128"));
7231        let proxies = resolve_variables(&variables(&[
7232            ("https_proxy", ""),
7233            ("HTTPS_PROXY", "http://upper.example:3128"),
7234        ]))
7235        .unwrap();
7236        assert_eq!(via_of(&proxies, tls), tunnel("http://upper.example:3128"));
7237        let proxies = resolve_variables(&variables(&[("http_proxy", "")])).unwrap();
7238        assert_eq!(via_of(&proxies, cleartext), None);
7239
7240        // A value the fetcher cannot connect through fails the resolution
7241        // whichever variable held it.
7242        for name in ["http_proxy", "https_proxy", "all_proxy"] {
7243            let err = resolve_variables(&variables(&[(name, "socks5://proxy.example:1080")]))
7244                .unwrap_err();
7245            assert!(matches!(err, Error::Unsupported(_)), "{name}: {err}");
7246        }
7247        // A variable that the selection passes over is parsed too. An
7248        // `all_proxy` beside both scheme-specific variables is read by no
7249        // fetch. If it holds a value that the fetcher cannot connect through,
7250        // the resolution fails.
7251        let err = resolve_variables(&variables(&[
7252            ("all_proxy", "socks5://proxy.example:1080"),
7253            ("http_proxy", "http://plain.example:3128"),
7254            ("https_proxy", "http://secure.example:3128"),
7255        ]))
7256        .unwrap_err();
7257        assert!(matches!(err, Error::Unsupported(_)), "{err}");
7258
7259        // No variable at all, and the explicit forms of the option.
7260        let proxies = resolve_variables(&[]).unwrap();
7261        assert_eq!(via_of(&proxies, cleartext), None);
7262        assert_eq!(via_of(&proxies, tls), None);
7263        let proxies = resolve_proxy(&Proxy::None).unwrap();
7264        assert_eq!(via_of(&proxies, cleartext), None);
7265        // One URL serves every origin, and it reads no exemption.
7266        let proxies = resolve_proxy(&Proxy::Url("http://any.example:3128".into())).unwrap();
7267        assert_eq!(
7268            via_of(&proxies, cleartext),
7269            absolute("http://any.example:3128")
7270        );
7271        assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
7272    }
7273
7274    /// A proxy variable with white space at the start or the end of its value
7275    /// fails the resolution, also a value of white space alone. The message
7276    /// names the variable, and holds nothing of the value. Each variable that
7277    /// the selection reads is checked, also if no fetch uses it. A variable
7278    /// that the selection does not read is not checked.
7279    #[test]
7280    fn a_proxy_variable_with_white_space_around_it_is_refused() {
7281        let url = "http://alice:s3cret@proxy.example:3128";
7282        let refused = |pairs: &[(&str, &str)], name: &str| {
7283            let err = resolve_variables(&variables(pairs)).unwrap_err();
7284            assert!(matches!(err, Error::Unsupported(_)), "{pairs:?}: {err}");
7285            let message = err.to_string();
7286            assert!(message.contains(name), "{pairs:?}: {message}");
7287            assert!(!message.contains("s3cret"), "{pairs:?}: {message}");
7288            assert!(!message.contains("proxy.example"), "{pairs:?}: {message}");
7289        };
7290
7291        for name in [
7292            "http_proxy",
7293            "https_proxy",
7294            "HTTPS_PROXY",
7295            "all_proxy",
7296            "ALL_PROXY",
7297        ] {
7298            for value in [
7299                format!(" {url}"),
7300                format!("{url} "),
7301                format!("{url}\t"),
7302                format!("{url}\n"),
7303                format!("{url}\u{a0}"),
7304                "   ".to_owned(),
7305            ] {
7306                refused(&[(name, &value)], name);
7307            }
7308        }
7309        // If the lower-case value is empty, the upper-case name is read, and
7310        // the refusal names it.
7311        refused(
7312            &[("all_proxy", ""), ("ALL_PROXY", "http://p:1 ")],
7313            "ALL_PROXY",
7314        );
7315        // The check comes before the parse, so a value the parse refuses as
7316        // well gets the white-space refusal.
7317        refused(
7318            &[("all_proxy", "socks5://alice:s3cret@proxy.example:1080 ")],
7319            "all_proxy",
7320        );
7321        // The refusal occurs when the fetcher is built. So an exemption of
7322        // every origin does not prevent it.
7323        refused(
7324            &[("http_proxy", &format!("{url} ")), ("no_proxy", "*")],
7325            "http_proxy",
7326        );
7327        // `all_proxy` beside both scheme-specific variables is read by no
7328        // fetch, and the check still reads its value.
7329        refused(
7330            &[
7331                ("all_proxy", &format!("{url} ")),
7332                ("http_proxy", "http://plain.example:3128"),
7333                ("https_proxy", "http://secure.example:3128"),
7334            ],
7335            "all_proxy",
7336        );
7337
7338        // An upper-case name shadowed by its lower-case one is not read, and
7339        // `HTTP_PROXY` is read by nothing.
7340        resolve_variables(&variables(&[
7341            ("https_proxy", "http://secure.example:3128"),
7342            ("HTTPS_PROXY", "http://upper.example:3128 "),
7343        ]))
7344        .unwrap();
7345        resolve_variables(&variables(&[("HTTP_PROXY", "http://cgi.example:3128 ")])).unwrap();
7346        // A URL the caller states in the options keeps its trim.
7347        resolve_proxy(&Proxy::Url("http://p:3128 ".into())).unwrap();
7348    }
7349
7350    /// What `no_proxy` exempts: an exact host, a host under a listed domain, a
7351    /// port-qualified entry, and every host under `*`. The match is made
7352    /// against the host text and never against the address it resolves to.
7353    #[test]
7354    fn no_proxy_exempts_by_host_text_and_port() {
7355        let proxied = |no_proxy: &str, url: &str| {
7356            let proxies = resolve_variables(&variables(&[
7357                ("all_proxy", "http://any.example:3128"),
7358                ("no_proxy", no_proxy),
7359            ]))
7360            .unwrap();
7361            via_of(&proxies, url).is_some()
7362        };
7363
7364        // An exact host, and a host of another name at the same domain.
7365        assert!(!proxied("origin.example", "http://origin.example/p"));
7366        assert!(proxied("origin.example", "http://other.example/p"));
7367        // A host under a listed domain, in each of the two spellings of the
7368        // entry. A name that only ends with the same letters is not exempted.
7369        for entry in ["example.com", ".example.com"] {
7370            assert!(!proxied(entry, "http://a.example.com/p"));
7371            assert!(!proxied(entry, "http://deep.a.example.com/p"));
7372            assert!(!proxied(entry, "http://example.com/p"));
7373            assert!(proxied(entry, "http://notexample.com/p"));
7374        }
7375        // The list is comma-separated, space around an entry is ignored, and an
7376        // empty entry names nothing.
7377        assert!(!proxied(" a.example , b.example ", "http://b.example/p"));
7378        assert!(!proxied("a.example,,b.example", "http://a.example/p"));
7379        assert!(proxied(",", "http://a.example/p"));
7380        assert!(proxied("", "http://a.example/p"));
7381        // ASCII case is ignored on both sides.
7382        assert!(!proxied("ORIGIN.example", "http://origin.EXAMPLE/p"));
7383        // A port-qualified entry matches that port alone.
7384        assert!(!proxied(
7385            "origin.example:8080",
7386            "http://origin.example:8080/p"
7387        ));
7388        assert!(proxied(
7389            "origin.example:8080",
7390            "http://origin.example:8081/p"
7391        ));
7392        assert!(proxied("origin.example:8080", "http://origin.example/p"));
7393        assert!(!proxied("origin.example:443", "https://origin.example/p"));
7394        // An entry with no port matches whatever port the origin names.
7395        assert!(!proxied("origin.example", "http://origin.example:8080/p"));
7396        // `*` exempts every host, whatever else the list holds.
7397        for url in ["http://a.example/p", "https://b.example:8443/p"] {
7398            assert!(!proxied("*", url));
7399            assert!(!proxied("a.example,*", url));
7400        }
7401        // An IP literal matches that text and nothing else. So the address of a
7402        // name does not exempt the name, and a name does not exempt an address.
7403        assert!(!proxied("127.0.0.1", "http://127.0.0.1:8080/p"));
7404        assert!(proxied("localhost", "http://127.0.0.1:8080/p"));
7405        assert!(proxied("127.0.0.1", "http://localhost:8080/p"));
7406        // An IPv6 literal is exempted by the address alone, written with or
7407        // without the brackets the authority carries.
7408        for entry in ["::1", "[::1]", "[::1]:8080"] {
7409            assert!(!proxied(entry, "http://[::1]:8080/p"), "{entry}");
7410        }
7411        assert!(proxied("[::1]:8081", "http://[::1]:8080/p"));
7412        // A network in CIDR notation names no network here: it is read as a
7413        // host text, which no origin holds.
7414        assert!(proxied("127.0.0.0/8", "http://127.0.0.1:8080/p"));
7415        // A port text that is no port leaves the entry as one host text, which
7416        // no origin host holds.
7417        assert!(proxied("origin.example:abc", "http://origin.example/p"));
7418        // An entry that names no host exempts nothing, also for a host written
7419        // with a trailing `.`.
7420        for entry in [".", ":8080", ".:8080"] {
7421            assert!(proxied(entry, "http://a.example./p"), "{entry}");
7422            assert!(proxied(entry, "http://a.example:8080/p"), "{entry}");
7423        }
7424        // One leading `.` is stripped, so a second belongs to the host text the
7425        // entry names.
7426        assert!(proxied("..example.com", "http://a.example.com/p"));
7427        // `*` as a whole entry is the one wildcard of the list. Each other form
7428        // with a `*` is a host text.
7429        assert!(proxied("*.example.com", "http://a.example.com/p"));
7430        assert!(proxied("*.example.com", "http://example.com/p"));
7431    }
7432
7433    /// The userinfo of a proxy URL holds a password. So it reaches neither a
7434    /// rendering of the options nor a refusal of the constructor.
7435    #[test]
7436    fn a_proxy_password_reaches_no_message() {
7437        let url = |tail: &str| format!("http://alice:sup3rs3cret@proxy.example:3128{tail}");
7438
7439        // The rendering of every form that carries a URL.
7440        for proxy in [
7441            Proxy::Url(url("")),
7442            Proxy::Variables(vec![("https_proxy".to_owned(), url(""))]),
7443        ] {
7444            let rendered = format!("{proxy:?}");
7445            assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
7446            assert!(rendered.contains("proxy.example:3128"), "{rendered}");
7447
7448            let options = FetcherOptions {
7449                proxy,
7450                ..direct_options("https://example.com")
7451            };
7452            let rendered = format!("{options:?}");
7453            assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
7454        }
7455
7456        // Each refusal, whichever part of the URL the parse read.
7457        for tail in ["/squid", "/?upstream=1", "/#frag", ":99999"] {
7458            let err = parse_proxy(&url(tail)).unwrap_err();
7459            let message = err.to_string();
7460            assert!(!message.contains("sup3rs3cret"), "{tail}: {message}");
7461        }
7462        let err = parse_proxy("socks5://alice:sup3rs3cret@proxy.example:1080").unwrap_err();
7463        assert!(!err.to_string().contains("sup3rs3cret"), "{err}");
7464
7465        // A password with a `/`, a `?`, or a `#` ends the authority before the
7466        // `@`. The userinfo is left out also in this case.
7467        for password in ["pa#ss", "pa?ss", "p/ss"] {
7468            let url = format!("http://alice:{password}@proxy.example:3128/squid");
7469            let rendered = format!("{:?}", Proxy::Url(url.clone()));
7470            assert!(!rendered.contains(password), "{password}: {rendered}");
7471            assert!(
7472                rendered.contains("proxy.example:3128"),
7473                "{password}: {rendered}"
7474            );
7475            let message = parse_proxy(&url).unwrap_err().to_string();
7476            assert!(!message.contains(password), "{password}: {message}");
7477            assert!(
7478                message.contains("proxy.example:3128"),
7479                "{password}: {message}"
7480            );
7481        }
7482
7483        // A `/` or a `?` in the userinfo moves the text after it into the path
7484        // or the query. The refusal of that path or query shows no part of it.
7485        for userinfo in ["u/pw-QXZ", "tok?pw-QXZ", "u:x/pw-QXZ", "u:x?pw-QXZ"] {
7486            let url = format!("http://{userinfo}@proxy.invalid:3128");
7487            let message = parse_proxy(&url).unwrap_err().to_string();
7488            assert!(!message.contains("pw-QXZ"), "{userinfo}: {message}");
7489        }
7490
7491        // The refusal the constructor writes is the one a caller logs.
7492        rt::block_on(async {
7493            let err = Fetcher::new(FetcherOptions {
7494                proxy: Proxy::Url(url("/squid")),
7495                ..direct_options("http://origin.example/repo")
7496            })
7497            .await
7498            .unwrap_err();
7499            assert!(matches!(err, Error::Unsupported(_)), "{err}");
7500            let message = err.to_string();
7501            assert!(!message.contains("sup3rs3cret"), "{message}");
7502            assert!(message.contains("proxy.example:3128"), "{message}");
7503        });
7504    }
7505
7506    /// The `Debug` of a proxy writes each URL as `RedactedUrl` writes it. The
7507    /// form of each variant is the form of `derive(Debug)`.
7508    #[test]
7509    fn proxy_debug_redacts_each_url() {
7510        let url = "http://alice:pw-QXZ@proxy.example:3128/?t=QXZ#QXZ";
7511        assert_eq!(
7512            format!("{:?}", Proxy::Url(url.to_owned())),
7513            r#"Url("http://proxy.example:3128/?<redacted>#<redacted>")"#
7514        );
7515        let variables = Proxy::Variables(vec![
7516            ("https_proxy".to_owned(), url.to_owned()),
7517            ("no_proxy".to_owned(), ".internal.example.com".to_owned()),
7518        ]);
7519        assert_eq!(
7520            format!("{variables:?}"),
7521            concat!(
7522                r#"Variables([("https_proxy", "http://proxy.example:3128/?<redacted>#<redacted>"), "#,
7523                r#"("no_proxy", ".internal.example.com")])"#
7524            )
7525        );
7526        assert_eq!(format!("{:?}", Proxy::None), "None");
7527        assert_eq!(format!("{:?}", Proxy::Environment), "Environment");
7528    }
7529
7530    /// The text before `://` is a scheme only when it is a valid scheme. Else
7531    /// the userinfo starts at the start of the text.
7532    #[test]
7533    fn without_userinfo_reads_only_a_valid_scheme() {
7534        assert_eq!(without_userinfo("u:a://b@h/p"), "h/p");
7535        assert_eq!(without_userinfo("svn+ssh://u@h/p"), "svn+ssh://h/p");
7536        assert_eq!(without_userinfo("https://h/p"), "https://h/p");
7537        assert_eq!(scheme_len("1http://h"), 0);
7538        assert_eq!(scheme_len("://h"), 0);
7539        assert_eq!(scheme_len("h/p"), 0);
7540    }
7541
7542    /// A `CONNECT` names its target by host and port, and always writes the
7543    /// port. The proxy opens a TCP connection, which reads no scheme.
7544    #[test]
7545    fn a_connect_names_the_target_with_its_port() {
7546        for (url, authority) in [
7547            ("https://origin.example/p", "origin.example:443"),
7548            ("https://origin.example:8443/p", "origin.example:8443"),
7549            ("http://origin.example/p", "origin.example:80"),
7550            ("https://[2001:db8::1]/p", "[2001:db8::1]:443"),
7551            ("https://[::1]:8443/p", "[::1]:8443"),
7552        ] {
7553            assert_eq!(connect_authority(&origin_of(url)), authority, "{url}");
7554        }
7555    }
7556
7557    /// A proxied cleartext request carries the absolute-form target and the
7558    /// `Host` header of the origin. It also carries the credential of the
7559    /// proxy, if the merged headers hold no header of that name. A direct
7560    /// request and the request over a tunnel carry the origin form and nothing
7561    /// of the proxy.
7562    #[test]
7563    fn a_proxied_cleartext_request_carries_the_absolute_form() {
7564        rt::block_on(async {
7565            let fetcher = Fetcher::new(FetcherOptions {
7566                proxy: Proxy::Url("http://alice:s3cret@proxy.example:3128".into()),
7567                ..tls_options("http://origin.example/r")
7568            })
7569            .await
7570            .unwrap();
7571            let destination = fetcher.inner.mirrors[0].destination("refs/heads/a", None);
7572            let request = FetchRequest::path("refs/heads/a");
7573            let built = |via: Via<'_>, headers: &[(HeaderName, HeaderValue)]| {
7574                fetcher
7575                    .build_request(&destination, &request, headers, Protocol::Http11, via)
7576                    .unwrap()
7577            };
7578            let proxy_credential = |request: &Request<RequestBody>| {
7579                request
7580                    .headers()
7581                    .get(hyper::header::PROXY_AUTHORIZATION)
7582                    .map(|value| value.to_str().unwrap().to_owned())
7583            };
7584            let Via::Absolute(proxy) = fetcher.inner.proxies.via(&destination.origin) else {
7585                panic!("a cleartext origin behind a proxy travels in absolute form");
7586            };
7587            let via = Via::Absolute(proxy);
7588
7589            let absolute = built(via, &fetcher.inner.headers);
7590            assert_eq!(absolute.uri(), "http://origin.example/r/refs/heads/a");
7591            assert_eq!(
7592                absolute.headers().get(hyper::header::HOST).unwrap(),
7593                "origin.example"
7594            );
7595            // base64("alice:s3cret")
7596            assert_eq!(
7597                proxy_credential(&absolute).as_deref(),
7598                Some("Basic YWxpY2U6czNjcmV0")
7599            );
7600
7601            // A `Proxy-Authorization` header that the caller set states the
7602            // value for the proxy. So the credential of the fetcher is left
7603            // out, and is not added to it.
7604            let mut headers = fetcher.inner.headers.clone();
7605            headers.push((
7606                hyper::header::PROXY_AUTHORIZATION,
7607                HeaderValue::from_static("Basic Y2FsbGVy"),
7608            ));
7609            let caller = built(via, &headers);
7610            assert_eq!(
7611                caller
7612                    .headers()
7613                    .get_all(hyper::header::PROXY_AUTHORIZATION)
7614                    .iter()
7615                    .count(),
7616                1
7617            );
7618            assert_eq!(proxy_credential(&caller).as_deref(), Some("Basic Y2FsbGVy"));
7619
7620            // A direct hop and the request over a tunnel carry the origin form
7621            // and nothing of the proxy.
7622            for via in [Via::Direct, Via::Tunnel(proxy)] {
7623                let direct = built(via, &fetcher.inner.headers);
7624                assert_eq!(direct.uri(), "/r/refs/heads/a");
7625                assert_eq!(proxy_credential(&direct), None);
7626            }
7627        });
7628    }
7629
7630    /// The connection layer frames a request and holds its connection. So a
7631    /// header of one of those names is refused. The constructor refuses a
7632    /// fetcher header, and a request header fails before admission.
7633    #[test]
7634    fn a_connection_header_is_refused_at_both_layers() {
7635        let fetcher_headers = vec![(
7636            HeaderName::from_static("x-trace"),
7637            HeaderValue::from_static("abc"),
7638        )];
7639        for name in CONNECTION_HEADERS {
7640            let options = FetcherOptions {
7641                headers: vec![(name.to_owned(), "10".to_owned())],
7642                ..direct_options("http://example.com")
7643            };
7644            let err = rt::block_on(Fetcher::new(options)).unwrap_err();
7645            let message = err.to_string();
7646            assert!(message.contains(name), "{name}: {message}");
7647            assert!(message.contains("connection layer"), "{name}: {message}");
7648
7649            let request = vec![(name.to_owned(), "10".to_owned())];
7650            let err = merge_headers(&fetcher_headers, &request, None, None).unwrap_err();
7651            let message = err.to_string();
7652            assert!(message.contains(name), "{name}: {message}");
7653            assert!(message.contains("connection layer"), "{name}: {message}");
7654        }
7655
7656        // A name written in another case is the same header name.
7657        let request = vec![("Content-Length".to_owned(), "10".to_owned())];
7658        let err = merge_headers(&fetcher_headers, &request, None, None).unwrap_err();
7659        assert!(err.to_string().contains("content-length"), "{err}");
7660    }
7661
7662    /// A request that adds no header and no credentials sends the list of the
7663    /// fetcher by reference. A request header replaces the fetcher header of
7664    /// the same name. The credentials of the request replace the
7665    /// `Authorization` of the fetcher.
7666    #[test]
7667    fn request_headers_merge_over_the_fetchers() {
7668        let header = |name: &'static str, value: &'static str| {
7669            (
7670                HeaderName::from_static(name),
7671                HeaderValue::from_static(value),
7672            )
7673        };
7674        let fetcher = vec![
7675            header("x-trace", "fetcher"),
7676            header("x-only", "yes"),
7677            header("authorization", "Basic ZmV0Y2hlcg=="),
7678        ];
7679        let sent = |headers: &[(HeaderName, HeaderValue)]| {
7680            headers
7681                .iter()
7682                .map(|(name, value)| (name.as_str().to_owned(), value.to_str().unwrap().to_owned()))
7683                .collect::<Vec<_>>()
7684        };
7685
7686        let borrowed = merge_headers(&fetcher, &[], None, None).unwrap();
7687        assert!(matches!(borrowed, Cow::Borrowed(_)));
7688        assert_eq!(sent(&borrowed), sent(&fetcher));
7689
7690        // The replacement compares names as header names, so the case that the
7691        // request wrote has no effect. It leaves each other fetcher header in
7692        // place. Two request headers of one name both reach the wire.
7693        let extra = vec![
7694            ("X-Trace".to_owned(), "request".to_owned()),
7695            ("x-trace".to_owned(), "second".to_owned()),
7696        ];
7697        let merged = merge_headers(&fetcher, &extra, None, None).unwrap();
7698        assert_eq!(
7699            sent(&merged),
7700            [
7701                ("x-only".to_owned(), "yes".to_owned()),
7702                ("authorization".to_owned(), "Basic ZmV0Y2hlcg==".to_owned()),
7703                ("x-trace".to_owned(), "request".to_owned()),
7704                ("x-trace".to_owned(), "second".to_owned()),
7705            ]
7706        );
7707
7708        // base64("u:p")
7709        let auth = BasicAuth {
7710            user: "u".into(),
7711            password: "p".into(),
7712        };
7713        let merged = merge_headers(&fetcher, &[], Some(&auth), None).unwrap();
7714        assert_eq!(
7715            sent(&merged),
7716            [
7717                ("x-trace".to_owned(), "fetcher".to_owned()),
7718                ("x-only".to_owned(), "yes".to_owned()),
7719                ("authorization".to_owned(), "Basic dTpw".to_owned()),
7720            ]
7721        );
7722
7723        let both = vec![("authorization".to_owned(), "Basic aaa".to_owned())];
7724        let err = merge_headers(&fetcher, &both, Some(&auth), None).unwrap_err();
7725        assert!(err.to_string().contains("pass one of them"), "{err}");
7726        let host = vec![("host".to_owned(), "elsewhere".to_owned())];
7727        let err = merge_headers(&fetcher, &host, None, None).unwrap_err();
7728        assert!(err.to_string().contains("host header"), "{err}");
7729        let invalid = vec![("not a header".to_owned(), "v".to_owned())];
7730        let err = merge_headers(&fetcher, &invalid, None, None).unwrap_err();
7731        assert!(err.to_string().contains("invalid header name"), "{err}");
7732    }
7733
7734    /// A fetch delivers the bytes that the remote stores. So a response is
7735    /// served only if it declares no coding, or declares `identity`. A value is
7736    /// a comma-separated list, and several headers state one list together. A
7737    /// token compares with no case and with no space around it.
7738    #[test]
7739    fn a_declared_content_coding_is_read_off_the_response() {
7740        let map = |values: &[&str]| {
7741            let mut headers = hyper::HeaderMap::new();
7742            for value in values {
7743                headers.append(
7744                    hyper::header::CONTENT_ENCODING,
7745                    HeaderValue::try_from(*value).unwrap(),
7746                );
7747            }
7748            headers
7749        };
7750
7751        // Nothing to undo: no header at all, an empty value, a value of
7752        // separators alone, and every spelling of the one coding that is served.
7753        for values in [
7754            vec![],
7755            vec![""],
7756            vec![","],
7757            vec!["identity"],
7758            vec!["IDENTITY"],
7759            vec![" identity "],
7760            vec!["identity", "identity"],
7761        ] {
7762            assert_eq!(declared_coding(&map(&values)), None, "{values:?}");
7763        }
7764
7765        // A coding that the body needs a decode from, named as the response
7766        // wrote it. A list with one coding refuses the whole response, at each
7767        // position of the coding. Several headers are read together, in the
7768        // order of arrival. A value whose tokens are all empty names nothing,
7769        // so it adds no separator to the message.
7770        for (values, named) in [
7771            (vec!["gzip"], "gzip"),
7772            (vec!["GZip"], "GZip"),
7773            (vec!["identity, gzip"], "identity, gzip"),
7774            (vec!["gzip, identity"], "gzip, identity"),
7775            (vec!["identity", "gzip"], "identity, gzip"),
7776            (vec!["gzip", "br"], "gzip, br"),
7777            (vec!["", "gzip"], "gzip"),
7778            (vec!["gzip", ""], "gzip"),
7779            (vec!["gzip", "", "br"], "gzip, br"),
7780            (vec!["gzip", ",", "br"], "gzip, br"),
7781        ] {
7782            assert_eq!(
7783                declared_coding(&map(&values)).as_deref(),
7784                Some(named),
7785                "{values:?}"
7786            );
7787        }
7788    }
7789
7790    /// Each request asks for no content coding. A configured header with a
7791    /// name that the fetcher sets replaces that entry, and does not join it on
7792    /// the wire.
7793    #[test]
7794    fn a_fetcher_header_replaces_the_entry_the_fetcher_sets() {
7795        let sent = |fetcher: &Fetcher, name: HeaderName| {
7796            fetcher
7797                .inner
7798                .headers
7799                .iter()
7800                .filter(|(held, _)| *held == name)
7801                .map(|(_, value)| value.to_str().unwrap().to_owned())
7802                .collect::<Vec<_>>()
7803        };
7804
7805        let fetcher = rt::block_on(Fetcher::new(direct_options("http://example.com"))).unwrap();
7806        assert_eq!(
7807            sent(&fetcher, hyper::header::ACCEPT_ENCODING),
7808            [IDENTITY.to_owned()]
7809        );
7810
7811        for name in ["accept-encoding", "user-agent"] {
7812            let options = FetcherOptions {
7813                headers: vec![(name.to_owned(), "caller".to_owned())],
7814                ..direct_options("http://example.com")
7815            };
7816            let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
7817            let header = HeaderName::from_static(name);
7818            assert_eq!(sent(&fetcher, header), ["caller".to_owned()], "{name}");
7819        }
7820
7821        // Two entries of one name both reach the wire. The first of them
7822        // replaces the entry that the fetcher sets.
7823        let options = FetcherOptions {
7824            headers: vec![
7825                ("accept-encoding".to_owned(), "one".to_owned()),
7826                ("Accept-Encoding".to_owned(), "two".to_owned()),
7827            ],
7828            ..direct_options("http://example.com")
7829        };
7830        let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
7831        assert_eq!(
7832            sent(&fetcher, hyper::header::ACCEPT_ENCODING),
7833            ["one".to_owned(), "two".to_owned()]
7834        );
7835        // A name under which the fetcher sets nothing also keeps both entries.
7836        let options = FetcherOptions {
7837            headers: vec![
7838                ("x-trace".to_owned(), "one".to_owned()),
7839                ("x-trace".to_owned(), "two".to_owned()),
7840            ],
7841            ..direct_options("http://example.com")
7842        };
7843        let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
7844        assert_eq!(
7845            sent(&fetcher, HeaderName::from_static("x-trace")),
7846            ["one".to_owned(), "two".to_owned()]
7847        );
7848    }
7849
7850    /// A credential is withheld from no destination. So one cleartext
7851    /// destination that a fetch can reach refuses it, and the message names
7852    /// the origin. A header that is not a credential reaches a cleartext
7853    /// destination.
7854    #[test]
7855    fn a_credential_refuses_a_cleartext_destination() {
7856        let credential = vec![(hyper::header::COOKIE, HeaderValue::from_static("session=1"))];
7857        let plain = vec![(
7858            HeaderName::from_static("x-trace"),
7859            HeaderValue::from_static("abc"),
7860        )];
7861        // A fetcher whose mirror list holds one cleartext entry among https
7862        // entries. The credential belongs to the request, so the construction
7863        // check of the list does not refuse it.
7864        let options = FetcherOptions {
7865            mirrors: vec![
7866                "https://secure.example/repo".to_owned(),
7867                "http://cleartext.example/repo".to_owned(),
7868            ],
7869            ..tls_options("unused")
7870        };
7871        let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
7872
7873        let mirrors = fetcher.route(Target::Path("summary")).unwrap();
7874        let err = fetcher.check_cleartext(&mirrors, &credential).unwrap_err();
7875        assert!(
7876            err.to_string().contains("http://cleartext.example"),
7877            "{err}"
7878        );
7879        fetcher.check_cleartext(&mirrors, &plain).unwrap();
7880
7881        let cleartext = fetcher
7882            .route(Target::Url("http://cleartext.example/p"))
7883            .unwrap();
7884        let err = fetcher
7885            .check_cleartext(&cleartext, &credential)
7886            .unwrap_err();
7887        assert!(
7888            err.to_string().contains("http://cleartext.example"),
7889            "{err}"
7890        );
7891        fetcher.check_cleartext(&cleartext, &plain).unwrap();
7892
7893        let secure = fetcher
7894            .route(Target::Url("https://secure.example/p"))
7895            .unwrap();
7896        fetcher.check_cleartext(&secure, &credential).unwrap();
7897    }
7898
7899    /// A handshake verifies the server certificate against a trust anchor. So
7900    /// if the fetcher holds none, a fetch of a TLS origin is refused before
7901    /// admission, and the message names the origin.
7902    ///
7903    /// A clear flag stands for a fetcher built on a host whose trust store
7904    /// holds nothing. The test sets the flag by hand, because this host has a
7905    /// CA bundle. `TrustRoots::Pem` fails the constructor over a blob that
7906    /// holds no certificate.
7907    #[test]
7908    fn a_tls_destination_needs_a_trust_anchor() {
7909        rt::block_on(async {
7910            let mut fetcher = Fetcher::new(direct_options("http://cleartext.example/repo"))
7911                .await
7912                .unwrap();
7913            Arc::get_mut(&mut fetcher.inner)
7914                .expect("the one handle on this fetcher")
7915                .has_trust_anchors = false;
7916
7917            // Nothing listens on port 1 of the loopback. So an attempt fails
7918            // its connect, and the fetcher tries again through each round and
7919            // each backoff. The refusal is definitive and takes no attempt, so
7920            // it resolves at once.
7921            let refused = within(
7922                Duration::from_secs(1),
7923                fetcher.fetch(FetchRequest::url("https://127.0.0.1:1/summary")),
7924            )
7925            .await;
7926            let err = refused
7927                .expect("the refusal takes no attempt")
7928                .expect_err("a tls url is refused without anchors");
7929            let message = err.to_string();
7930            assert!(message.contains("https://127.0.0.1:1"), "{message}");
7931            assert!(message.contains("no trust anchors"), "{message}");
7932
7933            // A cleartext destination opens no handshake, so it is served by
7934            // the same fetcher.
7935            let cleartext = fetcher
7936                .route(Target::Url("http://cleartext.example/summary"))
7937                .unwrap();
7938            fetcher.check_trust_anchors(&cleartext).unwrap();
7939            let mirrors = fetcher.route(Target::Path("summary")).unwrap();
7940            fetcher.check_trust_anchors(&mirrors).unwrap();
7941        });
7942    }
7943
7944    /// The constructor reads the host trust store only if a fetch can open a
7945    /// handshake. A fetcher whose mirrors are all `http`, and that follows no
7946    /// redirect, reads no store and holds no anchor. It refuses a URL target
7947    /// that names an `https` origin. An `https` mirror, an empty mirror list, and
7948    /// a redirect limit above zero each read the store.
7949    #[test]
7950    fn a_cleartext_fetcher_with_no_redirect_reads_no_trust_store() {
7951        let reads = || tls::SYSTEM_STORE_READS.with(std::cell::Cell::get);
7952        rt::block_on(async {
7953            let before = reads();
7954            let fetcher = Fetcher::new(FetcherOptions {
7955                max_redirects: 0,
7956                ..direct_options("http://cleartext.example/repo")
7957            })
7958            .await
7959            .unwrap();
7960            assert_eq!(reads(), before, "the store was read");
7961            assert!(!fetcher.inner.has_trust_anchors);
7962            let refused = within(
7963                Duration::from_secs(1),
7964                fetcher.fetch(FetchRequest::url("https://127.0.0.1:1/summary")),
7965            )
7966            .await
7967            .expect("the refusal takes no attempt")
7968            .expect_err("a tls url is refused without anchors");
7969            assert!(
7970                refused.to_string().contains("no trust anchors"),
7971                "{refused}"
7972            );
7973
7974            let cases = [
7975                direct_options("http://cleartext.example/repo"),
7976                FetcherOptions {
7977                    max_redirects: 0,
7978                    ..direct_options("https://tls.example/repo")
7979                },
7980                FetcherOptions {
7981                    max_redirects: 0,
7982                    proxy: Proxy::None,
7983                    ..FetcherOptions::default()
7984                },
7985            ];
7986            for options in cases {
7987                let before = reads();
7988                let what = format!("{:?} {}", options.mirrors, options.max_redirects);
7989                // A host with no CA bundle fails the `https` cases, after the
7990                // read.
7991                let _ = Fetcher::new(options).await;
7992                assert_eq!(reads(), before + 1, "{what}");
7993            }
7994        });
7995    }
7996
7997    /// The server chooses the origin of a redirect. So a hop to a TLS origin
7998    /// gets the refusal that a route to a TLS origin gets. The fetcher holds
7999    /// nothing to verify the certificate against. With no refusal, the
8000    /// handshake fails retryably with a message about the peer, and spends
8001    /// each round and each backoff.
8002    ///
8003    /// The test sets the flag by hand, for the reason that
8004    /// `a_tls_destination_needs_a_trust_anchor` states.
8005    ///
8006    /// The two peers are raw sockets: one answers a redirect to the other, and
8007    /// the other reports how many connections reached it.
8008    #[test]
8009    fn a_redirect_to_a_tls_origin_needs_a_trust_anchor() {
8010        use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
8011        use std::sync::atomic::{AtomicUsize, Ordering};
8012
8013        rt::block_on(async {
8014            // The origin that the redirect names. Nothing connects to it, and
8015            // the count reports this.
8016            let tls_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
8017                .await
8018                .unwrap();
8019            let tls_port = tls_peer.local_addr().unwrap().port();
8020            let connections = Arc::new(AtomicUsize::new(0));
8021            let counted = connections.clone();
8022            drop(rt::spawn(async move {
8023                while let Ok((stream, _peer)) = tls_peer.accept().await {
8024                    counted.fetch_add(1, Ordering::SeqCst);
8025                    drop(stream);
8026                }
8027            }));
8028
8029            let cleartext_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
8030                .await
8031                .unwrap();
8032            let cleartext_port = cleartext_peer.local_addr().unwrap().port();
8033            let requests = Arc::new(AtomicUsize::new(0));
8034            let counted = requests.clone();
8035            drop(rt::spawn(async move {
8036                while let Ok((mut stream, _peer)) = cleartext_peer.accept().await {
8037                    let mut request = [0u8; 1024];
8038                    let _ = stream.read(&mut request).await;
8039                    counted.fetch_add(1, Ordering::SeqCst);
8040                    let answer = format!(
8041                        "HTTP/1.1 302 Found\r\nLocation: https://127.0.0.1:{tls_port}/hopped\r\n\
8042                         Content-Length: 0\r\n\r\n"
8043                    );
8044                    let _ = stream.write_all(answer.as_bytes()).await;
8045                    let _ = stream.flush().await;
8046                }
8047            }));
8048
8049            let mut fetcher =
8050                Fetcher::new(direct_options(format!("http://127.0.0.1:{cleartext_port}")))
8051                    .await
8052                    .unwrap();
8053            Arc::get_mut(&mut fetcher.inner)
8054                .expect("the one handle on this fetcher")
8055                .has_trust_anchors = false;
8056
8057            // Six rounds of a retryable handshake failure and their backoffs
8058            // run for more than five seconds. So only a refusal that ends the
8059            // attempt resolves inside this window.
8060            let refused = within(
8061                Duration::from_secs(2),
8062                fetcher.fetch(FetchRequest::path("summary")),
8063            )
8064            .await;
8065            let err = refused
8066                .expect("the refusal ends the attempt")
8067                .expect_err("a tls hop is refused without anchors");
8068            let message = err.to_string();
8069            assert!(
8070                message.contains(&format!("https://127.0.0.1:{tls_port}")),
8071                "{message}"
8072            );
8073            assert!(message.contains("no trust anchors"), "{message}");
8074            assert_eq!(requests.load(Ordering::SeqCst), 1);
8075            assert_eq!(connections.load(Ordering::SeqCst), 0);
8076        });
8077    }
8078
8079    /// The reading end of a channel body, taken out of the body as an upload
8080    /// takes it.
8081    fn channel() -> (BodyEnd, UploadWriter) {
8082        let (body, writer) = UploadBody::channel();
8083        let UploadForm::Channel(end) = body.form else {
8084            panic!("a channel body holds its reading end");
8085        };
8086        (end, writer)
8087    }
8088
8089    /// The next frame of `end`, as the bytes it carries.
8090    async fn next_frame(end: &mut BodyEnd) -> Option<std::io::Result<Bytes>> {
8091        let frame = std::future::poll_fn(|cx| end.poll_frame(cx)).await?;
8092        Some(frame.map(|frame| frame.into_data().expect("an upload body yields data")))
8093    }
8094
8095    /// The writer hands the body over in frames of 64 KiB, a close hands over
8096    /// what is left, and the end follows the last frame. The close completes
8097    /// when the reading end gives the end.
8098    #[test]
8099    fn a_writer_hands_over_frames_of_64_kib() {
8100        rt::block_on(async {
8101            let (mut end, mut writer) = channel();
8102            let data = (0..150_000u32).map(|i| i as u8).collect::<Vec<_>>();
8103            let written = async {
8104                futures_lite::io::AsyncWriteExt::write_all(&mut writer, &data).await?;
8105                futures_lite::io::AsyncWriteExt::close(&mut writer).await
8106            };
8107            let read = async {
8108                let mut frames = Vec::new();
8109                while let Some(frame) = next_frame(&mut end).await {
8110                    frames.push(frame.unwrap());
8111                }
8112                frames
8113            };
8114            let (written, frames) = futures_lite::future::zip(written, read).await;
8115            written.unwrap();
8116            assert_eq!(
8117                frames.iter().map(Bytes::len).collect::<Vec<_>>(),
8118                [UPLOAD_FRAME, UPLOAD_FRAME, 150_000 - 2 * UPLOAD_FRAME]
8119            );
8120            assert_eq!(frames.concat(), data);
8121            assert!(end.is_end_stream());
8122            assert!(end.exchange.lock().ended);
8123            assert_eq!(end.exchange.exact, None);
8124        });
8125    }
8126
8127    /// A flush hands over a part-filled frame, and completes when hyper takes
8128    /// it.
8129    #[test]
8130    fn a_flush_hands_over_a_part_filled_frame() {
8131        rt::block_on(async {
8132            let (mut end, mut writer) = channel();
8133            let flushed = async {
8134                futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"hello").await?;
8135                futures_lite::io::AsyncWriteExt::flush(&mut writer).await
8136            };
8137            let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
8138            flushed.unwrap();
8139            assert_eq!(frame.unwrap().unwrap(), &b"hello"[..]);
8140            assert!(!end.is_end_stream());
8141        });
8142    }
8143
8144    /// A writer reports the hand-over of its request, and a request given
8145    /// back unwritten is no longer handed over.
8146    #[test]
8147    fn a_writer_reports_the_hand_over() {
8148        let (end, writer) = channel();
8149        assert!(!writer.is_handed_over());
8150        end.exchange.hand_over(Duration::from_secs(1)).unwrap();
8151        assert!(writer.is_handed_over());
8152        end.exchange.withdraw();
8153        assert!(!writer.is_handed_over());
8154    }
8155
8156    /// A writer holds no buffer until its first write. A flush of less than
8157    /// 4 KiB hands over a copy and keeps the frame buffer. A larger flush
8158    /// hands the buffer over, and the next one is allocated at the next
8159    /// write.
8160    #[test]
8161    fn a_small_flush_hands_over_a_copy_and_keeps_the_buffer() {
8162        rt::block_on(async {
8163            let (mut end, mut writer) = channel();
8164            assert_eq!(writer.buffer.capacity(), 0);
8165            futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"small")
8166                .await
8167                .unwrap();
8168            assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
8169            let kept = writer.buffer.as_ptr();
8170            let flushed = futures_lite::io::AsyncWriteExt::flush(&mut writer);
8171            let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
8172            flushed.unwrap();
8173            assert_eq!(frame.unwrap().unwrap(), &b"small"[..]);
8174            assert!(writer.buffer.is_empty());
8175            assert_eq!(writer.buffer.as_ptr(), kept);
8176            assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
8177
8178            let large = vec![7u8; SMALL_FRAME];
8179            let flushed = async {
8180                futures_lite::io::AsyncWriteExt::write_all(&mut writer, &large).await?;
8181                futures_lite::io::AsyncWriteExt::flush(&mut writer).await
8182            };
8183            let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
8184            flushed.unwrap();
8185            assert_eq!(frame.unwrap().unwrap(), large);
8186            assert_eq!(writer.buffer.capacity(), 0);
8187            futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
8188                .await
8189                .unwrap();
8190            assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
8191        });
8192    }
8193
8194    /// A writer dropped before close fails the body, so hyper never reads a
8195    /// clean end for a body cut short.
8196    #[test]
8197    fn a_writer_dropped_unclosed_fails_the_body() {
8198        rt::block_on(async {
8199            let (mut end, mut writer) = channel();
8200            futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"part")
8201                .await
8202                .unwrap();
8203            drop(writer);
8204            let err = next_frame(&mut end).await.unwrap().unwrap_err();
8205            assert!(err.to_string().contains("dropped"), "{err}");
8206            assert!(!end.is_end_stream());
8207            assert!(!end.exchange.lock().ended);
8208            // The failure stands for every later poll.
8209            assert!(next_frame(&mut end).await.unwrap().is_err());
8210        });
8211    }
8212
8213    /// Once the reading end is gone, a write, a flush, and a close fail with
8214    /// a broken pipe.
8215    #[test]
8216    fn a_write_after_the_reading_end_is_gone_is_a_broken_pipe() {
8217        rt::block_on(async {
8218            let (end, mut writer) = channel();
8219            drop(end);
8220            let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"late")
8221                .await
8222                .unwrap_err();
8223            assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
8224            let err = futures_lite::io::AsyncWriteExt::flush(&mut writer)
8225                .await
8226                .unwrap_err();
8227            assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
8228        });
8229    }
8230
8231    /// A write after close is a broken pipe.
8232    #[test]
8233    fn a_write_after_close_is_a_broken_pipe() {
8234        rt::block_on(async {
8235            let (mut end, mut writer) = channel();
8236            let closed = futures_lite::io::AsyncWriteExt::close(&mut writer);
8237            let (closed, frame) = futures_lite::future::zip(closed, next_frame(&mut end)).await;
8238            closed.unwrap();
8239            assert!(frame.is_none());
8240            let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
8241                .await
8242                .unwrap_err();
8243            assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
8244        });
8245    }
8246
8247    /// A frame that waits in the slot past the stall window fails the write
8248    /// with a timeout, and fails the body. The failure is latched. Before
8249    /// an upload starts the window, a full slot is no stall.
8250    #[test]
8251    fn a_frame_not_taken_within_the_window_fails_the_write() {
8252        rt::block_on(async {
8253            let (mut end, mut writer) = channel();
8254            let frame = vec![0u8; UPLOAD_FRAME];
8255            // The first frame fills the buffer, the second hands it to the
8256            // slot, and the third waits for the slot.
8257            for _ in 0..2 {
8258                futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame)
8259                    .await
8260                    .unwrap();
8261            }
8262            let unbounded = within(
8263                Duration::from_millis(100),
8264                futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame),
8265            )
8266            .await;
8267            assert!(unbounded.is_none(), "a wait before the upload has no bound");
8268
8269            end.exchange.hand_over(Duration::from_millis(50)).unwrap();
8270            let started = Instant::now();
8271            let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame)
8272                .await
8273                .unwrap_err();
8274            assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
8275            assert!(started.elapsed() >= Duration::from_millis(50));
8276            let again = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
8277                .await
8278                .unwrap_err();
8279            assert_eq!(again.kind(), std::io::ErrorKind::TimedOut);
8280            let failed = next_frame(&mut end).await.unwrap().unwrap_err();
8281            assert!(failed.to_string().contains("not taken"), "{failed}");
8282        });
8283    }
8284
8285    /// A body given whole declares its length and travels in frames of 64 KiB
8286    /// cut from its bytes with no copy. It reaches its end with the last
8287    /// frame. An empty body is at its end at the hand-over. The hand-over
8288    /// reports this, so the request can declare a length of zero.
8289    #[test]
8290    fn a_whole_body_travels_in_frames_of_a_declared_length() {
8291        rt::block_on(async {
8292            let bytes = Bytes::from((0..150_000u32).map(|i| i as u8).collect::<Vec<_>>());
8293            let mut end = BodyEnd::whole(&bytes);
8294            assert_eq!(end.exchange.exact, Some(150_000));
8295            assert_eq!(end.exchange.hand_over(Duration::from_secs(60)), Ok(false));
8296            assert!(!end.is_end_stream());
8297            let mut at = 0;
8298            for len in [UPLOAD_FRAME, UPLOAD_FRAME, 150_000 - 2 * UPLOAD_FRAME] {
8299                assert!(!end.exchange.lock().ended);
8300                let frame = next_frame(&mut end).await.unwrap().unwrap();
8301                assert_eq!(frame.len(), len);
8302                assert_eq!(frame.as_ptr(), bytes[at..].as_ptr());
8303                at += len;
8304            }
8305            assert!(end.exchange.lock().ended);
8306            assert!(end.is_end_stream());
8307            assert!(next_frame(&mut end).await.is_none());
8308
8309            let empty = BodyEnd::whole(&Bytes::new());
8310            assert_eq!(empty.exchange.exact, Some(0));
8311            assert!(!empty.is_end_stream());
8312            assert_eq!(empty.exchange.hand_over(Duration::from_secs(60)), Ok(true));
8313            assert!(empty.is_end_stream());
8314            assert!(empty.exchange.lock().ended);
8315        });
8316    }
8317
8318    /// A channel body that reaches its end after the hand-over is framed as a
8319    /// stream: hyper learns of the end from its first poll.
8320    #[test]
8321    fn a_body_closed_after_the_hand_over_ends_at_the_first_poll() {
8322        rt::block_on(async {
8323            let (mut end, mut writer) = channel();
8324            assert_eq!(end.exchange.hand_over(Duration::from_secs(60)), Ok(false));
8325            end.exchange.lock().closed = true;
8326            assert!(!end.is_end_stream());
8327            assert!(next_frame(&mut end).await.is_none());
8328            assert!(end.is_end_stream());
8329            futures_lite::io::AsyncWriteExt::close(&mut writer)
8330                .await
8331                .unwrap();
8332        });
8333    }
8334
8335    /// The timer of a window whose end moves later is armed once, fires at
8336    /// the first end, and is armed again for the rest alone.
8337    #[test]
8338    fn a_lazy_timer_fires_at_the_end_it_was_moved_to() {
8339        rt::block_on(async {
8340            let mut timer = None;
8341            let started = Instant::now();
8342            let mut end = started + Duration::from_millis(50);
8343            std::future::poll_fn(|cx| {
8344                if poll_until(&mut timer, cx, end).is_pending() {
8345                    end = started + Duration::from_millis(120);
8346                    return Poll::Pending;
8347                }
8348                Poll::Ready(())
8349            })
8350            .await;
8351            assert!(started.elapsed() >= Duration::from_millis(120));
8352            assert!(timer.is_none());
8353        });
8354    }
8355
8356    /// A bearer token holds the token68 syntax, and a refusal names no part
8357    /// of it. The bearer and the Basic values are marked sensitive, and so is
8358    /// a credential header the caller sets.
8359    #[test]
8360    fn a_bearer_token_is_token68_and_sensitive() {
8361        let token = |token: &str| BearerToken {
8362            token: token.to_owned(),
8363        };
8364        for good in ["abc", "a-b.c_d~e+f/g", "dGVzdA==", "x="] {
8365            assert!(is_token68(good), "{good}");
8366        }
8367        for bad in ["", "=", "a b", "a=b", "tök", "a\n", "a,b"] {
8368            assert!(!is_token68(bad), "{bad:?}");
8369            let err = merge_headers(&[], &[], None, Some(&token(bad))).unwrap_err();
8370            let message = err.to_string();
8371            assert!(message.contains("token68"), "{message}");
8372            assert!(!message.contains("  "), "{message}");
8373            if !bad.is_empty() && bad != "=" {
8374                assert!(!message.contains(bad), "{message}");
8375            }
8376        }
8377
8378        let authorization = |headers: &[(HeaderName, HeaderValue)]| {
8379            headers
8380                .iter()
8381                .find(|(name, _)| *name == hyper::header::AUTHORIZATION)
8382                .map(|(_, value)| value.clone())
8383                .unwrap()
8384        };
8385        let merged = merge_headers(&[], &[], None, Some(&token("t0k3n"))).unwrap();
8386        let value = authorization(&merged);
8387        assert_eq!(value, "Bearer t0k3n");
8388        assert!(value.is_sensitive());
8389
8390        let auth = BasicAuth {
8391            user: "u".into(),
8392            password: "p".into(),
8393        };
8394        let merged = merge_headers(&[], &[], Some(&auth), None).unwrap();
8395        assert!(authorization(&merged).is_sensitive());
8396        let header = vec![("authorization".to_owned(), "Custom x".to_owned())];
8397        let merged = merge_headers(&[], &header, None, None).unwrap();
8398        assert!(authorization(&merged).is_sensitive());
8399
8400        let err = merge_headers(&[], &[], Some(&auth), Some(&token("t"))).unwrap_err();
8401        assert!(err.to_string().contains("pass one of them"), "{err}");
8402        assert!(err.to_string().contains("bearer token"), "{err}");
8403        let err = merge_headers(&[], &header, None, Some(&token("t"))).unwrap_err();
8404        assert!(err.to_string().contains("pass one of them"), "{err}");
8405        assert!(err.to_string().contains("bearer token"), "{err}");
8406    }
8407
8408    #[test]
8409    fn bearer_token_debug_holds_no_token() {
8410        let token = BearerToken {
8411            token: "s3cret".into(),
8412        };
8413        let rendered = format!("{token:?}");
8414        assert!(!rendered.contains("s3cret"), "{rendered}");
8415        assert!(rendered.contains("redacted"), "{rendered}");
8416    }
8417
8418    /// The bearer token of the fetcher is one sensitive `Authorization` entry
8419    /// in the header list. A request without a credential sends it. Each of
8420    /// these replaces it for one request: the `basic_auth` of the request, the
8421    /// `bearer_token` of the request, or an `Authorization` header of the
8422    /// request.
8423    #[test]
8424    fn a_fetcher_bearer_token_joins_the_header_list() {
8425        let options = FetcherOptions {
8426            bearer_token: Some(BearerToken {
8427                token: "t0k3n".into(),
8428            }),
8429            ..tls_options("https://example.com")
8430        };
8431        let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
8432        let authorization = |headers: &[(HeaderName, HeaderValue)]| {
8433            headers
8434                .iter()
8435                .filter(|(name, _)| *name == hyper::header::AUTHORIZATION)
8436                .map(|(_, value)| value.clone())
8437                .collect::<Vec<_>>()
8438        };
8439        let held = authorization(&fetcher.inner.headers);
8440        assert_eq!(held, ["Bearer t0k3n"]);
8441        assert!(held[0].is_sensitive());
8442
8443        let extra = vec![("x-trace".to_owned(), "abc".to_owned())];
8444        let merged = merge_headers(&fetcher.inner.headers, &extra, None, None).unwrap();
8445        assert_eq!(authorization(&merged), ["Bearer t0k3n"]);
8446
8447        // base64("u:p")
8448        let auth = BasicAuth {
8449            user: "u".into(),
8450            password: "p".into(),
8451        };
8452        let merged = merge_headers(&fetcher.inner.headers, &[], Some(&auth), None).unwrap();
8453        assert_eq!(authorization(&merged), ["Basic dTpw"]);
8454        let token = BearerToken {
8455            token: "other".into(),
8456        };
8457        let merged = merge_headers(&fetcher.inner.headers, &[], None, Some(&token)).unwrap();
8458        assert_eq!(authorization(&merged), ["Bearer other"]);
8459        let header = vec![("authorization".to_owned(), "Custom x".to_owned())];
8460        let merged = merge_headers(&fetcher.inner.headers, &header, None, None).unwrap();
8461        assert_eq!(authorization(&merged), ["Custom x"]);
8462    }
8463
8464    /// The constructor refuses the bearer token of the fetcher beside another
8465    /// value for `Authorization`, and a token outside the token68 syntax. A
8466    /// refusal names no part of the token.
8467    #[test]
8468    fn a_fetcher_bearer_token_is_refused_beside_another_credential_or_out_of_syntax() {
8469        let token = |token: &str| {
8470            Some(BearerToken {
8471                token: token.to_owned(),
8472            })
8473        };
8474        let beside_basic = FetcherOptions {
8475            bearer_token: token("t0k3n"),
8476            basic_auth: Some(BasicAuth {
8477                user: "u".into(),
8478                password: "p".into(),
8479            }),
8480            ..tls_options("https://example.com")
8481        };
8482        let beside_header = FetcherOptions {
8483            bearer_token: token("t0k3n"),
8484            headers: vec![("authorization".into(), "Basic aaa".into())],
8485            ..tls_options("https://example.com")
8486        };
8487        for options in [beside_basic, beside_header] {
8488            let err = rt::block_on(Fetcher::new(options)).unwrap_err();
8489            let message = err.to_string();
8490            assert!(message.contains("bearer token"), "{message}");
8491            assert!(message.contains("pass one of them"), "{message}");
8492        }
8493
8494        let options = FetcherOptions {
8495            bearer_token: token("not a token"),
8496            ..tls_options("https://example.com")
8497        };
8498        let err = rt::block_on(Fetcher::new(options)).unwrap_err();
8499        assert!(matches!(err, Error::Fetch(_)), "{err}");
8500        let message = err.to_string();
8501        assert!(message.contains("token68"), "{message}");
8502        assert!(!message.contains("not a token"), "{message}");
8503    }
8504
8505    /// A credential of the fetcher fails the constructor beside a cleartext
8506    /// mirror. The cleartext permission of the fetcher admits each kind of
8507    /// credential.
8508    #[test]
8509    fn the_fetcher_cleartext_permission_admits_a_cleartext_mirror() {
8510        let cleartext = "http://cleartext.example/repo";
8511        let token = || {
8512            Some(BearerToken {
8513                token: "t0k3n".into(),
8514            })
8515        };
8516        let options = FetcherOptions {
8517            bearer_token: token(),
8518            ..tls_options(cleartext)
8519        };
8520        let err = rt::block_on(Fetcher::new(options)).unwrap_err();
8521        let message = err.to_string();
8522        assert!(message.contains("bearer token"), "{message}");
8523        assert!(message.contains(cleartext), "{message}");
8524        assert!(
8525            message.contains("FetcherOptions::allow_cleartext_credentials"),
8526            "{message}"
8527        );
8528        assert!(!message.contains("t0k3n"), "{message}");
8529
8530        let options = FetcherOptions {
8531            bearer_token: token(),
8532            allow_cleartext_credentials: true,
8533            ..tls_options(cleartext)
8534        };
8535        let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
8536        assert!(
8537            fetcher.inner.headers.iter().any(
8538                |(name, value)| name == hyper::header::AUTHORIZATION && value == "Bearer t0k3n"
8539            )
8540        );
8541
8542        let options = FetcherOptions {
8543            basic_auth: Some(BasicAuth {
8544                user: "u".into(),
8545                password: "p".into(),
8546            }),
8547            allow_cleartext_credentials: true,
8548            ..tls_options(cleartext)
8549        };
8550        rt::block_on(Fetcher::new(options)).unwrap();
8551        let options = FetcherOptions {
8552            headers: vec![("cookie".into(), "session=1".into())],
8553            allow_cleartext_credentials: true,
8554            ..tls_options(cleartext)
8555        };
8556        rt::block_on(Fetcher::new(options)).unwrap();
8557    }
8558
8559    #[test]
8560    fn fetcher_options_debug_holds_no_bearer_token() {
8561        let options = FetcherOptions {
8562            bearer_token: Some(BearerToken {
8563                token: "s3cret".into(),
8564            }),
8565            ..FetcherOptions::default()
8566        };
8567        let rendered = format!("{options:?}");
8568        assert!(!rendered.contains("s3cret"), "{rendered}");
8569        assert!(rendered.contains("redacted"), "{rendered}");
8570    }
8571
8572    /// Headers whose values hold the marker `QXZ`, which no `Debug` output
8573    /// shows.
8574    fn secret_headers() -> Vec<(String, String)> {
8575        vec![
8576            ("Authorization".into(), "Basic val-QXZ-1".into()),
8577            ("proxy-authorization".into(), "Basic val-QXZ-2".into()),
8578            ("cookie".into(), "id=val-QXZ-3".into()),
8579            ("X-Trace".into(), "val-QXZ-4".into()),
8580        ]
8581    }
8582
8583    /// The `Debug` output of the headers of [`secret_headers`].
8584    const SECRET_HEADERS_SHOWN: &str = r#"[("Authorization", "<redacted>"), ("proxy-authorization", "<redacted>"), ("cookie", "<redacted>"), ("X-Trace", "<redacted>")]"#;
8585
8586    /// Checks that `rendered` shows each header of [`secret_headers`] with
8587    /// `<redacted>`, and no header value.
8588    fn assert_no_header_value(rendered: &str) {
8589        assert!(!rendered.contains("QXZ"), "{rendered}");
8590        for (name, _) in secret_headers() {
8591            let entry = format!(r#"("{name}", "<redacted>")"#);
8592            assert!(rendered.contains(&entry), "{rendered}");
8593        }
8594    }
8595
8596    /// The `Debug` output of the options shows each header name and no header
8597    /// value. Each other field shows as its own `Debug` shows it, in the order
8598    /// of declaration.
8599    #[test]
8600    fn fetcher_options_debug_holds_no_header_value() {
8601        let options = FetcherOptions {
8602            headers: secret_headers(),
8603            ..FetcherOptions::new("https://example.com/")
8604        };
8605        let rendered = format!("{options:?}");
8606        assert_no_header_value(&rendered);
8607        assert_eq!(
8608            rendered,
8609            format!(
8610                "FetcherOptions {{ mirrors: [\"https://example.com/\"], \
8611                 headers: {SECRET_HEADERS_SHOWN}, basic_auth: None, bearer_token: None, \
8612                 allow_cleartext_credentials: false, \
8613                 tls: TlsOptions {{ roots: System, client_identity: None }}, \
8614                 proxy: Environment, http2: true, max_retries: 5, max_redirects: 10, \
8615                 max_outstanding: 8, connect_timeout: 30s, progress_timeout: 60s, \
8616                 low_speed: None, fetch_timeout: Some(300s) }}"
8617            )
8618        );
8619    }
8620
8621    /// The `Debug` output of a fetch request shows each header name and no
8622    /// header value. Each other field shows as its own `Debug` shows it.
8623    #[test]
8624    fn fetch_request_debug_holds_no_header_value() {
8625        let headers = secret_headers();
8626        let request = FetchRequest {
8627            headers: &headers,
8628            ..FetchRequest::path("summary")
8629        };
8630        let rendered = format!("{request:?}");
8631        assert_no_header_value(&rendered);
8632        assert_eq!(
8633            rendered,
8634            format!(
8635                "FetchRequest {{ target: Path(\"summary\"), priority: Normal, \
8636                 validators: None, max_size: None, headers: {SECRET_HEADERS_SHOWN}, \
8637                 basic_auth: None, allow_cleartext_credentials: false }}"
8638            )
8639        );
8640    }
8641
8642    /// The `Debug` output of an upload request shows each header name and no
8643    /// header value. Each other field shows as its own `Debug` shows it.
8644    #[test]
8645    fn upload_request_debug_holds_no_header_value() {
8646        let headers = secret_headers();
8647        let request = UploadRequest {
8648            headers: &headers,
8649            ..UploadRequest::path("objects", UploadBody::bytes(Vec::new()))
8650        };
8651        let rendered = format!("{request:?}");
8652        assert_no_header_value(&rendered);
8653        assert_eq!(
8654            rendered,
8655            format!(
8656                "UploadRequest {{ target: Path(\"objects\"), method: Post, body: Bytes(0), \
8657                 priority: Normal, max_response: 2097152, headers: {SECRET_HEADERS_SHOWN}, \
8658                 basic_auth: None, bearer_token: None, allow_cleartext_credentials: false, \
8659                 response_timeout: None }}"
8660            )
8661        );
8662    }
8663
8664    /// Starts a raw socket peer that answers each request with fixed headers,
8665    /// and gives a fetcher with the peer as its mirror, and the port of the
8666    /// peer.
8667    ///
8668    /// Each header value holds the marker `QXZ`.
8669    async fn fixed_header_peer() -> (Fetcher, u16) {
8670        use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
8671
8672        let peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
8673            .await
8674            .unwrap();
8675        let port = peer.local_addr().unwrap().port();
8676        drop(rt::spawn(async move {
8677            while let Ok((mut stream, _peer)) = peer.accept().await {
8678                let mut request = [0u8; 1024];
8679                let _ = stream.read(&mut request).await;
8680                let answer = "HTTP/1.1 200 OK\r\nSet-Cookie: a=val-QXZ-5\r\n\
8681                              Set-Cookie: b=val-QXZ-6\r\nContent-Type: text/val-QXZ-7\r\n\
8682                              Content-Length: 0\r\n\r\n";
8683                let _ = stream.write_all(answer.as_bytes()).await;
8684                let _ = stream.flush().await;
8685            }
8686        }));
8687
8688        // With no redirect and a cleartext mirror, the fetcher reads no system
8689        // trust store.
8690        let fetcher = Fetcher::new(FetcherOptions {
8691            max_redirects: 0,
8692            ..direct_options(format!("http://127.0.0.1:{port}"))
8693        })
8694        .await
8695        .unwrap();
8696        (fetcher, port)
8697    }
8698
8699    /// The `Debug` output of an upload answer shows the name of each response
8700    /// header, once for each value, and no header value.
8701    #[test]
8702    fn uploaded_debug_holds_no_header_value() {
8703        rt::block_on(async {
8704            let (fetcher, port) = fixed_header_peer().await;
8705            let uploaded = within(
8706                Duration::from_secs(5),
8707                fetcher.upload(UploadRequest::path(
8708                    "objects",
8709                    UploadBody::bytes(Vec::new()),
8710                )),
8711            )
8712            .await
8713            .expect("the upload ends within the limit")
8714            .unwrap();
8715            let rendered = format!("{uploaded:?}");
8716            assert!(!rendered.contains("QXZ"), "{rendered}");
8717            let headers = r#"[("set-cookie", "<redacted>"), ("set-cookie", "<redacted>"), ("content-type", "<redacted>"), ("content-length", "<redacted>")]"#;
8718            assert_eq!(
8719                rendered,
8720                format!(
8721                    "Uploaded {{ status: 200, headers: {headers}, \
8722                     url: \"http://127.0.0.1:{port}/objects\", body: Body {{ \
8723                     protocol: Http11, content_length: Some(0), received: 0, .. }} }}"
8724                )
8725            );
8726        });
8727    }
8728
8729    /// The `Debug` output of an upload answer shows the host and the path of
8730    /// its URL, and `<redacted>` in place of the query.
8731    #[test]
8732    fn uploaded_debug_holds_no_url_query() {
8733        rt::block_on(async {
8734            let (fetcher, port) = fixed_header_peer().await;
8735            let url = format!("http://127.0.0.1:{port}/objects?X-Amz-Signature=sig-QXZ");
8736            let uploaded = within(
8737                Duration::from_secs(5),
8738                fetcher.upload(UploadRequest::url(&url, UploadBody::bytes(Vec::new()))),
8739            )
8740            .await
8741            .expect("the upload ends within the limit")
8742            .unwrap();
8743            assert_eq!(uploaded.url(), url);
8744            let rendered = format!("{uploaded:?}");
8745            assert!(!rendered.contains("QXZ"), "{rendered}");
8746            assert!(
8747                rendered.contains(&format!(
8748                    "url: \"http://127.0.0.1:{port}/objects?<redacted>\""
8749                )),
8750                "{rendered}"
8751            );
8752        });
8753    }
8754
8755    /// For a text with no `@`, `?`, and `#`, the `Debug` output of a URL and
8756    /// of a path is the `Debug` output of the `str`.
8757    #[test]
8758    fn redacted_url_debug_quotes_as_str_debug() {
8759        let texts = [
8760            "https://example.com/it's",
8761            "a\"b\\c",
8762            "line\nnext\ttab\u{7f}",
8763            "caf\u{e9}",
8764            "\u{301}start",
8765            "mid\u{301}dle",
8766            "zero\u{200b}width",
8767            "emoji \u{1f980}",
8768            "",
8769        ];
8770        for text in texts {
8771            let expected = format!("{text:?}");
8772            assert_eq!(format!("{:?}", RedactedUrl::url(text)), expected);
8773            assert_eq!(format!("{:?}", RedactedUrl::path(text)), expected);
8774        }
8775    }
8776
8777    /// The `Debug` output of a URL removes the text up to the last `@` after
8778    /// the scheme, and shows `<redacted>` in place of a query and a fragment.
8779    /// A path keeps each `@`.
8780    #[test]
8781    fn redacted_url_debug_removes_userinfo_query_and_fragment() {
8782        let urls = [
8783            ("https://example.com/repo", "https://example.com/repo"),
8784            (
8785                "https://user:pw@example.com/repo",
8786                "https://example.com/repo",
8787            ),
8788            (
8789                "https://u:pa#ss@example.com/repo",
8790                "https://example.com/repo",
8791            ),
8792            (
8793                "https://u:pa?ss@example.com/repo",
8794                "https://example.com/repo",
8795            ),
8796            (
8797                "https://u:p/ss@example.com/repo",
8798                "https://example.com/repo",
8799            ),
8800            ("https://example.com/a@b/c", "https://b/c"),
8801            (
8802                "https://example.com/s?a=1",
8803                "https://example.com/s?<redacted>",
8804            ),
8805            (
8806                "https://example.com/s#f",
8807                "https://example.com/s#<redacted>",
8808            ),
8809            (
8810                "https://u:p@example.com/s?a=1#f",
8811                "https://example.com/s?<redacted>#<redacted>",
8812            ),
8813            ("https://example.com/s?", "https://example.com/s?<redacted>"),
8814            ("https://example.com/s#", "https://example.com/s#<redacted>"),
8815            (
8816                "https://example.com/s?#",
8817                "https://example.com/s?<redacted>#<redacted>",
8818            ),
8819            ("https://example.com/s?a=x@y&b=1", "https://y&b=1"),
8820            ("example.com/s?a=1", "example.com/s?<redacted>"),
8821            ("u:p@example.com/s", "example.com/s"),
8822            ("u:a://b@h/p", "h/p"),
8823            ("https://[::1]:8/p?q", "https://[::1]:8/p?<redacted>"),
8824            ("https://h/p#a?b", "https://h/p#<redacted>"),
8825            ("é@é?é#é", "é?<redacted>#<redacted>"),
8826        ];
8827        for (url, shown) in urls {
8828            assert_eq!(
8829                format!("{:?}", RedactedUrl::url(url)),
8830                format!("\"{shown}\"")
8831            );
8832        }
8833        let paths = [
8834            ("objects/ab", "objects/ab"),
8835            ("a@b/c", "a@b/c"),
8836            ("summary?sig=1", "summary?<redacted>"),
8837            ("summary#f", "summary#<redacted>"),
8838            ("summary?sig=1#f", "summary?<redacted>#<redacted>"),
8839        ];
8840        for (path, shown) in paths {
8841            assert_eq!(
8842                format!("{:?}", RedactedUrl::path(path)),
8843                format!("\"{shown}\"")
8844            );
8845        }
8846    }
8847
8848    /// The `Debug` output of a target alone shows the layout of a tuple
8849    /// variant, with the URL rule.
8850    #[test]
8851    fn target_debug_redacts_url_and_path() {
8852        let url = Target::Url("https://u:pw-QXZ@h/p?t=QXZ#QXZ");
8853        let path = Target::Path("summary?sig=QXZ#QXZ");
8854        assert_eq!(
8855            format!("{url:?}"),
8856            r#"Url("https://h/p?<redacted>#<redacted>")"#
8857        );
8858        assert_eq!(
8859            format!("{path:?}"),
8860            r#"Path("summary?<redacted>#<redacted>")"#
8861        );
8862        assert_eq!(
8863            format!("{url:#?}"),
8864            "Url(\n    \"https://h/p?<redacted>#<redacted>\",\n)"
8865        );
8866        assert_eq!(
8867            format!("{path:#?}"),
8868            "Path(\n    \"summary?<redacted>#<redacted>\",\n)"
8869        );
8870        let path_query = Target::PathQuery {
8871            path: "p?QXZ",
8872            query: "pattern=QXZ",
8873        };
8874        assert_eq!(
8875            format!("{path_query:?}"),
8876            r#"PathQuery { path: "p?<redacted>", query: "<redacted>" }"#
8877        );
8878        let rendered = format!("{:?}", FetchRequest::path_query("refs/v1", "pattern=QXZ"));
8879        assert!(!rendered.contains("QXZ"), "{rendered}");
8880        assert!(
8881            rendered.contains(r#"target: PathQuery { path: "refs/v1", query: "<redacted>" }"#),
8882            "{rendered}"
8883        );
8884    }
8885
8886    /// A URL that holds the marker `QXZ` in its userinfo, query, and fragment.
8887    const SECRET_URL: &str =
8888        "https://user-QXZ:pw-QXZ@example.com/repo?X-Amz-Signature=sig-QXZ#frag-QXZ";
8889
8890    /// The `Debug` output of the options shows the host and the path of each
8891    /// mirror, and no userinfo, query, or fragment.
8892    #[test]
8893    fn fetcher_options_debug_holds_no_mirror_secret() {
8894        let options = FetcherOptions {
8895            mirrors: vec![SECRET_URL.into(), "https://mirror.example.com/os".into()],
8896            ..FetcherOptions::default()
8897        };
8898        let rendered = format!("{options:?}");
8899        assert!(!rendered.contains("QXZ"), "{rendered}");
8900        assert!(
8901            rendered.contains(
8902                r#"mirrors: ["https://example.com/repo?<redacted>#<redacted>", "https://mirror.example.com/os"]"#
8903            ),
8904            "{rendered}"
8905        );
8906    }
8907
8908    /// The `Debug` output of a fetch request shows the host and the path of
8909    /// its target, and no userinfo, query, or fragment.
8910    #[test]
8911    fn fetch_request_debug_holds_no_target_secret() {
8912        let rendered = format!("{:?}", FetchRequest::url(SECRET_URL));
8913        assert!(!rendered.contains("QXZ"), "{rendered}");
8914        assert!(
8915            rendered.contains(r#"target: Url("https://example.com/repo?<redacted>#<redacted>")"#),
8916            "{rendered}"
8917        );
8918        let rendered = format!("{:?}", FetchRequest::path("summary?sig=QXZ#f"));
8919        assert!(!rendered.contains("QXZ"), "{rendered}");
8920        assert!(
8921            rendered.contains(r#"target: Path("summary?<redacted>#<redacted>")"#),
8922            "{rendered}"
8923        );
8924    }
8925
8926    /// The `Debug` output of an upload request shows the host and the path of
8927    /// its target, and no userinfo, query, or fragment.
8928    #[test]
8929    fn upload_request_debug_holds_no_target_secret() {
8930        let request = UploadRequest::url(SECRET_URL, UploadBody::bytes(Vec::new()));
8931        let rendered = format!("{request:?}");
8932        assert!(!rendered.contains("QXZ"), "{rendered}");
8933        assert!(
8934            rendered.contains(r#"target: Url("https://example.com/repo?<redacted>#<redacted>")"#),
8935            "{rendered}"
8936        );
8937    }
8938}