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`, `PUT`, or
9//! `DELETE`. A response body streams in bounded chunks, so no object is held
10//! whole in memory.
11//!
12//! The [`Target`] of a request is a path under each mirror, a path with a
13//! query string under each mirror, or an absolute URL. The fetcher sends a
14//! path and a query as written, so the caller escapes them. A fetcher with a
15//! [`RequestSigner`] sends a path in the form that
16//! [`RequestSigner::request_path`] gives.
17//!
18//! A failed fetch gives the status of the response. On request, it also gives
19//! the headers and a capped body of that response.
20//!
21//! # Entry points
22//!
23//! - [`Fetcher::new`] builds a fetcher from [`FetcherOptions`].
24//! - [`Fetcher::fetch`] sends a [`FetchRequest`] and returns a [`Fetched`].
25//! - [`ErrorResponse`] holds the headers and the capped body of an
26//! unsuccessful response, if the request asks for them.
27//! - [`Body`] streams a response body in bounded chunks.
28//! - [`Fetcher::refetching`] returns a [`Refetch`], which fetches a failed body again.
29//! - [`Fetcher::upload`] sends an [`UploadRequest`] and returns an [`Uploaded`].
30//! - [`UploadBody`] gives an upload body whole or streams it from an [`UploadWriter`].
31//! - [`RequestSigner`] signs each attempt through [`FetcherOptions::signer`],
32//! and gives the form of each request path.
33//! - [`Error`] is the error of each fallible operation of the crate.
34//!
35//! # Modules
36//!
37//! - [`gate`]: the priority admission gate that bounds concurrent work.
38//!
39//! # Features
40//!
41//! - `smol` (default): the `smol` backend of `ostrya-rt`.
42//! - `tokio`: the `tokio` backend of `ostrya-rt`, with tokio I/O impls on [`Body`] and [`UploadWriter`].
43//!
44//! # Examples
45//!
46//! ```no_run
47//! use futures_lite::AsyncReadExt;
48//! use ostrya_fetch::{FetchRequest, Fetched, Fetcher, FetcherOptions};
49//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
50//! let fetcher = Fetcher::new(FetcherOptions::new("https://example.com/repo")).await?;
51//! if let Fetched::Body(mut body) = fetcher.fetch(FetchRequest::path("config")).await? {
52//! let mut config = Vec::new();
53//! body.read_to_end(&mut config).await?;
54//! }
55//! # Ok(())
56//! # }
57//! ```
58
59use std::borrow::Cow;
60use std::collections::HashMap;
61use std::future::Future;
62use std::net::SocketAddr;
63use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
64use std::sync::{Arc, Mutex, MutexGuard};
65use std::time::{Duration, Instant};
66
67use futures_io::{AsyncRead, AsyncWrite};
68use hyper::body::{Body as _, Bytes, Frame, Incoming, SizeHint};
69use hyper::header::{HeaderName, HeaderValue};
70use hyper::http::uri::Scheme;
71use hyper::{Method, Request, Response, StatusCode, Uri, Version};
72use ostrya_rt as rt;
73use std::pin::Pin;
74use std::task::{Context, Poll, Waker, ready};
75
76mod error;
77pub mod gate;
78mod io;
79mod socks;
80mod tls;
81
82pub use self::error::{Error, Result};
83
84use gate::{Gate, Permit};
85#[doc(hidden)]
86pub use io::{FuturesIo, RtExecutor, RtTimer, WriteVectored};
87use tls::{ClientConfigs, client_config};
88pub use tls::{ClientIdentity, TlsOptions, TrustRoots};
89#[doc(hidden)]
90pub use tls::{client_cert_verifier, server_config};
91
92/// The `User-Agent` value of each request. A `User-Agent` header of the fetcher
93/// or of the request replaces it.
94const USER_AGENT: &str = concat!("ostrya/", env!("CARGO_PKG_VERSION"));
95
96/// The one content coding that a fetch accepts, which is no coding. Each
97/// request asks for it, and a response that declares another coding fails the
98/// attempt. An `Accept-Encoding` header of the fetcher or of the request
99/// replaces the value that the fetcher sends.
100const IDENTITY: &str = "identity";
101
102/// The one transfer coding that a response can declare. It frames a message,
103/// and the connection removes the framing, so the caller gets the body as the
104/// remote wrote it. The fetcher sends no `TE` header, so another transfer coding
105/// is a server fault. A response that declares one fails the attempt.
106const CHUNKED: &str = "chunked";
107
108/// The variables that [`Proxy::Environment`] reads, in the order of preference
109/// of a lookup.
110///
111/// The list holds the lower-case name of each variable, and the upper-case name
112/// where the lookup reads one. Nothing reads `HTTP_PROXY`. A CGI gateway gives a
113/// request header `Proxy` to the program as `HTTP_PROXY`, so a client can set
114/// that variable with a request.
115const PROXY_VARIABLES: [&str; 7] = [
116 "http_proxy",
117 "https_proxy",
118 "HTTPS_PROXY",
119 "all_proxy",
120 "ALL_PROXY",
121 "no_proxy",
122 "NO_PROXY",
123];
124
125/// The scheme of an HTTP proxy URL. An HTTP proxy connection opens with this
126/// scheme alone.
127const PROXY_SCHEME: &str = "http://";
128
129/// The scheme of a SOCKS5 proxy URL whose client resolves the origin host.
130const SOCKS5_SCHEME: &str = "socks5://";
131
132/// The scheme of a SOCKS5 proxy URL whose proxy resolves the origin host.
133const SOCKS5H_SCHEME: &str = "socks5h://";
134
135/// The statuses at which a fetch follows a redirect. A fetch is a GET, so none
136/// of the five changes the method of the next hop. The statuses that differ in
137/// the method are one case here. An upload follows [`UPLOAD_REDIRECTS`] alone.
138const REDIRECTS: [StatusCode; 5] = [
139 StatusCode::MOVED_PERMANENTLY,
140 StatusCode::FOUND,
141 StatusCode::SEE_OTHER,
142 StatusCode::TEMPORARY_REDIRECT,
143 StatusCode::PERMANENT_REDIRECT,
144];
145
146/// The statuses at which an upload follows a redirect. These two keep the
147/// method and the body, so the next hop sends the same request again.
148const UPLOAD_REDIRECTS: [StatusCode; 2] = [
149 StatusCode::TEMPORARY_REDIRECT,
150 StatusCode::PERMANENT_REDIRECT,
151];
152
153/// The message for a layer that sets both credentials and an `Authorization`
154/// header. The layer does not state which of the two the request sends. A
155/// choice of one sends a credential that the caller did not choose.
156const AMBIGUOUS_AUTHORIZATION: &str =
157 "basic-auth credentials and an authorization header both set Authorization: pass one of them";
158
159/// The message for a layer that sets both a bearer token and an
160/// `Authorization` header, for the reason that [`AMBIGUOUS_AUTHORIZATION`]
161/// states.
162const AMBIGUOUS_BEARER: &str =
163 "a bearer token and an authorization header both set Authorization: pass one of them";
164
165/// The message for a layer that sets both basic-auth credentials and a bearer
166/// token, for the reason that [`AMBIGUOUS_AUTHORIZATION`] states.
167const BASIC_AND_BEARER: &str =
168 "basic-auth credentials and a bearer token both set Authorization: pass one of them";
169
170/// The message for a fetcher that has a request signer, and basic-auth
171/// credentials on the fetcher or on a request. A signer sets the headers of
172/// its signature, which can include `Authorization`, so the reason of
173/// [`AMBIGUOUS_AUTHORIZATION`] applies.
174const SIGNER_AND_BASIC: &str =
175 "a request signer and basic-auth credentials both authorize the request: pass one of them";
176
177/// The message for a fetcher that has a request signer, and a bearer token on
178/// the fetcher or on a request, for the reason that [`SIGNER_AND_BASIC`]
179/// states.
180const SIGNER_AND_BEARER: &str =
181 "a request signer and a bearer token both authorize the request: pass one of them";
182
183/// The message for a fetcher that has a request signer, and an
184/// `Authorization` header on the fetcher or on a request, for the reason that
185/// [`SIGNER_AND_BASIC`] states.
186const SIGNER_AND_AUTHORIZATION: &str =
187 "a request signer and an authorization header both authorize the request: pass one of them";
188
189/// The message for a layer that sets a `Host` header. The header states the
190/// authority of the destination, and the fetcher reads it from the URL.
191const HOST_COMES_FROM_THE_URL: &str = "the host header is set from the url the request is sent to";
192
193/// The header names that the connection layer sets.
194///
195/// These names frame a request, or state what happens to the connection that
196/// carries it. A value of the caller puts the wire and the connection pool out
197/// of step. For example, a `Content-Length` of the caller ends the HTTP/1.1
198/// connection under a pooled sender. The next fetch over that fetcher then
199/// fails on a channel that the connection task dropped.
200const CONNECTION_HEADERS: [&str; 9] = [
201 "connection",
202 "content-length",
203 "expect",
204 "keep-alive",
205 "proxy-connection",
206 "te",
207 "trailer",
208 "transfer-encoding",
209 "upgrade",
210];
211
212/// The size of the frames of an upload body.
213///
214/// The writer fills one frame while the slot holds the frame that it handed
215/// over last, so the writer holds at most two frames. hyper takes a body given
216/// whole in frames of this size.
217///
218/// The connection buffers more of the body. Over HTTP/1.1, hyper takes another
219/// frame while it holds fewer than 16 frames and less than 408 KiB. Over HTTP/2,
220/// it holds up to two frames.
221const UPLOAD_FRAME: usize = 64 * 1024;
222
223/// The size under which a flush hands over a copy of its part-filled frame and
224/// keeps the buffer. So a small frame that waits in the connection does not hold
225/// a whole frame of memory.
226const SMALL_FRAME: usize = 4 * 1024;
227
228/// The longest idle time in the pool of an HTTP/1.1 connection that an upload
229/// takes. [`Inner::take_upload`] states why an upload takes only a connection
230/// that became idle a short time ago.
231const UPLOAD_IDLE: Duration = Duration::from_secs(2);
232
233/// The largest declared response body that a failed attempt reads to the end,
234/// so that its HTTP/1.1 connection goes back to the pool. If the declared length
235/// is larger, or if the response declares no length, the fetcher closes the
236/// connection.
237const DRAIN_LIMIT: u64 = 64 * 1024;
238
239/// The largest capacity that a kept error body reserves before its bytes
240/// arrive: 64 KiB. The declared length of the body is a claim of the server,
241/// so it does not size an allocation.
242const CAPTURE_RESERVE: u64 = 64 * 1024;
243
244/// The HTTP/2 flow-control window of each stream. The default of hyper is
245/// 64 KiB, which limits the throughput of one stream on a link with a high
246/// bandwidth-delay product. An object fetch is one stream, so this window limits
247/// it.
248const H2_STREAM_WINDOW: u32 = 2 * 1024 * 1024;
249
250/// The largest flow-control window the protocol allows, 2^31 - 1.
251const H2_MAX_WINDOW: u32 = i32::MAX as u32;
252
253/// How often an HTTP/2 connection with an open stream pings its peer, and how
254/// long it waits for the reply. Both values are less than the default
255/// [`progress_timeout`](FetcherOptions::progress_timeout). So the ping reports a
256/// peer that went away, and no read waits for ever.
257const H2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15);
258const H2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(15);
259
260/// The priority of a request that waits for admission to a [`Fetcher`].
261///
262/// If [`max_outstanding`](FetcherOptions::max_outstanding) requests are in
263/// flight, a new request waits in a queue. The queue serves the highest
264/// priority first, and requests of one priority in arrival order. The
265/// [`gate`] module holds the queue.
266#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
267pub enum Priority {
268 /// The lowest priority, for bulk content.
269 Low,
270 /// The middle priority, which is the default.
271 #[default]
272 Normal,
273 /// The highest priority, for metadata that other work waits for.
274 High,
275}
276
277/// The HTTP version of a response.
278#[derive(Clone, Copy, Debug, Eq, PartialEq)]
279pub enum Protocol {
280 /// HTTP/1.1.
281 Http11,
282 /// HTTP/2.
283 Http2,
284}
285
286/// The credentials of HTTP basic authentication.
287///
288/// The [`Debug`] output shows the user name and a fixed word in place of the
289/// password. So the log of a struct that holds credentials does not show the
290/// password.
291#[derive(Clone, Eq, PartialEq)]
292pub struct BasicAuth {
293 /// The user name.
294 pub user: String,
295 /// The password.
296 pub password: String,
297}
298
299impl std::fmt::Debug for BasicAuth {
300 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
301 f.debug_struct("BasicAuth")
302 .field("user", &self.user)
303 .field("password", &"<redacted>")
304 .finish()
305 }
306}
307
308/// A token for `Authorization: Bearer`.
309///
310/// The fetcher sends the token as written, so the token must have the token68
311/// syntax of HTTP authentication. This is one or more ASCII letters, digits,
312/// `-`, `.`, `_`, `~`, `+`, or `/`, then any number of `=`. If the token has
313/// another form, [`Error::Fetch`] occurs. A request fails before admission, and
314/// [`FetcherOptions::bearer_token`] fails [`Fetcher::new`]. The message holds
315/// no part of the token.
316///
317/// The [`Debug`] output shows a fixed word in place of the token. So the log of
318/// a struct that holds a token does not show it.
319#[derive(Clone, Eq, PartialEq)]
320pub struct BearerToken {
321 /// The token.
322 pub token: String,
323}
324
325impl std::fmt::Debug for BearerToken {
326 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327 f.debug_struct("BearerToken")
328 .field("token", &"<redacted>")
329 .finish()
330 }
331}
332
333/// A signer that adds the headers of a request signature to each attempt.
334///
335/// [`FetcherOptions::signer`] holds the signer of a fetcher. The fetcher calls
336/// [`sign`](RequestSigner::sign) once for each request that it sends to the
337/// origin that the route names. This includes each retry, each round, and
338/// each redirect hop at that origin. The call occurs after the fetcher takes
339/// the connection, so a signature with a date is fresh when the request
340/// leaves. An upload over a pooled HTTP/1.1 connection that the server closed
341/// continues over a new connection, and the fetcher calls the signer again.
342///
343/// A redirect hop at another origin gets no signature. No later hop of that
344/// attempt gets one, also a hop back to the named origin.
345///
346/// The fetcher calls the signer on the task of the request. A signer that
347/// hashes a body given whole does that work on the task, on each call. A
348/// caller with a large body gives the SHA-256 of the body with
349/// [`UploadBody::bytes_with_sha256`], so that the signer gets
350/// [`SignPayload::Sha256`] and hashes no byte of the body.
351///
352/// The path of a [`Target::Path`] or a [`Target::PathQuery`] goes through
353/// [`request_path`](RequestSigner::request_path) before the fetcher adds it
354/// to the base path of a mirror. So a signer that signs a canonical form of
355/// the path gets a request that carries that form. A [`Target::Url`] goes on
356/// the wire as written.
357///
358/// The [`Debug`] output of a signer must show no secret, because the
359/// [`Debug`] output of [`FetcherOptions`] includes it.
360pub trait RequestSigner: Send + Sync + std::fmt::Debug {
361 /// Returns `path`, the path of a [`Target::Path`] or a
362 /// [`Target::PathQuery`], in the form that the request carries.
363 ///
364 /// The fetcher calls this method once for each fetch and each upload
365 /// with a path target, before admission. It adds the result to the base
366 /// path of each mirror, in place of `path`. The fetcher does not call it
367 /// for a [`Target::Url`], or for the query of a [`Target::PathQuery`].
368 ///
369 /// The default returns `path` unchanged. A signer whose signature covers
370 /// a canonical form of the path returns that form, so the request
371 /// carries the bytes that the signature covers.
372 ///
373 /// # Errors
374 ///
375 /// The fetcher passes an error of this method through unchanged, and the
376 /// request ends with it before admission. Usually, the error is
377 /// [`Error::Fetch`].
378 fn request_path<'a>(&self, path: &'a str) -> Result<Cow<'a, str>> {
379 Ok(Cow::Borrowed(path))
380 }
381
382 /// Returns the headers that sign `request`. Each one replaces a header of
383 /// the same name.
384 ///
385 /// The fetcher refuses a returned header as it refuses a request header:
386 /// an invalid name or value, a `Host` header, and a header that the
387 /// connection layer sets. Each returned value is marked sensitive, so an
388 /// HTTP/2 connection never adds it to its header compression table. Two
389 /// returned headers of one name both go on the wire.
390 ///
391 /// # Errors
392 ///
393 /// The fetcher passes an error of this method through unchanged, and the
394 /// request ends with it. The request sends nothing for the attempt, and
395 /// the fetcher tries no other destination and no other round. An error on
396 /// a redirect hop of an upload ends the upload with
397 /// [`Error::UploadInterrupted`], because the first hop sent the request.
398 /// Usually, the error is [`Error::Fetch`].
399 fn sign(&self, request: &SignRequest<'_>) -> Result<Vec<(String, String)>>;
400}
401
402/// The parts of one attempt that a signer signs, as the request carries them.
403#[derive(Clone, Copy, Debug)]
404pub struct SignRequest<'a> {
405 /// The method: `GET`, `POST`, `PUT`, or `DELETE`.
406 pub method: &'a str,
407 /// The `host[:port]` of the request, which is the `Host` header of an
408 /// HTTP/1.1 request and the `:authority` of an HTTP/2 request.
409 ///
410 /// It has no default port of the scheme. An IPv6 literal keeps its
411 /// brackets.
412 pub authority: &'a str,
413 /// The path of the request target, as the request carries it. It includes
414 /// the base path of a mirror, and the escapes of the caller.
415 pub path: &'a str,
416 /// The query string of the request target, without the `?`.
417 ///
418 /// It is `None` if the target has no `?`. A target that ends in `?` has an
419 /// empty query.
420 pub query: Option<&'a str>,
421 /// The body of the request.
422 pub payload: SignPayload<'a>,
423}
424
425/// The body of a signed request.
426///
427/// The [`Debug`] output of [`Bytes`](SignPayload::Bytes) and of
428/// [`Sha256`](SignPayload::Sha256) shows the length of the body, and not its
429/// bytes.
430#[derive(Clone, Copy, Eq, PartialEq)]
431#[non_exhaustive]
432pub enum SignPayload<'a> {
433 /// No body: a `GET` or a `DELETE`.
434 Empty,
435 /// The whole body of a `POST` or a `PUT` that [`UploadBody::bytes`] gives.
436 /// An empty body is also this variant.
437 ///
438 /// The signer gets the whole body on each attempt, and it runs on the task
439 /// that sends the request. So the time to hash the body on that task grows
440 /// with the size of the body. For a large body,
441 /// [`UploadBody::bytes_with_sha256`] gives the signer the SHA-256 of the
442 /// body as [`Sha256`](SignPayload::Sha256).
443 Bytes(&'a [u8]),
444 /// The whole body of a `POST` or a `PUT` that
445 /// [`UploadBody::bytes_with_sha256`] gives, with the SHA-256 of the body
446 /// that the caller computed.
447 ///
448 /// The fetcher does not check the digest. A wrong digest signs other
449 /// bytes than the bytes that the request sends, and the server refuses
450 /// the request.
451 Sha256 {
452 /// The whole body.
453 bytes: &'a [u8],
454 /// The SHA-256 of `bytes`, as the caller gave it.
455 sha256: [u8; 32],
456 },
457 /// The body of a `POST` or a `PUT` that streams from an [`UploadWriter`].
458 /// Its bytes are not known when the fetcher calls the signer.
459 Streamed,
460}
461
462impl std::fmt::Debug for SignPayload<'_> {
463 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464 match self {
465 SignPayload::Empty => f.write_str("Empty"),
466 SignPayload::Bytes(bytes) => f.debug_tuple("Bytes").field(&bytes.len()).finish(),
467 SignPayload::Sha256 { bytes, .. } => {
468 f.debug_tuple("Sha256").field(&bytes.len()).finish()
469 }
470 SignPayload::Streamed => f.write_str("Streamed"),
471 }
472 }
473}
474
475/// The validators of a response, which make a later fetch conditional.
476#[derive(Clone, Debug, Default, Eq, PartialEq)]
477pub struct Validators {
478 /// The `ETag` of the response, sent back as `If-None-Match`.
479 pub etag: Option<String>,
480 /// The `Last-Modified` of the response, sent back as `If-Modified-Since`.
481 pub last_modified: Option<String>,
482}
483
484impl Validators {
485 /// Returns `true` if no validator holds a value.
486 pub fn is_empty(&self) -> bool {
487 self.etag.is_none() && self.last_modified.is_none()
488 }
489}
490
491/// The lowest transfer rate that a fetch accepts.
492///
493/// The fetcher samples the rate of a transfer once a second. Each sample is the
494/// bytes of the last five seconds divided by five. In the first five seconds, a
495/// sample is the bytes so far divided by the whole seconds so far.
496///
497/// If the rate stays at `limit` or less for `time` without a break, the
498/// transfer fails as a transport failure. A transfer starts under the limit,
499/// because it carried no bytes. A sample over the limit starts the count of
500/// `time` again. For the response head, the count starts at the start of the
501/// attempt, and for the body, at the first read.
502#[derive(Clone, Copy, Debug, Eq, PartialEq)]
503pub struct LowSpeed {
504 /// The rate in bytes per second that a transfer must keep.
505 ///
506 /// A zero fails [`Fetcher::new`].
507 pub limit: u32,
508 /// The longest time that the rate can stay at `limit` or less.
509 ///
510 /// A zero fails [`Fetcher::new`]. The fetcher samples the rate once a
511 /// second, so a part of a second counts as a whole second.
512 pub time: Duration,
513}
514
515impl LowSpeed {
516 /// Returns `time` rounded up to whole seconds. The addition saturates at the
517 /// maximum and does not wrap.
518 fn whole_seconds(&self) -> Duration {
519 let partial = u64::from(self.time.subsec_nanos() > 0);
520 Duration::from_secs(self.time.as_secs().saturating_add(partial))
521 }
522}
523
524/// How often the low-speed rule samples the rate of a body.
525const SAMPLE_PERIOD: Duration = Duration::from_secs(1);
526
527/// The number of samples over which the low-speed rule measures the rate.
528const RATE_SPAN: usize = 5;
529
530/// The proxy through which a [`Fetcher`] reaches each origin.
531///
532/// [`Fetcher::new`] resolves each form once, and refuses a proxy URL that the
533/// fetcher cannot connect through. A request does not read the environment
534/// again.
535///
536/// The [`Debug`] output does not show the userinfo of a proxy URL. So the log
537/// of a struct that holds proxy credentials does not show them.
538///
539/// # Variables
540///
541/// `http_proxy` serves `http` origins, and `https_proxy` serves `https`
542/// origins. If the variable of the scheme is unset, `all_proxy` serves the
543/// origin. The fetcher also reads each name in upper case, except `HTTP_PROXY`.
544/// A CGI gateway gives a request header `Proxy` to the program as `HTTP_PROXY`,
545/// so a client can set that variable with a request.
546///
547/// The lower-case name has priority over the upper-case name. An empty value
548/// counts as unset.
549///
550/// # White space
551///
552/// If the value of `http_proxy`, `https_proxy`, or `all_proxy`, or of an
553/// upper-case name, has white space at its start or end, [`Fetcher::new`]
554/// fails with [`Error::Unsupported`]. A value of white space alone also fails.
555/// It is not empty, so it counts as set and hides the upper-case name.
556///
557/// The fetcher checks the value of each variable that the lookup reads, when it
558/// builds the fetcher. It checks a variable also if no request goes through
559/// that proxy. The message names the variable and holds no part of the value,
560/// which can hold a password. The fetcher trims the URL of [`Proxy::Url`] and
561/// each `no_proxy` entry.
562///
563/// # Proxy URL
564///
565/// A proxy URL has the form `http://host[:port]`, `socks5://host[:port]`, or
566/// `socks5h://host[:port]`. The port is 80 by default for `http://` and 1080
567/// for `socks5://` and `socks5h://`. The URL has no path other than `/`, no
568/// query, and no fragment. For an `http://` proxy, the fetcher percent-decodes
569/// the userinfo and sends it to the proxy as `Proxy-Authorization: Basic`.
570/// [SOCKS proxies](Proxy#socks-proxies) states the rules of a SOCKS5 proxy.
571///
572/// Any other form fails [`Fetcher::new`] with [`Error::Unsupported`], for
573/// example an `https://` or a `socks4://` proxy. This applies to a URL from the
574/// options and to a URL from the environment. The message names the value
575/// without its userinfo.
576///
577/// # Exemptions
578///
579/// `no_proxy` is a comma-separated list of the origins that the two
580/// environment forms exempt. An entry holds a host text, with one leading `.`
581/// if it is written with one, and `:port` if it names a port. The fetcher
582/// ignores the space around an entry. An entry that names no host exempts
583/// nothing, for example an empty entry, `.`, or `:8080`.
584///
585/// If the port text of an entry is not a number from 0 to 65535, the whole
586/// entry is one host text. No origin holds that text, so the entry exempts
587/// nothing.
588///
589/// `*` as a whole entry exempts all hosts. It is the one wildcard that the list
590/// reads. `*.example.com` is a host text, and no origin holds it.
591///
592/// An entry matches an origin if it equals the host, or if the host ends with a
593/// `.` and the entry. The fetcher removes one leading `.` from the entry first,
594/// so `.example.com` and `example.com` both exempt `a.example.com`. A second
595/// leading `.` is part of the host text of the entry. An entry with `:port`
596/// matches that port alone.
597///
598/// The match compares the host text of the URL, with ASCII case ignored. It
599/// never compares the address of the host. So `localhost` exempts no origin
600/// written as `127.0.0.1`, and an entry that is an IP literal matches that text
601/// alone.
602///
603/// An entry in CIDR notation names no network. The fetcher reads it as a host
604/// text, which no origin holds. This is a divergence from curl 7.86 and later,
605/// which read such an entry as a network. An empty `no_proxy` value exempts
606/// nothing, and [`Proxy::Url`] reads no exemptions.
607///
608/// # Cleartext origins
609///
610/// The fetcher reaches a cleartext origin behind an `http://` proxy over a
611/// connection to the proxy. The request carries the absolute-form target, the whole
612/// `http://host/path` URL, and the `Host` header of the origin. Such a
613/// connection uses HTTP/1.1, because cleartext HTTP/2 needs prior knowledge or
614/// an upgrade.
615///
616/// The pool keeps such a connection under the proxy endpoint, so one proxy
617/// connection carries requests for all cleartext origins. The pool key marks a
618/// connection as a proxy connection. So the pool never gives a direct
619/// connection to the proxy endpoint to a proxied request, or the reverse. The
620/// two request forms differ, and a server answers the unexpected form with a
621/// 404.
622///
623/// # TLS origins
624///
625/// The fetcher reaches a TLS origin behind an `http://` proxy over a `CONNECT`
626/// tunnel. The
627/// request names the target as `host:port`. The port is always written, and an
628/// IPv6 literal keeps its brackets. If the proxy URL holds userinfo, the
629/// `CONNECT` carries the same `Proxy-Authorization`.
630///
631/// On a 2xx answer, the fetcher gets the tunneled socket back. The TLS
632/// handshake, the ALPN selection, and the pool entry are then the same as for a
633/// direct connection to that origin. Nothing follows a `CONNECT` response, so a
634/// byte that arrives before the client sends fails the connect.
635///
636/// A non-2xx answer is a retryable failure, and a 407 is a definitive failure.
637/// Both are [`Error::Fetch`] and name the proxy.
638/// [`connect_timeout`](FetcherOptions::connect_timeout) is the limit for all
639/// these steps together: the connect to the proxy, the `CONNECT` exchange, the
640/// TLS handshake, and the HTTP handshake.
641///
642/// # SOCKS proxies
643///
644/// A `socks5://` or a `socks5h://` URL names a SOCKS5 proxy (RFC 1928). With
645/// `socks5://`, the fetcher resolves the host name of the origin and sends an
646/// address to the proxy. With `socks5h://`, the fetcher sends the host name
647/// of the origin to the proxy, and the proxy resolves the name. If the origin
648/// host is an IP address, the fetcher sends the address under both schemes.
649/// `socks4://` and `socks4a://` fail [`Fetcher::new`] with
650/// [`Error::Unsupported`].
651///
652/// The fetcher opens a connection to the proxy and asks the proxy to connect
653/// to the origin. Then the connection carries the bytes of the origin. A
654/// cleartext origin and a TLS origin use this one way. The TLS handshake, the
655/// ALPN selection, the request, and the pool entry are the same as for a
656/// direct connection to the origin. So the request has the origin form, and
657/// the proxy reads no HTTP. A `Proxy-Authorization` header of the caller goes
658/// to the origin.
659///
660/// If the URL has no userinfo, the fetcher offers the method "no
661/// authentication" alone. If the URL has userinfo, the fetcher also offers the
662/// user name and password method of RFC 1929. It sends the user name and the
663/// password only if the proxy selects that method. The fetcher does not offer
664/// GSSAPI.
665///
666/// The userinfo is `user:password`. The fetcher percent-decodes each field as
667/// for an `http://` proxy, and each field must be UTF-8 after the decode. Each
668/// field must be 1 to 255 bytes after the decode. [`Fetcher::new`] refuses
669/// other userinfo with [`Error::Unsupported`], for example `user@` or
670/// `user:@`. The message names the URL without its userinfo.
671///
672/// A message names the proxy with its URL without the userinfo. The message
673/// leaves out the port if it is 1080.
674///
675/// SOCKS5 sends a host name of 1 to 255 bytes. A longer origin host fails the
676/// hop as a definitive failure. A host name with a `%` also fails as a
677/// definitive failure, because a SOCKS5 request has no field for the zone id
678/// of an IPv6 address. The fetcher applies these two checks under both
679/// schemes, before it resolves the name. In these two cases, the fetcher
680/// resolves no name and opens no connection to the proxy.
681///
682/// Under `socks5://`, the fetcher asks the proxy to connect to each resolved
683/// address in turn, in the order that a direct connection tries them. Each
684/// address gets a new connection to the proxy, because a refused request ends
685/// the connection. The first address that the proxy connects wins. A
686/// definitive failure stops the loop, and a failed connect to the proxy also
687/// stops it. If the proxy refuses each address, the retryable failure states
688/// the last failure and the number of addresses. A failed resolve, or a
689/// resolve that gives no address, is a retryable failure and names the origin
690/// host.
691///
692/// Two answers of the proxy are definitive failures: the proxy accepts none of
693/// the offered methods, or it refuses the user name and the password. A retry
694/// gets the same answer. Each other failure is retryable. This includes each
695/// reply code other than success, a reply that breaks the protocol, and an I/O
696/// failure. The fetcher ignores the value of the reserved byte of the reply.
697/// Each failure is [`Error::Fetch`]. A failure of the SOCKS5 exchange names
698/// the proxy and the origin.
699///
700/// [`connect_timeout`](FetcherOptions::connect_timeout) is the limit for all
701/// these steps together: the resolve, the connect to the proxy, the SOCKS5
702/// exchange, the TLS handshake, and the HTTP handshake. Under `socks5://`,
703/// the limit covers the whole address loop. An attempt that stalls can use
704/// the full limit, and then the fetcher tries no later address. A timeout
705/// names the proxy.
706///
707/// # Proxy credential
708///
709/// The proxy credential belongs to the connection layer. It goes to the proxy
710/// on a proxied cleartext request and on a `CONNECT`, and to no origin. It is
711/// not in the merged header list, so the cleartext credential check and the
712/// redirect scoping do not read it. A tunnel carries no part of it. A SOCKS
713/// proxy gets its credential in the RFC 1929 exchange alone.
714///
715/// A `Proxy-Authorization` header that a caller sets keeps the meaning that it
716/// has without a proxy. It is a credential in the merged list. A fetch refuses
717/// it for a cleartext destination, as it refuses an `Authorization` or a
718/// `Cookie` header.
719///
720/// On a proxied cleartext request, the header of the caller replaces the proxy
721/// credential of the fetcher. Two values for one header give two answers to one
722/// question. Over a tunnel, the two never meet. The header of the caller goes
723/// to the origin, and the credential of the fetcher goes to the proxy.
724///
725/// # Redirects
726///
727/// The fetcher makes the proxy decision for each hop, from the origin of that
728/// hop. So a redirect to another origin goes the same way as a route that names
729/// that origin. A proxy does not change the cleartext rule: a cleartext origin
730/// is cleartext also through a proxy.
731///
732/// # Examples
733///
734/// ```no_run
735/// use ostrya_fetch::{Fetcher, FetcherOptions, Proxy};
736/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
737/// let mut options = FetcherOptions::new("https://example.com/repo");
738/// options.proxy = Proxy::Variables(vec![
739/// ("https_proxy".into(), "http://proxy.example.com:3128".into()),
740/// ("no_proxy".into(), ".internal.example.com".into()),
741/// ]);
742/// let fetcher = Fetcher::new(options).await?;
743/// # let _ = fetcher;
744/// # Ok(())
745/// # }
746/// ```
747#[derive(Clone, Default)]
748pub enum Proxy {
749 /// A direct connection, whatever the environment holds.
750 None,
751 /// The proxy variables of the process environment.
752 ///
753 /// [`Fetcher::new`] reads the variables once. This is the default.
754 /// [Variables](Proxy#variables) states the names, and
755 /// [White space](Proxy#white-space) states the check of each value.
756 #[default]
757 Environment,
758 /// The proxy variables, given as name and value pairs.
759 ///
760 /// The fetcher does not read the process environment. It ignores a name
761 /// that the environment forms do not read. Of two entries of one name, the
762 /// first entry with a value counts. [White space](Proxy#white-space) states
763 /// the check of each value.
764 Variables(Vec<(String, String)>),
765 /// One `http://`, `socks5://`, or `socks5h://` proxy URL for all origins.
766 ///
767 /// The fetcher sends the userinfo of an `http://` URL as
768 /// `Proxy-Authorization: Basic`, and the userinfo of a SOCKS5 URL in the
769 /// RFC 1929 exchange. No origin is exempt, because the fetcher
770 /// reads the environment for neither the proxy nor the exemptions. The
771 /// fetcher trims white space around the URL.
772 Url(String),
773}
774
775impl std::fmt::Debug for Proxy {
776 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
777 match self {
778 Proxy::None => f.write_str("None"),
779 Proxy::Environment => f.write_str("Environment"),
780 Proxy::Variables(variables) => f
781 .debug_tuple("Variables")
782 .field(&RedactedVariables { variables })
783 .finish(),
784 Proxy::Url(url) => f.debug_tuple("Url").field(&RedactedUrl::url(url)).finish(),
785 }
786 }
787}
788
789/// The proxy variables in a [`Debug`] output: a list of name and value pairs.
790///
791/// Each value shows as [`RedactedUrl`] shows an absolute URL.
792struct RedactedVariables<'a> {
793 variables: &'a [(String, String)],
794}
795
796impl std::fmt::Debug for RedactedVariables<'_> {
797 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
798 let RedactedVariables { variables } = self;
799 f.debug_list()
800 .entries(
801 variables
802 .iter()
803 .map(|(name, value)| (name, RedactedUrl::url(value))),
804 )
805 .finish()
806 }
807}
808
809/// The headers in a [`Debug`] output: a list of name and `<redacted>` pairs.
810///
811/// A header value can be a credential, so no value shows. Each call of `names`
812/// gives the name of each header value, in order.
813struct RedactedHeaders<F> {
814 names: F,
815}
816
817impl<'a, F, I> std::fmt::Debug for RedactedHeaders<F>
818where
819 F: Fn() -> I,
820 I: Iterator<Item = &'a str>,
821{
822 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
823 f.debug_list()
824 .entries((self.names)().map(|name| (name, "<redacted>")))
825 .finish()
826 }
827}
828
829/// A URL or a request path in a [`Debug`] output, with no userinfo, query
830/// value, or fragment value.
831///
832/// The userinfo of an absolute URL is the text after the `://` of the scheme,
833/// up to and including the last `@`. When the text has no valid scheme before
834/// the first `://`, the userinfo is the text from the start up to and including
835/// the last `@`. A password can hold a `/`, `?`, or `#`, so the output removes
836/// the userinfo first and leaves no marker for it. Then a query shows as
837/// `?<redacted>`, and a fragment shows as `#<redacted>`. A path has no
838/// userinfo. Each other part shows as the [`Debug`] output of a `str` shows it.
839struct RedactedUrl<'a> {
840 text: &'a str,
841 /// `true` if `text` is an absolute URL, which can hold userinfo.
842 absolute: bool,
843}
844
845impl<'a> RedactedUrl<'a> {
846 /// Shows an absolute URL.
847 fn url(text: &'a str) -> RedactedUrl<'a> {
848 RedactedUrl {
849 text,
850 absolute: true,
851 }
852 }
853
854 /// Shows a request path.
855 fn path(text: &'a str) -> RedactedUrl<'a> {
856 RedactedUrl {
857 text,
858 absolute: false,
859 }
860 }
861}
862
863impl std::fmt::Debug for RedactedUrl<'_> {
864 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
865 use std::fmt::Write as _;
866
867 let RedactedUrl { text, absolute } = *self;
868 let (scheme, rest) = if absolute {
869 let end = scheme_len(text);
870 let rest = &text[end..];
871 let rest = rest.rfind('@').map_or(rest, |at| &rest[at + 1..]);
872 (&text[..end], rest)
873 } else {
874 ("", text)
875 };
876 let (shown, query, fragment) = match rest.find(['?', '#']) {
877 None => (rest, false, false),
878 Some(at) if rest[at..].starts_with('#') => (&rest[..at], false, true),
879 Some(at) => (&rest[..at], true, rest[at..].contains('#')),
880 };
881 // The `Debug` output of a `str` escapes each `char` as
882 // `char::escape_debug` does, except `'`, which it writes as it is.
883 f.write_char('"')?;
884 for c in scheme.chars().chain(shown.chars()) {
885 if c == '\'' {
886 f.write_char(c)?;
887 } else {
888 for escaped in c.escape_debug() {
889 f.write_char(escaped)?;
890 }
891 }
892 }
893 if query {
894 f.write_str("?<redacted>")?;
895 }
896 if fragment {
897 f.write_str("#<redacted>")?;
898 }
899 f.write_char('"')
900 }
901}
902
903/// A list of URLs in a [`Debug`] output, each one shown as [`RedactedUrl`]
904/// shows an absolute URL.
905struct RedactedUrls<'a> {
906 urls: &'a [String],
907}
908
909impl std::fmt::Debug for RedactedUrls<'_> {
910 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
911 let RedactedUrls { urls } = self;
912 f.debug_list()
913 .entries(urls.iter().map(|url| RedactedUrl::url(url)))
914 .finish()
915 }
916}
917
918/// The options of a [`Fetcher`]: the remote, the credentials, and the limits.
919///
920/// [`FetcherOptions::default`] sets each field to the default that the field
921/// states. [`FetcherOptions::new`] also sets one mirror.
922///
923/// The [`Debug`] output shows the name of each header, and `<redacted>` in
924/// place of its value. The output also shows no password of `basic_auth`, no
925/// token of `bearer_token`, no client key or passphrase, and no userinfo of a
926/// proxy URL. Each mirror URL shows with no userinfo. A query shows as
927/// `?<redacted>`, and a fragment shows as `#<redacted>`. The signer shows as
928/// its own [`Debug`] output shows it.
929#[derive(Clone)]
930pub struct FetcherOptions {
931 /// The base URLs, tried in order for each request that names a
932 /// [`Target::Path`] or a [`Target::PathQuery`].
933 ///
934 /// A remote with a mirror list gives one entry for each mirror. A base URL
935 /// is a scheme, an authority, and a path. A query string or userinfo fails
936 /// [`Fetcher::new`], so neither part of a base URL reaches the wire. A
937 /// request target is the base path, then `/` and the request path, then
938 /// `?` and the query of a [`Target::PathQuery`]. With a
939 /// [`signer`](FetcherOptions::signer), the request path is the path that
940 /// [`RequestSigner::request_path`] gives.
941 ///
942 /// An empty list serves [`Target::Url`] requests alone. The default is an
943 /// empty list.
944 pub mirrors: Vec<String>,
945 /// The extra headers of each request, to each destination and redirect hop.
946 ///
947 /// A request header of the same name replaces an entry. The fetcher sets
948 /// `User-Agent` and `Accept-Encoding: identity`, and an entry of one of
949 /// these names replaces the value of the fetcher. Other headers go as
950 /// written. The default is an empty list.
951 ///
952 /// An `Authorization`, `Proxy-Authorization`, or `Cookie` header is a
953 /// credential, because its value is a secret, whatever it holds. A
954 /// credential goes to the origin that the route names, and to a redirect hop
955 /// at that origin alone.
956 ///
957 /// [`Fetcher::new`] refuses these entries:
958 ///
959 /// - a credential header, if a mirror is cleartext `http` and
960 /// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
961 /// is `false`
962 /// - a `Host` header
963 /// - a header that the connection layer sets: a framing name or a
964 /// hop-by-hop name
965 /// - an `Authorization` header beside
966 /// [`basic_auth`](FetcherOptions::basic_auth)
967 /// - an `Authorization` header beside
968 /// [`bearer_token`](FetcherOptions::bearer_token)
969 /// - an `Authorization` header beside [`signer`](FetcherOptions::signer)
970 /// - an invalid header name or value.
971 pub headers: Vec<(String, String)>,
972 /// The credentials for `Authorization: Basic`, sent with each request.
973 ///
974 /// The credentials go to each destination, and to a redirect hop at the
975 /// origin that the route names. [`FetchRequest::basic_auth`] replaces them
976 /// for one request. The default is `None`.
977 ///
978 /// Each mirror must be `https`, unless
979 /// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
980 /// is `true`. [`Fetcher::new`] refuses a cleartext mirror, so the
981 /// credentials go in cleartext only with that permission. An
982 /// `Authorization` entry in [`headers`](FetcherOptions::headers), a
983 /// [`bearer_token`](FetcherOptions::bearer_token), or a
984 /// [`signer`](FetcherOptions::signer) beside these also fails
985 /// [`Fetcher::new`], because each of them can set the same header.
986 pub basic_auth: Option<BasicAuth>,
987 /// The token for `Authorization: Bearer`, sent with each request.
988 ///
989 /// The token goes to each destination, and to a redirect hop at the origin
990 /// that the route names. Each of these replaces it for one request:
991 /// [`FetchRequest::basic_auth`], [`UploadRequest::basic_auth`],
992 /// [`UploadRequest::bearer_token`], or an `Authorization` entry in the
993 /// headers of the request. The default is `None`.
994 ///
995 /// [`Fetcher::new`] refuses a token that does not have the token68 syntax
996 /// that [`BearerToken`] states. It also refuses the token beside
997 /// [`basic_auth`](FetcherOptions::basic_auth), beside an
998 /// `Authorization` entry in [`headers`](FetcherOptions::headers), or
999 /// beside a [`signer`](FetcherOptions::signer), because each of them can
1000 /// set the same header.
1001 ///
1002 /// Each mirror must be `https`, unless
1003 /// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
1004 /// is `true`.
1005 pub bearer_token: Option<BearerToken>,
1006 /// The signer that adds a signature to each attempt at the origin that
1007 /// the route names.
1008 ///
1009 /// [`RequestSigner`] states when the fetcher calls the signer. The headers
1010 /// of the signer replace the headers of the same name in each layer: the
1011 /// fetcher and the request. A redirect hop at another origin gets no
1012 /// signature. The default is `None`.
1013 ///
1014 /// The signer is a credential. [`Fetcher::new`] refuses it beside
1015 /// [`basic_auth`](FetcherOptions::basic_auth), beside
1016 /// [`bearer_token`](FetcherOptions::bearer_token), and beside an
1017 /// `Authorization` entry in [`headers`](FetcherOptions::headers), because
1018 /// a signature can set the same header. For the same reason, a fetch or an
1019 /// upload with a credential of its own fails before admission: basic-auth
1020 /// credentials, a bearer token, or an `Authorization` request header.
1021 ///
1022 /// Each mirror must be `https`, unless
1023 /// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
1024 /// is `true`.
1025 pub signer: Option<Arc<dyn RequestSigner>>,
1026 /// The permission for a credential to reach a cleartext origin.
1027 ///
1028 /// If this is `true`, [`Fetcher::new`] does not refuse a cleartext mirror
1029 /// beside a credential: [`basic_auth`](FetcherOptions::basic_auth),
1030 /// [`bearer_token`](FetcherOptions::bearer_token),
1031 /// [`signer`](FetcherOptions::signer), or a credential header in
1032 /// [`headers`](FetcherOptions::headers). A fetch or an upload also does
1033 /// not refuse a credential for a cleartext destination, whatever the flag
1034 /// of the request is. [`FetchRequest::allow_cleartext_credentials`] states
1035 /// that rule.
1036 ///
1037 /// The redirect rules apply with this flag. A hop at another origin gets no
1038 /// credential and no signature, and a hop from `https` to `http` is
1039 /// refused. The default is `false`.
1040 ///
1041 /// A caller sets it for a server on a loopback address, or for a server
1042 /// behind a proxy that terminates TLS.
1043 pub allow_cleartext_credentials: bool,
1044 /// The trust anchors and the client certificate for `https` mirrors.
1045 ///
1046 /// The default is [`TlsOptions::default`]: [`TrustRoots::System`] and no
1047 /// client identity.
1048 pub tls: TlsOptions,
1049 /// The proxy through which the fetcher reaches an origin.
1050 ///
1051 /// [`Fetcher::new`] resolves the value once, and a request does not read it
1052 /// again. It refuses a proxy URL that is not `http://host[:port]`,
1053 /// `socks5://host[:port]`, or `socks5h://host[:port]`, a SOCKS5 URL with a
1054 /// userinfo that [SOCKS proxies](Proxy#socks-proxies) refuses, and a proxy variable with
1055 /// [white space](Proxy#white-space) around its value.
1056 /// The default is [`Proxy::Environment`], the proxy that the process
1057 /// environment names.
1058 pub proxy: Proxy,
1059 /// The switch that offers HTTP/2 in ALPN.
1060 ///
1061 /// If this is `false`, the fetcher uses HTTP/1.1, also with a server that
1062 /// supports HTTP/2. The default is `true`.
1063 pub http2: bool,
1064 /// The number of times that a fetch repeats a round after a retryable
1065 /// failure.
1066 ///
1067 /// [`Fetcher::fetch`] states the retry rules. The default is 5.
1068 pub max_retries: u32,
1069 /// The number of redirects that one attempt against one destination
1070 /// follows.
1071 ///
1072 /// The attempt follows a 301, 302, 303, 307, or 308 while it followed fewer
1073 /// redirects than this value. If the next one names a URL, the attempt fails
1074 /// definitively with [`Error::RedirectLimit`]. If it names no URL, the
1075 /// attempt reports its own status.
1076 ///
1077 /// Zero follows nothing, so each of those statuses is then a definitive
1078 /// answer. A fetch with [`FetchRequest::max_error_body`] then gets the
1079 /// headers of the redirect, `Location` included, in its
1080 /// [`Error::HttpStatus`]. The count belongs to one attempt, so a repeated
1081 /// round counts again from the destination that the route names.
1082 /// [`Fetcher::fetch`] states the redirect rules. The default is 10.
1083 pub max_redirects: u32,
1084 /// The number of requests in flight at one time.
1085 ///
1086 /// The fetcher admits this many requests at a time, and serves the queue in
1087 /// [`Priority`] order. A request holds its permit until the fetch fails, or
1088 /// until its response body reaches its end or is dropped. A body in flight
1089 /// occupies a connection, so it keeps the permit.
1090 ///
1091 /// The default is 8. The fetcher admits at least one request, so 0 admits
1092 /// one request.
1093 pub max_outstanding: usize,
1094 /// The time limit to open a connection.
1095 ///
1096 /// The limit applies to the TCP connect, the TLS handshake, and the HTTP
1097 /// handshake together. Through a proxy, it also applies to the connect to
1098 /// the proxy and to the `CONNECT` exchange.
1099 ///
1100 /// The TCP connect resolves the host name, then races the addresses that
1101 /// the resolver gave. A new attempt starts every 250ms, and an attempt that
1102 /// fails starts the next one immediately. So the limit includes the
1103 /// resolution and all attempts.
1104 ///
1105 /// The expiry is a transport failure. So it is retryable, and the fetch
1106 /// tries the next destination. The default is 30 s.
1107 pub connect_timeout: Duration,
1108 /// The longest time that a response can go without bytes.
1109 ///
1110 /// The window applies to the wait for the response head and to each stall
1111 /// of the body. It measures the silence since a read asked for bytes. So it
1112 /// limits silence, and leaves the transfer time unlimited.
1113 ///
1114 /// The window runs from the read that finds no bytes until bytes arrive.
1115 /// After a read found no bytes, the window runs also when no read is
1116 /// outstanding. A body that no read found empty is not on the clock.
1117 ///
1118 /// If the body stalls, the read fails with
1119 /// [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut), and each
1120 /// later read fails the same way. An expired wait for the head is a
1121 /// retryable transport failure, so the fetch tries the next destination.
1122 /// The default is 60 s.
1123 pub progress_timeout: Duration,
1124 /// The lowest transfer rate that an attempt accepts, as [`LowSpeed`]
1125 /// states.
1126 ///
1127 /// The response head must arrive within `time` of the start of the attempt,
1128 /// rounded up to whole seconds, redirects included. The rate of the body
1129 /// counts from its first read. So the fetcher does not measure a body that
1130 /// waits for its consumer before the consumer asks for bytes.
1131 ///
1132 /// The fetcher samples the body only while a read is outstanding. A gap
1133 /// between reads that is longer than a second counts as one second. The
1134 /// bytes that arrived in the gap count at the next read.
1135 ///
1136 /// A transfer slower than the rate is a transport failure. A slow head is a
1137 /// retryable failure of the attempt. A slow body fails the read with
1138 /// [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut).
1139 ///
1140 /// `None` checks no rate. The default is `None`.
1141 pub low_speed: Option<LowSpeed>,
1142 /// The longest time that one fetch can take to get a response head.
1143 ///
1144 /// The limit includes all rounds, all retries, and the delays between them,
1145 /// from the admission of the fetch until the response head arrives. Only
1146 /// [`progress_timeout`](FetcherOptions::progress_timeout) limits the body
1147 /// that follows. `None` sets no limit. The default is 300 s.
1148 ///
1149 /// This limit is the longest time that a fetch with no response holds an
1150 /// admission permit. So a caller sizes it against
1151 /// [`max_outstanding`](FetcherOptions::max_outstanding). Without this
1152 /// limit, an unresponsive peer can stall a fetch for a product of three
1153 /// values. These are the destination count, the retry count, and the two
1154 /// deadlines of an attempt.
1155 ///
1156 /// On expiry, the fetch fails with [`Error::Fetch`] and tries nothing more.
1157 /// The attempt that the expiry cancels releases the admission permit. An
1158 /// upload has a narrower limit, which [`Fetcher::upload`] states.
1159 pub fetch_timeout: Option<Duration>,
1160}
1161
1162impl Default for FetcherOptions {
1163 fn default() -> Self {
1164 FetcherOptions {
1165 mirrors: Vec::new(),
1166 headers: Vec::new(),
1167 basic_auth: None,
1168 bearer_token: None,
1169 signer: None,
1170 allow_cleartext_credentials: false,
1171 tls: TlsOptions::default(),
1172 proxy: Proxy::default(),
1173 http2: true,
1174 max_retries: 5,
1175 max_redirects: 10,
1176 max_outstanding: 8,
1177 connect_timeout: Duration::from_secs(30),
1178 progress_timeout: Duration::from_secs(60),
1179 low_speed: None,
1180 fetch_timeout: Some(Duration::from_secs(300)),
1181 }
1182 }
1183}
1184
1185impl std::fmt::Debug for FetcherOptions {
1186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1187 let FetcherOptions {
1188 mirrors,
1189 headers,
1190 basic_auth,
1191 bearer_token,
1192 signer,
1193 allow_cleartext_credentials,
1194 tls,
1195 proxy,
1196 http2,
1197 max_retries,
1198 max_redirects,
1199 max_outstanding,
1200 connect_timeout,
1201 progress_timeout,
1202 low_speed,
1203 fetch_timeout,
1204 } = self;
1205 let headers = RedactedHeaders {
1206 names: || headers.iter().map(|(name, _)| name.as_str()),
1207 };
1208 f.debug_struct("FetcherOptions")
1209 .field("mirrors", &RedactedUrls { urls: mirrors })
1210 .field("headers", &headers)
1211 .field("basic_auth", basic_auth)
1212 .field("bearer_token", bearer_token)
1213 .field("signer", signer)
1214 .field("allow_cleartext_credentials", allow_cleartext_credentials)
1215 .field("tls", tls)
1216 .field("proxy", proxy)
1217 .field("http2", http2)
1218 .field("max_retries", max_retries)
1219 .field("max_redirects", max_redirects)
1220 .field("max_outstanding", max_outstanding)
1221 .field("connect_timeout", connect_timeout)
1222 .field("progress_timeout", progress_timeout)
1223 .field("low_speed", low_speed)
1224 .field("fetch_timeout", fetch_timeout)
1225 .finish()
1226 }
1227}
1228
1229impl FetcherOptions {
1230 /// Creates options with one base URL and the default of each other field.
1231 pub fn new(url: impl Into<String>) -> FetcherOptions {
1232 FetcherOptions {
1233 mirrors: vec![url.into()],
1234 ..FetcherOptions::default()
1235 }
1236 }
1237}
1238
1239/// The target of a request.
1240///
1241/// The [`Debug`] output shows no userinfo of a URL. A query shows as
1242/// `?<redacted>`, and a fragment shows as `#<redacted>`, in a URL and in a
1243/// path. The query of [`Target::PathQuery`] shows as `<redacted>`.
1244#[derive(Clone, Copy, Eq, PartialEq)]
1245#[non_exhaustive]
1246pub enum Target<'a> {
1247 /// A path under the base URL of each mirror.
1248 Path(&'a str),
1249 /// A path under the base URL of each mirror, with a query string.
1250 ///
1251 /// The fetcher adds `?` and the query to the URL of each mirror. It sends
1252 /// the query as written, so the query carries the escapes that the server
1253 /// expects.
1254 PathQuery {
1255 /// The path, read as [`Target::Path`] is.
1256 path: &'a str,
1257 /// The query string, without the `?`.
1258 query: &'a str,
1259 },
1260 /// An absolute `http` or `https` URL.
1261 ///
1262 /// The fetcher does not use the mirror list for it.
1263 Url(&'a str),
1264}
1265
1266impl std::fmt::Debug for Target<'_> {
1267 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1268 match *self {
1269 Target::Path(path) => f
1270 .debug_tuple("Path")
1271 .field(&RedactedUrl::path(path))
1272 .finish(),
1273 Target::PathQuery { path, query: _ } => f
1274 .debug_struct("PathQuery")
1275 .field("path", &RedactedUrl::path(path))
1276 .field("query", &"<redacted>")
1277 .finish(),
1278 Target::Url(url) => f.debug_tuple("Url").field(&RedactedUrl::url(url)).finish(),
1279 }
1280 }
1281}
1282
1283impl<'a> Target<'a> {
1284 /// Returns the text that names the target in each message: the path, the
1285 /// path with `?` and its query, or the URL, as the caller wrote it.
1286 fn describe(&self) -> Cow<'a, str> {
1287 match *self {
1288 Target::Path(path) => Cow::Borrowed(path),
1289 Target::PathQuery { path, query } => Cow::Owned(format!("{path}?{query}")),
1290 Target::Url(url) => Cow::Borrowed(url),
1291 }
1292 }
1293}
1294
1295/// The request of one fetch.
1296///
1297/// The [`Debug`] output shows the name of each header, and `<redacted>` in
1298/// place of its value. The target shows as the [`Debug`] output of [`Target`]
1299/// shows it.
1300#[derive(Clone)]
1301pub struct FetchRequest<'a> {
1302 /// The target: a path under the base URL of each mirror, the same with a
1303 /// query string, or an absolute URL.
1304 ///
1305 /// The fetcher adds a path to the base path as written, so the path carries
1306 /// the escapes that the server expects. A path holds no `?` and no `#`,
1307 /// because neither is part of a path. Either one fails the fetch before
1308 /// admission. If the fetcher has a
1309 /// [`signer`](FetcherOptions::signer), the fetcher adds the path that
1310 /// [`RequestSigner::request_path`] gives in place of the path.
1311 ///
1312 /// The fetcher adds `?` and the query of [`Target::PathQuery`] after the
1313 /// path, as written, so the query carries the escapes that the server
1314 /// expects. A query holds no `#`, because a `#` starts a fragment. A `#`
1315 /// fails the fetch before admission.
1316 ///
1317 /// The fetcher sends the query string of a URL as written. A fragment in a
1318 /// URL fails the fetch, because no request sends a fragment. A character
1319 /// that a request target cannot hold fails the fetch when the fetcher
1320 /// assembles the URL.
1321 pub target: Target<'a>,
1322 /// The place of the request in the queue when the fetcher is at its limit.
1323 pub priority: Priority,
1324 /// The validators of a previous fetch.
1325 ///
1326 /// If the server reports that the copy is still current, the fetch gives
1327 /// [`Fetched::NotModified`].
1328 pub validators: Option<&'a Validators>,
1329 /// The largest response body, in bytes, that the fetch accepts.
1330 ///
1331 /// A larger `Content-Length` fails the fetch with [`Error::FetchTooLarge`].
1332 /// If a body grows past the cap while it streams, the read fails with
1333 /// [`io::ErrorKind::FileTooLarge`](std::io::ErrorKind::FileTooLarge). The
1334 /// fetcher compares the cap with the response that answers, and does not
1335 /// measure an intermediate redirect response.
1336 pub max_size: Option<u64>,
1337 /// Headers merged over the headers of the fetcher.
1338 ///
1339 /// An entry replaces a fetcher header of the same name. Names compare as
1340 /// `HeaderName`, so the comparison ignores case. Two entries of one name
1341 /// both go on the wire. An invalid name or value fails the fetch before
1342 /// admission.
1343 ///
1344 /// The fetcher sets `User-Agent` and `Accept-Encoding: identity`, and an
1345 /// entry of one of these names replaces the value. An entry can ask for a
1346 /// content coding. A response that declares a coding fails with
1347 /// [`Error::ContentEncoded`], whichever layer asked for it.
1348 ///
1349 /// A `Range` entry, in either layer, makes a 206 a successful answer. The
1350 /// fetch then gives the part of the object as a [`Body`], whose
1351 /// [`status`](Body::status) is 206. A 206 to a request with no `Range`
1352 /// entry fails the fetch with [`Error::HttpStatus`]. The size cap and the
1353 /// content coding rules apply to a 206 as to a 200.
1354 ///
1355 /// A `Host` entry fails the fetch, because the header comes from the URL. A
1356 /// header that the connection layer sets fails at both layers: a framing
1357 /// name or a hop-by-hop name. The connection owns the framing of a request
1358 /// and the state of its connection. A value of the caller puts the wire and
1359 /// the connection pool out of step.
1360 ///
1361 /// # Authorization
1362 ///
1363 /// The request carries the `Authorization` header of the first of these
1364 /// that is set:
1365 ///
1366 /// 1. [`FetchRequest::basic_auth`]
1367 /// 2. an `Authorization` entry in these headers
1368 /// 3. [`FetcherOptions::basic_auth`] or [`FetcherOptions::bearer_token`]
1369 /// 4. an `Authorization` entry in [`FetcherOptions::headers`].
1370 ///
1371 /// Credentials beside an `Authorization` header in one layer give two
1372 /// answers to one question. [`Fetcher::new`] refuses them on the fetcher,
1373 /// and the fetch refuses them on a request.
1374 ///
1375 /// A fetcher with a [`signer`](FetcherOptions::signer) takes no
1376 /// credential of a request. [`basic_auth`](FetchRequest::basic_auth) or
1377 /// an `Authorization` entry in these headers then fails the fetch before
1378 /// admission with [`Error::Fetch`]. [`Fetcher::new`] refuses layers 3 and
1379 /// 4 beside a signer. So the signature is the one credential of the
1380 /// request, and each header that the signer returns replaces the header
1381 /// of the same name.
1382 pub headers: &'a [(String, String)],
1383 /// Credentials that replace the credentials of the fetcher for this
1384 /// request.
1385 ///
1386 /// These set the `Authorization` header, so an `Authorization` entry in
1387 /// [`headers`](FetchRequest::headers) beside them fails the fetch. A
1388 /// [`signer`](FetcherOptions::signer) of the fetcher beside them also
1389 /// fails the fetch before admission with [`Error::Fetch`].
1390 ///
1391 /// The fetcher encodes the header value for each request. A caller that
1392 /// sends one credential over many requests can encode the `Authorization`
1393 /// value once and set it in [`headers`](FetchRequest::headers). That entry
1394 /// replaces the credential of the fetcher for the request in the same way.
1395 pub basic_auth: Option<&'a BasicAuth>,
1396 /// The permission for a credential to reach a cleartext origin.
1397 ///
1398 /// If this is `false` and the merged headers carry a credential, the fetch
1399 /// fails if a destination that it can reach is `http`. The merged headers
1400 /// include the credentials of the fetcher. The check of [`Fetcher::new`] on
1401 /// the mirror list applies whatever this value is. The default is `false`.
1402 ///
1403 /// [`FetcherOptions::allow_cleartext_credentials`] lifts this refusal for
1404 /// each request of the fetcher.
1405 ///
1406 /// A redirect hop never carries a credential to a cleartext origin of its
1407 /// own. The fetcher removes the credential for a hop at another origin, and
1408 /// refuses a hop from `https` to `http`. [`Fetcher::fetch`] states the
1409 /// redirect rules.
1410 ///
1411 /// # Cleartext credentials
1412 ///
1413 /// The fetcher withholds a credential from no destination that a route
1414 /// names. So it refuses a credential and a cleartext destination together.
1415 /// The credentials are [`basic_auth`](FetchRequest::basic_auth), and an
1416 /// `Authorization`, `Proxy-Authorization`, or `Cookie` entry in the merged
1417 /// headers. [`FetcherOptions::basic_auth`] and
1418 /// [`FetcherOptions::bearer_token`] are `Authorization` entries in the
1419 /// merged headers. [`FetcherOptions::signer`] is also a credential.
1420 ///
1421 /// If a fetch carries a credential and a destination that it can reach is
1422 /// `http`, the fetch fails before admission with [`Error::Fetch`]. The
1423 /// message names that origin. The other choice is to withhold the
1424 /// credential from that one destination. That choice turns a configuration
1425 /// mistake into a 401 that names nothing.
1426 pub allow_cleartext_credentials: bool,
1427 /// The largest body of an unsuccessful response that the fetch keeps.
1428 ///
1429 /// With `Some(cap)`, a fetch that fails with [`Error::HttpStatus`] gives
1430 /// the headers of the reported response in that error. It also gives the
1431 /// body, if the whole body is `cap` bytes or less. `Some(0)` keeps the
1432 /// headers and an empty body. [`ErrorResponse`] states when the body is
1433 /// absent.
1434 ///
1435 /// `None` keeps nothing, and the fetch discards each unsuccessful
1436 /// response. The default is `None`.
1437 ///
1438 /// [`Fetcher::fetch`] states the rules in its section "Error responses".
1439 pub max_error_body: Option<u64>,
1440}
1441
1442impl std::fmt::Debug for FetchRequest<'_> {
1443 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1444 let FetchRequest {
1445 target,
1446 priority,
1447 validators,
1448 max_size,
1449 headers,
1450 basic_auth,
1451 allow_cleartext_credentials,
1452 max_error_body,
1453 } = self;
1454 let headers = RedactedHeaders {
1455 names: || headers.iter().map(|(name, _)| name.as_str()),
1456 };
1457 f.debug_struct("FetchRequest")
1458 .field("target", target)
1459 .field("priority", priority)
1460 .field("validators", validators)
1461 .field("max_size", max_size)
1462 .field("headers", &headers)
1463 .field("basic_auth", basic_auth)
1464 .field("allow_cleartext_credentials", allow_cleartext_credentials)
1465 .field("max_error_body", max_error_body)
1466 .finish()
1467 }
1468}
1469
1470impl<'a> FetchRequest<'a> {
1471 /// Creates a request for `path` under each mirror.
1472 ///
1473 /// The request has normal priority, no validators, and no size cap. It
1474 /// carries the headers and the credentials of the fetcher.
1475 pub fn path(path: &'a str) -> FetchRequest<'a> {
1476 FetchRequest::for_target(Target::Path(path))
1477 }
1478
1479 /// Creates a request for `path` with the query string `query` under each
1480 /// mirror.
1481 ///
1482 /// The query has no leading `?`. The request has normal priority, no
1483 /// validators, and no size cap. It carries the headers and the
1484 /// credentials of the fetcher.
1485 pub fn path_query(path: &'a str, query: &'a str) -> FetchRequest<'a> {
1486 FetchRequest::for_target(Target::PathQuery { path, query })
1487 }
1488
1489 /// Creates a request for the absolute URL `url`.
1490 ///
1491 /// The request has normal priority, no validators, and no size cap. It
1492 /// carries the headers and the credentials of the fetcher.
1493 pub fn url(url: &'a str) -> FetchRequest<'a> {
1494 FetchRequest::for_target(Target::Url(url))
1495 }
1496
1497 /// Creates a request for `target` with the default of each other field.
1498 fn for_target(target: Target<'a>) -> FetchRequest<'a> {
1499 FetchRequest {
1500 target,
1501 priority: Priority::default(),
1502 validators: None,
1503 max_size: None,
1504 headers: &[],
1505 basic_auth: None,
1506 allow_cleartext_credentials: false,
1507 max_error_body: None,
1508 }
1509 }
1510}
1511
1512/// The result of a fetch.
1513#[derive(Debug)]
1514// The body variant is much larger than the other variant. A box adds an
1515// allocation on the path of each object, so the variant stays inline.
1516#[allow(clippy::large_enum_variant)]
1517pub enum Fetched {
1518 /// The body of the object that the server sent.
1519 Body(Body),
1520 /// A 304 answer: the copy of the caller is current.
1521 NotModified,
1522}
1523
1524/// The method of an upload.
1525#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1526#[non_exhaustive]
1527pub enum UploadMethod {
1528 /// `POST`, which sends the body.
1529 ///
1530 /// This is the default.
1531 #[default]
1532 Post,
1533 /// `PUT`, which sends the body.
1534 ///
1535 /// The retry and the redirect rules of [`Post`](UploadMethod::Post)
1536 /// apply.
1537 Put,
1538 /// `DELETE`, which sends no body.
1539 ///
1540 /// The request takes an empty [`UploadBody::bytes`]. Any other body fails
1541 /// the upload before admission with [`Error::Fetch`].
1542 Delete,
1543}
1544
1545/// The request body of an upload.
1546///
1547/// A body has one of two forms:
1548///
1549/// - [`bytes`](UploadBody::bytes) gives the whole body. The request declares
1550/// its `Content-Length`, and hyper takes the bytes in frames of 64 KiB. A
1551/// followed redirect sends the bytes again.
1552/// [`bytes_with_sha256`](UploadBody::bytes_with_sha256) also gives the
1553/// SHA-256 of the body to the signer.
1554/// - [`channel`](UploadBody::channel) streams the body. The caller writes the
1555/// body into the [`UploadWriter`] while the upload runs. Over HTTP/1.1, the
1556/// body travels chunked.
1557///
1558/// If a channel body is dropped before an upload sends it, or after its upload
1559/// ends, each write of its writer fails with
1560/// [`io::ErrorKind::BrokenPipe`](std::io::ErrorKind::BrokenPipe). If the body
1561/// of a `POST` or a `PUT` is at its end when the fetcher hands over the
1562/// request, the request declares a `Content-Length` of zero.
1563pub struct UploadBody {
1564 form: UploadForm,
1565}
1566
1567/// The two forms of an [`UploadBody`].
1568enum UploadForm {
1569 /// The whole body, which each hop of the upload sends, and the SHA-256
1570 /// of the body if the caller gave it.
1571 Bytes {
1572 bytes: Bytes,
1573 sha256: Option<[u8; 32]>,
1574 },
1575 /// The reading end of a body that an [`UploadWriter`] fills.
1576 Channel(BodyEnd),
1577}
1578
1579impl UploadBody {
1580 /// Creates a body of `bytes`.
1581 ///
1582 /// The request sends the vector in frames cut from it with no copy.
1583 pub fn bytes(bytes: Vec<u8>) -> UploadBody {
1584 UploadBody {
1585 form: UploadForm::Bytes {
1586 bytes: Bytes::from(bytes),
1587 sha256: None,
1588 },
1589 }
1590 }
1591
1592 /// Creates a body of `bytes`, whose SHA-256 is `sha256`.
1593 ///
1594 /// The body is a body of [`bytes`](UploadBody::bytes). A signer gets it
1595 /// as [`SignPayload::Sha256`] with `sha256`, so a signer that signs the
1596 /// SHA-256 of the body hashes no byte of it on the task of the request.
1597 /// Each retry and each redirect hop of the upload uses the same digest,
1598 /// and so does a copy from [`try_clone`](UploadBody::try_clone).
1599 ///
1600 /// The fetcher does not check the digest. A wrong digest signs other
1601 /// bytes than the bytes that the request sends, and the server refuses
1602 /// the request.
1603 pub fn bytes_with_sha256(bytes: Vec<u8>, sha256: [u8; 32]) -> UploadBody {
1604 UploadBody {
1605 form: UploadForm::Bytes {
1606 bytes: Bytes::from(bytes),
1607 sha256: Some(sha256),
1608 },
1609 }
1610 }
1611
1612 /// Creates a streamed body and the writer that fills it.
1613 pub fn channel() -> (UploadBody, UploadWriter) {
1614 let exchange = Arc::new(Exchange::default());
1615 let body = UploadBody {
1616 form: UploadForm::Channel(BodyEnd {
1617 exchange: exchange.clone(),
1618 }),
1619 };
1620 let writer = UploadWriter {
1621 exchange,
1622 // The first write allocates the frame. So a body that gets no
1623 // write holds no frame of memory.
1624 buffer: Vec::new(),
1625 stall: None,
1626 failed: None,
1627 };
1628 (body, writer)
1629 }
1630
1631 /// Returns the bytes of a body of [`bytes`](UploadBody::bytes), or `None`
1632 /// for a streamed body.
1633 pub fn as_bytes(&self) -> Option<&[u8]> {
1634 match &self.form {
1635 UploadForm::Bytes { bytes, .. } => Some(bytes),
1636 UploadForm::Channel(_) => None,
1637 }
1638 }
1639
1640 /// Returns the SHA-256 of a body of
1641 /// [`bytes_with_sha256`](UploadBody::bytes_with_sha256), or `None` for
1642 /// another body.
1643 pub fn sha256(&self) -> Option<[u8; 32]> {
1644 match &self.form {
1645 UploadForm::Bytes { sha256, .. } => *sha256,
1646 UploadForm::Channel(_) => None,
1647 }
1648 }
1649
1650 /// Returns a second body with the same bytes, or `None` for a streamed
1651 /// body.
1652 ///
1653 /// The two bodies of [`bytes`](UploadBody::bytes) share the one buffer, so
1654 /// the call copies no byte. The copy keeps the SHA-256 of a body of
1655 /// [`bytes_with_sha256`](UploadBody::bytes_with_sha256). A caller sends
1656 /// the copy in a second request, for example after the first one failed
1657 /// with [`Error::UploadInterrupted`]. A [`channel`](UploadBody::channel)
1658 /// body has one writer, so it has no copy.
1659 pub fn try_clone(&self) -> Option<UploadBody> {
1660 match &self.form {
1661 UploadForm::Bytes { bytes, sha256 } => Some(UploadBody {
1662 form: UploadForm::Bytes {
1663 bytes: bytes.clone(),
1664 sha256: *sha256,
1665 },
1666 }),
1667 UploadForm::Channel(_) => None,
1668 }
1669 }
1670
1671 /// Returns the bytes of a body of [`bytes`](UploadBody::bytes) as a
1672 /// vector, or the body unchanged.
1673 ///
1674 /// If no other body shares the buffer, the call gives the buffer back
1675 /// with its capacity, and copies no byte. A caller can then fill the
1676 /// vector again for a later request. The vector does not keep the
1677 /// SHA-256 of a body of
1678 /// [`bytes_with_sha256`](UploadBody::bytes_with_sha256). A copy from
1679 /// [`try_clone`](UploadBody::try_clone) shares the buffer, and so does an
1680 /// upload that still holds the body. The call then returns the body as
1681 /// the error, as it does for a [`channel`](UploadBody::channel) body.
1682 ///
1683 /// # Errors
1684 ///
1685 /// Returns the body unchanged if it is a streamed body, or if another
1686 /// body shares its buffer.
1687 pub fn into_vec(self) -> std::result::Result<Vec<u8>, UploadBody> {
1688 match self.form {
1689 UploadForm::Bytes { bytes, sha256 } => match bytes.try_into_mut() {
1690 Ok(bytes) => Ok(Vec::from(bytes)),
1691 Err(bytes) => Err(UploadBody {
1692 form: UploadForm::Bytes { bytes, sha256 },
1693 }),
1694 },
1695 UploadForm::Channel(end) => Err(UploadBody {
1696 form: UploadForm::Channel(end),
1697 }),
1698 }
1699 }
1700}
1701
1702impl From<Vec<u8>> for UploadBody {
1703 fn from(bytes: Vec<u8>) -> UploadBody {
1704 UploadBody::bytes(bytes)
1705 }
1706}
1707
1708impl std::fmt::Debug for UploadBody {
1709 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1710 match &self.form {
1711 UploadForm::Bytes { bytes, .. } => f.debug_tuple("Bytes").field(&bytes.len()).finish(),
1712 UploadForm::Channel(_) => f.write_str("Channel"),
1713 }
1714 }
1715}
1716
1717/// The request of one upload, which sends a body and gets a bounded response.
1718///
1719/// The [`Debug`] output shows the name of each header, and `<redacted>` in
1720/// place of its value. The target shows as the [`Debug`] output of [`Target`]
1721/// shows it.
1722pub struct UploadRequest<'a> {
1723 /// The target, read as [`FetchRequest::target`] is. A
1724 /// [`Target::PathQuery`] goes to the mirrors with its query, as for a
1725 /// fetch.
1726 ///
1727 /// The fetcher tries the mirrors in order until one of them takes the
1728 /// request. It never asks a mirror after that one.
1729 pub target: Target<'a>,
1730 /// The method.
1731 ///
1732 /// The default is `POST`.
1733 pub method: UploadMethod,
1734 /// The body that the request sends.
1735 pub body: UploadBody,
1736 /// The place of the request in the queue when the fetcher is at its limit.
1737 pub priority: Priority,
1738 /// The largest response body, in bytes, for each status.
1739 ///
1740 /// A larger `Content-Length` of a 2xx answer fails the upload with
1741 /// [`Error::UploadInterrupted`]. An answer other than 2xx with a larger
1742 /// `Content-Length` keeps its status, and its body is
1743 /// [withheld](Uploaded::body_withheld). If a body grows past the cap
1744 /// while it streams, the read fails with
1745 /// [`io::ErrorKind::FileTooLarge`](std::io::ErrorKind::FileTooLarge). The
1746 /// default is [`UploadRequest::DEFAULT_MAX_RESPONSE`].
1747 pub max_response: u64,
1748 /// Headers merged over the headers of the fetcher.
1749 ///
1750 /// [`FetchRequest::headers`] states the merge. The fetcher sets no
1751 /// `Content-Type`, so a `Content-Type` that the server needs goes here.
1752 pub headers: &'a [(String, String)],
1753 /// Credentials for `Authorization: Basic`, for this request.
1754 ///
1755 /// They replace the credentials of the fetcher.
1756 ///
1757 /// Beside [`bearer_token`](UploadRequest::bearer_token), beside an
1758 /// `Authorization` entry in [`headers`](UploadRequest::headers), or beside
1759 /// a [`signer`](FetcherOptions::signer) of the fetcher, they fail the
1760 /// upload before admission with [`Error::Fetch`].
1761 pub basic_auth: Option<&'a BasicAuth>,
1762 /// A token for `Authorization: Bearer`, for this request.
1763 ///
1764 /// It replaces the credentials of the fetcher.
1765 ///
1766 /// Beside [`basic_auth`](UploadRequest::basic_auth), beside an
1767 /// `Authorization` entry in [`headers`](UploadRequest::headers), or beside
1768 /// a [`signer`](FetcherOptions::signer) of the fetcher, it fails the
1769 /// upload before admission with [`Error::Fetch`].
1770 pub bearer_token: Option<&'a BearerToken>,
1771 /// The permission for a credential to reach a cleartext origin.
1772 ///
1773 /// [`FetchRequest::allow_cleartext_credentials`] states the rule.
1774 pub allow_cleartext_credentials: bool,
1775 /// The longest wait for the response head after hyper takes the end of the
1776 /// body.
1777 ///
1778 /// `None` takes [`progress_timeout`](FetcherOptions::progress_timeout).
1779 pub response_timeout: Option<Duration>,
1780}
1781
1782impl std::fmt::Debug for UploadRequest<'_> {
1783 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1784 let UploadRequest {
1785 target,
1786 method,
1787 body,
1788 priority,
1789 max_response,
1790 headers,
1791 basic_auth,
1792 bearer_token,
1793 allow_cleartext_credentials,
1794 response_timeout,
1795 } = self;
1796 let headers = RedactedHeaders {
1797 names: || headers.iter().map(|(name, _)| name.as_str()),
1798 };
1799 f.debug_struct("UploadRequest")
1800 .field("target", target)
1801 .field("method", method)
1802 .field("body", body)
1803 .field("priority", priority)
1804 .field("max_response", max_response)
1805 .field("headers", &headers)
1806 .field("basic_auth", basic_auth)
1807 .field("bearer_token", bearer_token)
1808 .field("allow_cleartext_credentials", allow_cleartext_credentials)
1809 .field("response_timeout", response_timeout)
1810 .finish()
1811 }
1812}
1813
1814impl<'a> UploadRequest<'a> {
1815 /// The default response cap of a request: 2 MiB.
1816 pub const DEFAULT_MAX_RESPONSE: u64 = 2 * 1024 * 1024;
1817
1818 /// Creates a `POST` of `body` to `path` under each mirror.
1819 ///
1820 /// The request has normal priority. It carries the headers and the
1821 /// credentials of the fetcher.
1822 pub fn path(path: &'a str, body: UploadBody) -> UploadRequest<'a> {
1823 UploadRequest::for_target(Target::Path(path), body)
1824 }
1825
1826 /// Creates a `POST` of `body` to the absolute URL `url`.
1827 ///
1828 /// The request has normal priority. It carries the headers and the
1829 /// credentials of the fetcher.
1830 pub fn url(url: &'a str, body: UploadBody) -> UploadRequest<'a> {
1831 UploadRequest::for_target(Target::Url(url), body)
1832 }
1833
1834 /// Creates a request for `target` with the default of each other field.
1835 fn for_target(target: Target<'a>, body: UploadBody) -> UploadRequest<'a> {
1836 UploadRequest {
1837 target,
1838 method: UploadMethod::default(),
1839 body,
1840 priority: Priority::default(),
1841 max_response: UploadRequest::DEFAULT_MAX_RESPONSE,
1842 headers: &[],
1843 basic_auth: None,
1844 bearer_token: None,
1845 allow_cleartext_credentials: false,
1846 response_timeout: None,
1847 }
1848 }
1849}
1850
1851/// The answer to an upload: the status, the headers, and the response body.
1852///
1853/// Each final status arrives here, also an unsuccessful one. The caller
1854/// decides what it means.
1855///
1856/// The [`Debug`] output shows the name of each response header, and
1857/// `<redacted>` in place of its value. A header with several values shows its
1858/// name once for each value. The URL shows with no userinfo. A query shows as
1859/// `?<redacted>`, and a fragment shows as `#<redacted>`.
1860pub struct Uploaded {
1861 status: StatusCode,
1862 headers: hyper::HeaderMap,
1863 url: String,
1864 body: Body,
1865 /// `true` if the upload withheld the body of an answer other than 2xx.
1866 withheld: bool,
1867}
1868
1869impl std::fmt::Debug for Uploaded {
1870 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1871 let Uploaded {
1872 status,
1873 headers,
1874 url,
1875 body,
1876 withheld: _,
1877 } = self;
1878 let headers = RedactedHeaders {
1879 names: || headers.iter().map(|(name, _)| name.as_str()),
1880 };
1881 f.debug_struct("Uploaded")
1882 .field("status", status)
1883 .field("headers", &headers)
1884 .field("url", &RedactedUrl::url(url))
1885 .field("body", body)
1886 .finish()
1887 }
1888}
1889
1890impl Uploaded {
1891 /// Returns the status of the response.
1892 pub fn status(&self) -> u16 {
1893 self.status.as_u16()
1894 }
1895
1896 /// Returns the headers of the response.
1897 pub fn headers(&self) -> &hyper::HeaderMap {
1898 &self.headers
1899 }
1900
1901 /// Returns the URL that answered.
1902 ///
1903 /// After a redirect, this is the URL of the last hop.
1904 pub fn url(&self) -> &str {
1905 &self.url
1906 }
1907
1908 /// Returns `true` if the upload withheld the body of the response.
1909 ///
1910 /// An answer other than 2xx whose head declares a coding, or a
1911 /// `Content-Length` over [`max_response`](UploadRequest::max_response),
1912 /// comes with its status and its headers alone. Its body is not read:
1913 /// [`into_body`](Uploaded::into_body) gives a body that reads as empty,
1914 /// and the connection closes. [`Fetcher::upload`] states the rule.
1915 pub fn body_withheld(&self) -> bool {
1916 self.withheld
1917 }
1918
1919 /// Returns the HTTP version of the response.
1920 pub fn protocol(&self) -> Protocol {
1921 self.body.protocol()
1922 }
1923
1924 /// Returns the response body, capped at
1925 /// [`max_response`](UploadRequest::max_response).
1926 ///
1927 /// The body holds the admission permit until it ends or is dropped. A
1928 /// [withheld](Uploaded::body_withheld) body reads as empty and holds no
1929 /// permit.
1930 pub fn into_body(self) -> Body {
1931 self.body
1932 }
1933}
1934
1935/// The headers and the capped body of an unsuccessful response to a fetch.
1936///
1937/// [`Error::HttpStatus`] carries it if the request set
1938/// [`max_error_body`](FetchRequest::max_error_body). A caller outside this
1939/// crate builds one with [`new`](ErrorResponse::new).
1940///
1941/// The [`Debug`] output shows the name of each header, and `<redacted>` in
1942/// place of its value. A header with several values shows its name once for
1943/// each value. The body shows as its length.
1944pub struct ErrorResponse {
1945 headers: hyper::HeaderMap,
1946 body: Option<Vec<u8>>,
1947}
1948
1949impl std::fmt::Debug for ErrorResponse {
1950 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1951 let ErrorResponse { headers, body } = self;
1952 let headers = RedactedHeaders {
1953 names: || headers.iter().map(|(name, _)| name.as_str()),
1954 };
1955 f.debug_struct("ErrorResponse")
1956 .field("headers", &headers)
1957 .field("body", &body.as_ref().map(Vec::len))
1958 .finish()
1959 }
1960}
1961
1962impl ErrorResponse {
1963 /// Creates a response of `headers` and `body`.
1964 pub fn new(headers: hyper::HeaderMap, body: Option<Vec<u8>>) -> ErrorResponse {
1965 ErrorResponse { headers, body }
1966 }
1967
1968 /// Returns the headers of the response.
1969 pub fn headers(&self) -> &hyper::HeaderMap {
1970 &self.headers
1971 }
1972
1973 /// Returns the whole body of the response.
1974 ///
1975 /// The body is `None` in these cases:
1976 ///
1977 /// - the response declared a `Content-Length` over the cap
1978 /// - the body grew past the cap while it arrived
1979 /// - the response declared a coding in `Content-Encoding` or
1980 /// `Transfer-Encoding`
1981 /// - the body failed in transit
1982 /// - the body did not arrive in full within one
1983 /// [`progress_timeout`](FetcherOptions::progress_timeout) from the
1984 /// arrival of the response head.
1985 ///
1986 /// The fetcher never keeps a part of a body.
1987 pub fn body(&self) -> Option<&[u8]> {
1988 self.body.as_deref()
1989 }
1990}
1991
1992/// A parsed base URL.
1993#[derive(Clone, Debug)]
1994struct Mirror {
1995 /// The scheme, the host, and the port of the origin.
1996 origin: Origin,
1997 /// The `host[:port]` of this mirror, which is the `Host` header of an
1998 /// HTTP/1.1 request. It holds the authority as the base URL wrote it,
1999 /// without the default port of the scheme. An IPv6 literal keeps its
2000 /// brackets.
2001 authority: HeaderValue,
2002 /// The `scheme://authority` prefix of each absolute URL for this mirror.
2003 /// A message names the origin of the mirror with this prefix.
2004 prefix: String,
2005 /// The base path, without a trailing slash. It is empty for a mirror at the
2006 /// root.
2007 base: String,
2008}
2009
2010impl Mirror {
2011 /// Returns the destination of a request for `path` and `query` under this
2012 /// mirror. The one string of the destination is the prefix and the base
2013 /// path of the mirror, then the request path, then `?` and the query if
2014 /// there is one.
2015 fn destination(&self, path: &str, query: Option<&str>) -> Destination {
2016 let path = path.trim_start_matches('/');
2017 let url = match query {
2018 None => format!("{}{}/{path}", self.prefix, self.base),
2019 Some(query) => format!("{}{}/{path}?{query}", self.prefix, self.base),
2020 };
2021 Destination {
2022 origin: self.origin.clone(),
2023 authority: self.authority.clone(),
2024 url,
2025 path_at: self.prefix.len(),
2026 }
2027 }
2028}
2029
2030/// The place to which one attempt sends its request.
2031///
2032/// A URL target resolves its one destination once for each fetch, and each
2033/// attempt and each retry round uses it. A path target resolves the
2034/// destination of a mirror at the attempt that uses that mirror.
2035#[derive(Clone, Debug)]
2036struct Destination {
2037 /// The scheme, the host, and the port of the origin. The pool key holds it,
2038 /// together with the client identity that the connection presents.
2039 origin: Origin,
2040 /// The `host[:port]` of the request, which is the `Host` header of an
2041 /// HTTP/1.1 request. It holds the authority as the caller wrote it, without
2042 /// the default port of the scheme. An IPv6 literal keeps its brackets.
2043 authority: HeaderValue,
2044 /// The absolute URL. It holds the two forms that one request needs: the
2045 /// whole string, and the tail from `path_at`.
2046 url: String,
2047 /// The start of the request path in `url`, which is the length of the
2048 /// `scheme://authority` prefix.
2049 path_at: usize,
2050}
2051
2052impl Destination {
2053 /// Returns the absolute URL, which an HTTP/2 request carries and each
2054 /// message names.
2055 fn url(&self) -> &str {
2056 &self.url
2057 }
2058
2059 /// Returns the origin-form request target, which an HTTP/1.1 request to an
2060 /// origin server carries. It is the path, and the query string of a URL
2061 /// target or of a path target with a query.
2062 fn target(&self) -> &str {
2063 &self.url[self.path_at..]
2064 }
2065
2066 /// Returns the `scheme://authority` of this destination. A message about
2067 /// the origin names it with this string.
2068 fn origin_url(&self) -> &str {
2069 &self.url[..self.path_at]
2070 }
2071
2072 /// Returns the `host[:port]` of this destination as text, which is the
2073 /// value of the `Host` header in `authority`. An HTTP/2 request carries
2074 /// the same text in its `:authority`, because it carries the absolute URL.
2075 fn authority_text(&self) -> &str {
2076 &self.url[scheme_len(&self.url)..self.path_at]
2077 }
2078}
2079
2080/// The destinations of a fetch, in the order in which it asks them.
2081///
2082/// A path target goes to each mirror. So a round walks the mirror list, and
2083/// builds the destination of a mirror when it asks that mirror. If the first
2084/// mirror answers, the fetch builds one destination, whatever the length of the
2085/// list. A URL target names one destination, which the fetch parses once.
2086#[derive(Debug)]
2087enum Route<'a> {
2088 /// Each mirror in order, for this request path and query string. The
2089 /// path is in the form that the signer of the fetcher gives.
2090 Mirrors {
2091 path: Cow<'a, str>,
2092 query: Option<&'a str>,
2093 },
2094 /// The one destination that a URL target names.
2095 One(Destination),
2096}
2097
2098/// A connection endpoint.
2099#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2100struct Origin {
2101 tls: bool,
2102 /// The host that the connect resolves, and the source of the TLS server
2103 /// name. So an IPv6 literal has no brackets here. An ASCII host is in lower
2104 /// case, so one origin written in two cases is one pool key and one
2105 /// connection.
2106 host: String,
2107 port: u16,
2108}
2109
2110/// The key of the connection pool.
2111///
2112/// The key holds an endpoint, the client configuration that opened the
2113/// connection, and the proxy flag. A connection presents the client
2114/// certificate for each request that it carries. So the pool never gives a
2115/// connection with the certificate to a hop that must not present it. It never
2116/// gives a connection without the certificate to the origin that the route
2117/// named.
2118///
2119/// The identity flag is in this key, and not in [`Origin`]. [`Origin`] states
2120/// the identity of a network endpoint, and the cleartext and trust-anchor
2121/// checks read it.
2122#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2123struct PoolKey {
2124 origin: Origin,
2125 /// `true` if the connection presents the configured client certificate.
2126 identity: bool,
2127 /// `true` if the connection goes to a proxy and carries absolute-form
2128 /// requests.
2129 ///
2130 /// The pool keeps such a connection under the proxy endpoint. A cleartext
2131 /// origin of the same host and port has the same endpoint, and the two
2132 /// carry different request forms. This flag keeps the pool from giving one
2133 /// to a request of the other.
2134 proxied: bool,
2135}
2136
2137/// One proxy that the fetcher connects through, resolved from a proxy URL.
2138#[derive(Debug)]
2139struct ProxyEndpoint {
2140 /// The endpoint of the connection. The fetcher reaches a proxy over
2141 /// cleartext, so this origin is never TLS.
2142 endpoint: Origin,
2143 /// The protocol of the proxy and its credential.
2144 kind: ProxyKind,
2145 /// The name of this proxy in a message, which is its URL without the
2146 /// userinfo.
2147 named: String,
2148}
2149
2150/// The protocol that the fetcher speaks to a proxy.
2151#[derive(Debug)]
2152enum ProxyKind {
2153 /// An `http://` proxy.
2154 Http {
2155 /// The `Proxy-Authorization` value from the userinfo of the proxy URL,
2156 /// if the URL holds userinfo.
2157 credential: Option<HeaderValue>,
2158 },
2159 /// A `socks5://` or a `socks5h://` proxy.
2160 Socks(SocksProxy),
2161}
2162
2163/// The settings of a SOCKS5 proxy.
2164#[derive(Debug)]
2165struct SocksProxy {
2166 /// The side that resolves the host name of an origin.
2167 resolve: ResolveSide,
2168 /// The user name and the password from the userinfo of the proxy URL, if
2169 /// the URL holds userinfo.
2170 credential: Option<socks::Credential>,
2171}
2172
2173/// The side of a SOCKS5 connection that resolves the host name of an origin.
2174#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2175enum ResolveSide {
2176 /// The fetcher resolves the name and sends each address to the proxy in
2177 /// turn. A `socks5://` proxy uses this side.
2178 Client,
2179 /// The fetcher sends the name, and the proxy resolves it. A `socks5h://`
2180 /// proxy uses this side.
2181 Proxy,
2182}
2183
2184/// One `no_proxy` entry: a host text, and the port of the entry if it names
2185/// one.
2186#[derive(Debug)]
2187struct Exemption {
2188 /// The host that the entry names, in ASCII lower case, without one leading
2189 /// `.`. It is never empty: an entry that names no host exempts nothing and
2190 /// gets no place in a list.
2191 host: String,
2192 /// The port that the entry matches, if it names a port that the fetcher
2193 /// can read.
2194 port: Option<u16>,
2195}
2196
2197impl Exemption {
2198 /// Returns `true` if this entry exempts `origin`.
2199 ///
2200 /// The comparison is byte by byte, with ASCII case ignored. So a host that
2201 /// is not ASCII needs no slice at a character boundary, which can panic.
2202 fn matches(&self, origin: &Origin) -> bool {
2203 if self.port.is_some_and(|port| port != origin.port) {
2204 return false;
2205 }
2206 let host = origin.host.as_bytes();
2207 let entry = self.host.as_bytes();
2208 if host.eq_ignore_ascii_case(entry) {
2209 return true;
2210 }
2211 // The `.` before the entry states that the host is a name under the
2212 // entry. `notexample.com` is no part of `example.com`.
2213 host.len() > entry.len()
2214 && host[host.len() - entry.len() - 1] == b'.'
2215 && host[host.len() - entry.len()..].eq_ignore_ascii_case(entry)
2216 }
2217}
2218
2219/// The proxy of each scheme, and the exemptions from both.
2220#[derive(Debug, Default)]
2221struct Proxies {
2222 /// The proxy of a cleartext origin.
2223 http: Option<Arc<ProxyEndpoint>>,
2224 /// The proxy of a TLS origin. If one proxy URL serves both schemes, this
2225 /// field and `http` hold one endpoint.
2226 https: Option<Arc<ProxyEndpoint>>,
2227 /// `true` if `no_proxy` lists `*`, which exempts all hosts.
2228 exempt_all: bool,
2229 /// The hosts that `no_proxy` lists.
2230 exempt: Vec<Exemption>,
2231}
2232
2233impl Proxies {
2234 /// Returns the way to reach a hop at `origin`. This reads the resolved
2235 /// state and allocates nothing, so the decision costs a fetch one walk of
2236 /// the exemption list.
2237 fn via(&self, origin: &Origin) -> Via<'_> {
2238 let proxy = if origin.tls { &self.https } else { &self.http };
2239 let Some(proxy) = proxy.as_deref() else {
2240 return Via::Direct;
2241 };
2242 if self.exempt_all || self.exempt.iter().any(|entry| entry.matches(origin)) {
2243 return Via::Direct;
2244 }
2245 match &proxy.kind {
2246 ProxyKind::Socks(socks) => Via::Socks(proxy, socks),
2247 ProxyKind::Http { .. } if origin.tls => Via::Tunnel(proxy),
2248 ProxyKind::Http { .. } => Via::Absolute(proxy),
2249 }
2250 }
2251}
2252
2253/// The way that one hop reaches its origin.
2254#[derive(Clone, Copy, Debug)]
2255enum Via<'a> {
2256 /// A direct connection to the origin.
2257 Direct,
2258 /// A connection to the proxy that carries absolute-form requests. A
2259 /// cleartext origin behind an HTTP proxy uses this way.
2260 Absolute(&'a ProxyEndpoint),
2261 /// A `CONNECT` tunnel through the proxy. A TLS origin behind an HTTP
2262 /// proxy uses this way.
2263 Tunnel(&'a ProxyEndpoint),
2264 /// A connection to the origin through a SOCKS5 proxy. It carries
2265 /// origin-form requests, as a direct connection does. Each origin behind
2266 /// a SOCKS5 proxy uses this way.
2267 Socks(&'a ProxyEndpoint, &'a SocksProxy),
2268}
2269
2270/// The body of a request: no body for a fetch and for a `CONNECT`, or the
2271/// reading end of an upload body. One type serves both, so a fetch and an
2272/// upload share a pooled connection.
2273enum RequestBody {
2274 /// No body: a fetch, a `CONNECT`.
2275 Empty,
2276 /// The body of an upload.
2277 Upload(BodyEnd),
2278}
2279
2280impl hyper::body::Body for RequestBody {
2281 type Data = Bytes;
2282 type Error = std::io::Error;
2283
2284 fn poll_frame(
2285 self: Pin<&mut Self>,
2286 cx: &mut Context<'_>,
2287 ) -> Poll<Option<std::result::Result<Frame<Bytes>, Self::Error>>> {
2288 match self.get_mut() {
2289 RequestBody::Empty => Poll::Ready(None),
2290 RequestBody::Upload(end) => end.poll_frame(cx),
2291 }
2292 }
2293
2294 fn is_end_stream(&self) -> bool {
2295 match self {
2296 RequestBody::Empty => true,
2297 RequestBody::Upload(end) => end.is_end_stream(),
2298 }
2299 }
2300
2301 fn size_hint(&self) -> SizeHint {
2302 match self {
2303 RequestBody::Empty => SizeHint::with_exact(0),
2304 RequestBody::Upload(end) => match end.exchange.exact {
2305 Some(length) => SizeHint::with_exact(length),
2306 None => SizeHint::default(),
2307 },
2308 }
2309 }
2310}
2311
2312/// The state that one upload body shares between its writer, the reading end
2313/// that hyper polls, and the upload that waits for the response.
2314#[derive(Default)]
2315struct Exchange {
2316 slot: Mutex<Slot>,
2317 /// The length of a body given whole, which the request declares. This
2318 /// field is here, and not in the reading end, so the body of a fetch stays
2319 /// one pointer wide.
2320 exact: Option<u64>,
2321}
2322
2323/// The one slot through which an upload body passes its frames, and the
2324/// progress of each party.
2325#[derive(Default)]
2326struct Slot {
2327 /// A frame that the writer handed over and hyper did not take yet. For a
2328 /// body given whole, this is the remaining part of the body, which hyper
2329 /// takes in frames of [`UPLOAD_FRAME`].
2330 frame: Option<Bytes>,
2331 /// `true` if the writer closed the body, so no frame follows `frame`.
2332 closed: bool,
2333 /// The reason for the failure of the body. The writer was dropped before
2334 /// it closed the body, a frame waited past the stall window, or the
2335 /// response ended before the body.
2336 aborted: Option<String>,
2337 /// `true` if the reading end is dropped, which ends the upload.
2338 gone: bool,
2339 /// `true` if the reading end gave hyper the end of the body.
2340 ended: bool,
2341 /// `true` if hyper polled the body for a frame.
2342 polled: bool,
2343 /// `true` if the body was at its end at the hand-over of the request, so
2344 /// the request declares a length of zero.
2345 empty: bool,
2346 /// The stall window, which runs from the hand-over of the request.
2347 stall: Option<Stall>,
2348 /// The writer, which waits for the slot to empty or for the end.
2349 writer: Option<Waker>,
2350 /// hyper, which waits for a frame.
2351 reader: Option<Waker>,
2352 /// The upload, which waits for the end of the body or for its failure.
2353 upload: Option<Waker>,
2354}
2355
2356/// The stall window of an upload body: the longest time that a frame can wait
2357/// in the slot for hyper to take it.
2358#[derive(Clone, Copy)]
2359struct Stall {
2360 window: Duration,
2361 /// The start of the wait of the frame in the slot. This is the latest of
2362 /// three instants: the frame got its place, hyper took the frame before it
2363 /// from a body given whole, or the window started.
2364 since: Instant,
2365}
2366
2367impl Slot {
2368 /// Records that the body is at its end, and gives back the wakers of the
2369 /// two parties that wait for it.
2370 fn end(&mut self) -> [Option<Waker>; 2] {
2371 self.ended = true;
2372 [self.writer.take(), self.upload.take()]
2373 }
2374
2375 /// Fails the body for `reason`, and gives back the wakers of the parties
2376 /// that read the failure. If the body failed before, the first reason
2377 /// stays.
2378 fn abort(&mut self, reason: impl FnOnce() -> String) -> [Option<Waker>; 3] {
2379 self.aborted.get_or_insert_with(reason);
2380 [self.reader.take(), self.upload.take(), self.writer.take()]
2381 }
2382
2383 /// Returns `true` if the body is at its end: closed, with no frame left to
2384 /// take and no failure.
2385 fn at_end(&self) -> bool {
2386 self.closed && self.frame.is_none() && self.aborted.is_none()
2387 }
2388
2389 /// Returns the instant at which the frame in the slot waited the whole
2390 /// stall window. It is `None` if no frame waits, no window runs, or the
2391 /// body failed.
2392 fn stall_end(&self) -> Option<Instant> {
2393 let stall = self.stall?;
2394 if self.frame.is_none() || self.aborted.is_some() {
2395 return None;
2396 }
2397 stall.since.checked_add(stall.window)
2398 }
2399
2400 /// Starts the wait of the frame in the slot again, from now.
2401 fn restart_stall(&mut self) {
2402 if let Some(stall) = &mut self.stall {
2403 stall.since = Instant::now();
2404 }
2405 }
2406}
2407
2408/// The state of the body that the upload sees while it waits for the response.
2409enum Watch {
2410 /// The body still streams. A body given whole has no writer, so the upload
2411 /// runs its stall window, which ends at the given instant.
2412 Streaming(Option<Instant>),
2413 /// hyper took the end of the body.
2414 Ended,
2415 /// The body failed, for the reason given.
2416 Aborted(String),
2417}
2418
2419impl Exchange {
2420 /// Creates the exchange of a body given whole. The bytes are the frame that
2421 /// hyper takes in parts, and the body is closed. An empty body holds no
2422 /// frame, so it is at its end before hyper polls it.
2423 fn whole(bytes: &Bytes) -> Exchange {
2424 Exchange {
2425 slot: Mutex::new(Slot {
2426 frame: (!bytes.is_empty()).then(|| bytes.clone()),
2427 closed: true,
2428 ..Slot::default()
2429 }),
2430 exact: Some(bytes.len() as u64),
2431 }
2432 }
2433
2434 fn lock(&self) -> MutexGuard<'_, Slot> {
2435 self.slot.lock().expect("upload body mutex")
2436 }
2437
2438 /// Returns the reason for the failure of the body, if the body failed.
2439 fn aborted(&self) -> Option<String> {
2440 self.lock().aborted.clone()
2441 }
2442
2443 /// Hands the body to hyper. This starts the stall window of `stall` from
2444 /// now, and returns `true` if the body is at its end, which the request then
2445 /// declares. The function does not hand over a failed body, and returns
2446 /// the reason for the failure as the error.
2447 fn hand_over(&self, stall: Duration) -> std::result::Result<bool, String> {
2448 let mut slot = self.lock();
2449 if let Some(reason) = &slot.aborted {
2450 return Err(reason.clone());
2451 }
2452 slot.stall = Some(Stall {
2453 window: stall,
2454 since: Instant::now(),
2455 });
2456 slot.empty = slot.at_end();
2457 let empty = slot.empty;
2458 let writer = slot.writer.take();
2459 drop(slot);
2460 wake(writer);
2461 Ok(empty)
2462 }
2463
2464 /// Returns `true` if hyper took the end of the body, with no failure.
2465 fn has_ended(&self) -> bool {
2466 let slot = self.lock();
2467 slot.ended && slot.aborted.is_none()
2468 }
2469
2470 /// Takes the body back from hyper, which gave the request back unwritten.
2471 /// The stall window stops until the next hand-over.
2472 fn withdraw(&self) {
2473 let mut slot = self.lock();
2474 slot.stall = None;
2475 slot.empty = false;
2476 }
2477
2478 /// Fails the body if the frame in the slot waited the whole stall window,
2479 /// and returns the reason. If the frame still has time, or no frame waits,
2480 /// the error holds the instant at which the wait ends.
2481 fn check_stall(&self) -> std::result::Result<String, Option<Instant>> {
2482 let mut slot = self.lock();
2483 let end = slot.stall_end();
2484 let (Some(end), Some(stall)) = (end, slot.stall) else {
2485 return Err(None);
2486 };
2487 if Instant::now() < end {
2488 return Err(Some(end));
2489 }
2490 let message = format!("the upload body was not taken for {:?}", stall.window);
2491 let wakers = slot.abort(|| message.clone());
2492 drop(slot);
2493 wakers.into_iter().for_each(wake);
2494 Ok(message)
2495 }
2496
2497 /// Fails a body that did not end, because its response ended or was
2498 /// dropped. hyper stops the body and closes the connection, and the writer
2499 /// gets a broken pipe.
2500 fn cut(&self) {
2501 let mut slot = self.lock();
2502 if slot.ended {
2503 return;
2504 }
2505 let wakers = slot.abort(|| "the response to the upload ended before its body".into());
2506 drop(slot);
2507 wakers.into_iter().for_each(wake);
2508 }
2509
2510 /// Returns the state of the body, and registers the upload for a wake when
2511 /// the state changes.
2512 fn watch(&self, cx: &mut Context<'_>) -> Watch {
2513 let mut slot = self.lock();
2514 if let Some(reason) = &slot.aborted {
2515 return Watch::Aborted(reason.clone());
2516 }
2517 if slot.ended {
2518 return Watch::Ended;
2519 }
2520 park(&mut slot.upload, cx);
2521 Watch::Streaming(self.exact.and(slot.stall_end()))
2522 }
2523}
2524
2525/// Keeps the waker of `cx` in `waker`, unless the held waker wakes the same
2526/// task.
2527fn park(waker: &mut Option<Waker>, cx: &Context<'_>) {
2528 if !waker
2529 .as_ref()
2530 .is_some_and(|held| held.will_wake(cx.waker()))
2531 {
2532 *waker = Some(cx.waker().clone());
2533 }
2534}
2535
2536/// Wakes `waker`, if a party left one.
2537fn wake(waker: Option<Waker>) {
2538 if let Some(waker) = waker {
2539 waker.wake();
2540 }
2541}
2542
2543/// Polls a timer toward `end`, and is ready after `end`.
2544///
2545/// The function arms the timer once, for the remaining time. If the start of a
2546/// window moves later, as the stall window does with each frame, `end` moves
2547/// later and the timer stays. If the timer fires early, the function arms it
2548/// again for the remaining time.
2549fn poll_until(timer: &mut Option<rt::Deadline>, cx: &mut Context<'_>, end: Instant) -> Poll<()> {
2550 loop {
2551 let left = end.saturating_duration_since(Instant::now());
2552 if left.is_zero() {
2553 *timer = None;
2554 return Poll::Ready(());
2555 }
2556 let deadline = timer.get_or_insert_with(|| rt::Deadline::new(left));
2557 if deadline.poll_expired(cx).is_pending() {
2558 return Poll::Pending;
2559 }
2560 *timer = None;
2561 }
2562}
2563
2564/// The reading end of an upload body, which hyper polls for frames.
2565///
2566/// The reading end takes a frame out of the slot as it is. So the bytes of a
2567/// frame get at most one copy, from the buffer of the caller into the buffer of
2568/// the writer. A body given whole goes in frames of [`UPLOAD_FRAME`] cut from
2569/// its bytes, with no copy. A drop of the end wakes the writer, and each later
2570/// write fails.
2571struct BodyEnd {
2572 exchange: Arc<Exchange>,
2573}
2574
2575impl BodyEnd {
2576 /// Creates the reading end of a body given whole.
2577 fn whole(bytes: &Bytes) -> BodyEnd {
2578 BodyEnd {
2579 exchange: Arc::new(Exchange::whole(bytes)),
2580 }
2581 }
2582
2583 /// Polls for the next frame. A failed body fails the poll. So hyper ends
2584 /// the request unfinished, and does not send a truncated body as a whole
2585 /// body.
2586 fn poll_frame(&mut self, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> {
2587 let mut slot = self.exchange.lock();
2588 slot.polled = true;
2589 if let Some(reason) = &slot.aborted {
2590 return Poll::Ready(Some(Err(std::io::Error::other(reason.clone()))));
2591 }
2592 // hyper takes a body given whole in frames. So the end follows the last
2593 // frame, and the stall window runs over each frame.
2594 if let Some(held) = &mut slot.frame
2595 && held.len() > UPLOAD_FRAME
2596 {
2597 let frame = held.split_to(UPLOAD_FRAME);
2598 slot.restart_stall();
2599 return Poll::Ready(Some(Ok(Frame::data(frame))));
2600 }
2601 if let Some(frame) = slot.frame.take() {
2602 // The last frame of a closed body is also its end. hyper reads the
2603 // end from `is_end_stream`, and does not poll for it.
2604 let wakers = if slot.closed {
2605 slot.end()
2606 } else {
2607 [slot.writer.take(), None]
2608 };
2609 drop(slot);
2610 wakers.into_iter().for_each(wake);
2611 return Poll::Ready(Some(Ok(Frame::data(frame))));
2612 }
2613 if slot.closed {
2614 let wakers = slot.end();
2615 drop(slot);
2616 wakers.into_iter().for_each(wake);
2617 return Poll::Ready(None);
2618 }
2619 park(&mut slot.reader, cx);
2620 Poll::Pending
2621 }
2622
2623 /// Returns `true` if the body has no more frames. hyper asks before it
2624 /// polls, and never polls a body at its end. So this answer records the
2625 /// end, as a poll that finds the end does.
2626 ///
2627 /// hyper frames the request from the first answer. Over HTTP/1.1, a
2628 /// request at its end at that time carries no length of its own. So before
2629 /// the first poll, a body is at its end only if the request declared a
2630 /// length of zero at the hand-over. If a body reached its end after the
2631 /// hand-over, hyper frames it as a stream, and the stream ends empty.
2632 fn is_end_stream(&self) -> bool {
2633 let mut slot = self.exchange.lock();
2634 if slot.ended {
2635 return true;
2636 }
2637 if !slot.at_end() || !(slot.polled || slot.empty) {
2638 return false;
2639 }
2640 let wakers = slot.end();
2641 drop(slot);
2642 wakers.into_iter().for_each(wake);
2643 true
2644 }
2645}
2646
2647impl Drop for BodyEnd {
2648 fn drop(&mut self) {
2649 let mut slot = self.exchange.lock();
2650 slot.gone = true;
2651 let writer = slot.writer.take();
2652 drop(slot);
2653 wake(writer);
2654 }
2655}
2656
2657/// The request body of an upload, which its response holds. If the response
2658/// ends or is dropped before the request body ends, the request body fails. So
2659/// hyper stops the body and closes the connection.
2660struct RequestEnd {
2661 exchange: Arc<Exchange>,
2662}
2663
2664impl Drop for RequestEnd {
2665 fn drop(&mut self) {
2666 self.exchange.cut();
2667 }
2668}
2669
2670type H1Sender = hyper::client::conn::http1::SendRequest<RequestBody>;
2671type H2Sender = hyper::client::conn::http2::SendRequest<RequestBody>;
2672
2673/// A connection ready to carry one request.
2674enum Sender {
2675 /// An HTTP/1.1 connection, which carries one request at a time. It goes
2676 /// back to the pool when its response body ends.
2677 H1(H1Sender),
2678 /// A handle on a pooled HTTP/2 connection, which multiplexes requests.
2679 H2(H2Sender),
2680}
2681
2682/// The connections pooled under one [`PoolKey`].
2683#[derive(Default)]
2684struct PoolEntry {
2685 /// The HTTP/2 connection of the origin, if one is open.
2686 h2: Option<H2Sender>,
2687 /// The idle HTTP/1.1 connections. The connection that became idle last is
2688 /// at the end.
2689 h1: Vec<IdleH1>,
2690}
2691
2692/// An idle HTTP/1.1 connection in the pool, and the instant at which it became
2693/// idle.
2694struct IdleH1 {
2695 sender: H1Sender,
2696 since: Instant,
2697}
2698
2699/// The shared state of a fetcher. A [`Fetcher`] is a handle on this state.
2700struct Inner {
2701 mirrors: Vec<Mirror>,
2702 headers: Vec<(HeaderName, HeaderValue)>,
2703 tls: ClientConfigs,
2704 /// `true` if a handshake has the anchors to verify the peer.
2705 ///
2706 /// A store with no anchor gets here only for a fetcher with all mirrors in
2707 /// cleartext, which opens no handshake that reads the store. The fetcher
2708 /// then refuses a TLS destination. A bypass variant of [`TrustRoots`] reads
2709 /// no store and sets `true`, because its handshake reads no anchor and
2710 /// completes.
2711 has_trust_anchors: bool,
2712 /// `true` if a client certificate is configured, so the two client
2713 /// configurations differ. If none is configured, each connection opens
2714 /// over one configuration, and the pool holds one entry for each origin.
2715 client_identity: bool,
2716 /// The proxy of each scheme, resolved at construction.
2717 proxies: Proxies,
2718 /// `true` if a credential can reach a cleartext destination. A fetch and
2719 /// an upload then skip the cleartext check.
2720 allow_cleartext_credentials: bool,
2721 /// The signer of each attempt at the origin that the route names.
2722 signer: Option<Arc<dyn RequestSigner>>,
2723 max_retries: u32,
2724 max_redirects: u32,
2725 connect_timeout: Duration,
2726 progress_timeout: Duration,
2727 low_speed: Option<LowSpeed>,
2728 fetch_timeout: Option<Duration>,
2729 /// The number of requests that the gate admits at one time, at least 1.
2730 max_outstanding: usize,
2731 gate: Arc<Gate>,
2732 h2_connection_window: u32,
2733 pool: Mutex<HashMap<PoolKey, PoolEntry>>,
2734}
2735
2736/// Returns the HTTP/2 flow-control window of the connection for a fetcher that
2737/// admits `max_outstanding` requests: one stream window for each request.
2738///
2739/// A receiver credits a window back when the caller reads the data. So a
2740/// parked stream, whose body the caller received and did not read yet, holds
2741/// its own credit. The connection window is the sum of the stream windows, so
2742/// that credit belongs to the parked stream alone. Each other open stream
2743/// still has a full window.
2744///
2745/// For example, the HTTP pull of `ostrya` parks content bodies while they wait
2746/// for a write permit. The metadata object that its scan waits for uses the
2747/// same connection.
2748///
2749/// The cost is the received and unread data that one connection can hold,
2750/// which is this window. At the default limit of 8, it is 16 MiB.
2751fn h2_connection_window(max_outstanding: usize) -> u32 {
2752 u32::try_from(max_outstanding)
2753 .unwrap_or(u32::MAX)
2754 .saturating_mul(H2_STREAM_WINDOW)
2755 .min(H2_MAX_WINDOW)
2756}
2757
2758/// A failed attempt, and the retry class of the failure.
2759enum Failure {
2760 /// A transport failure, or a status that a later attempt can avoid.
2761 Retry(Error),
2762 /// A definitive answer, which a retry gets again.
2763 Fatal(Error),
2764 /// A failure of the request itself, which no destination and no round
2765 /// avoids. The request ends with it.
2766 Final(Error),
2767}
2768
2769impl Failure {
2770 /// Returns the error of the failure, of any kind.
2771 fn into_error(self) -> Error {
2772 match self {
2773 Failure::Retry(e) | Failure::Fatal(e) | Failure::Final(e) => e,
2774 }
2775 }
2776
2777 /// Returns the cap of the error body that `keep` asks for in the class of
2778 /// this failure, or `None` if the fetch keeps no response of this class.
2779 fn kept_cap(&self, keep: Option<Keep>) -> Option<u64> {
2780 let keep = keep?;
2781 match self {
2782 Failure::Retry(_) if keep.retryable => Some(keep.cap),
2783 Failure::Fatal(_) if keep.definitive => Some(keep.cap),
2784 _ => None,
2785 }
2786 }
2787
2788 /// Puts `kept` into the [`Error::HttpStatus`] of this failure. A failure
2789 /// of another error stays as it is.
2790 fn with_response(mut self, kept: ErrorResponse) -> Failure {
2791 if let Failure::Retry(Error::HttpStatus { response, .. })
2792 | Failure::Fatal(Error::HttpStatus { response, .. }) = &mut self
2793 {
2794 *response = Some(Box::new(kept));
2795 }
2796 self
2797 }
2798}
2799
2800/// The unsuccessful responses that one attempt of a fetch keeps.
2801///
2802/// A fetch reports one failure. So an attempt reads the body of a failure
2803/// only if that failure can become the reported one. The flags follow the
2804/// failure order of [`Fetcher::fetch`].
2805#[derive(Clone, Copy)]
2806struct Keep {
2807 /// The largest body to keep: [`FetchRequest::max_error_body`].
2808 cap: u64,
2809 /// `true` if no failure is reported yet, so a retryable failure becomes
2810 /// the reported one.
2811 retryable: bool,
2812 /// `true` if no definitive answer is reported yet, so a definitive answer
2813 /// becomes the reported one.
2814 definitive: bool,
2815}
2816
2817/// A failed upload attempt, and the send state of the request.
2818enum UploadFailure {
2819 /// No part of the request reached hyper, so the round continues as for a
2820 /// fetch.
2821 Unsent(Failure),
2822 /// hyper took the request, so the upload ends with
2823 /// [`Error::UploadInterrupted`] of this URL and message. A sent request has
2824 /// no other error, and [`Error::is_unsent`] reads this fact.
2825 Sent { url: String, message: String },
2826}
2827
2828/// The parts that each attempt of one upload sends, set before admission.
2829struct UploadPlan<'a> {
2830 method: Method,
2831 headers: &'a [(HeaderName, HeaderValue)],
2832 /// The bytes of a body given whole, which a followed redirect sends again.
2833 /// A streamed body has none, so the upload follows no redirect of it.
2834 bytes: Option<Bytes>,
2835 /// The SHA-256 of `bytes` that the caller gave, which the signer of each
2836 /// attempt and each hop gets.
2837 sha256: Option<[u8; 32]>,
2838 max_response: u64,
2839 response_timeout: Duration,
2840}
2841
2842/// The result of a request after hyper took it.
2843enum Answer<T> {
2844 /// The send resolved, with the response head or the error of hyper.
2845 Sent(T),
2846 /// The writer failed the body before the response head arrived.
2847 Aborted(String),
2848 /// The body ended, and no response head followed within the window.
2849 Silent(Duration),
2850}
2851
2852/// The response of one upload hop, its protocol, and the body that the request
2853/// sent. It also holds the HTTP/1.1 connection, which goes back to the pool
2854/// when the response body ends.
2855type UploadResponse = (Response<Incoming>, Protocol, RequestEnd, Option<H1Sender>);
2856
2857/// An async HTTP client for one remote.
2858///
2859/// A fetcher holds the mirrors, the headers, the credentials, and the TLS
2860/// configuration of one remote. It serves a [`Target::Url`] from the origin of
2861/// that URL. A clone of a `Fetcher` is another handle on the same connection
2862/// pool and the same admission limit. The clone has the counters of received
2863/// body bytes of the handle. [`counted`](Fetcher::counted) gives a handle with
2864/// more counters.
2865///
2866/// # Connections
2867///
2868/// The TLS handshake selects the protocol: ALPN offers `h2` and `http/1.1`,
2869/// and the fetcher uses the choice of the server. Over cleartext, the fetcher
2870/// uses HTTP/1.1. The pool keeps one HTTP/2 connection for each origin, which
2871/// carries concurrent requests. The pool also keeps HTTP/1.1 connections, and
2872/// the fetcher uses one again after the previous body is read to the end.
2873///
2874/// The pool key holds three terms:
2875///
2876/// - the endpoint of the connection
2877/// - `true` if the connection presents the configured client certificate
2878/// - `true` if the connection goes to a proxy and carries absolute-form
2879/// requests.
2880///
2881/// The endpoint is the origin for a direct connection and for a tunnel,
2882/// because the TLS of a tunnel reaches the origin. For a proxied cleartext
2883/// connection, the endpoint is the proxy. So a URL target shares a connection
2884/// with a mirror at the same origin. One proxy connection carries requests for
2885/// all cleartext origins.
2886///
2887/// An unsuccessful status, or a `Content-Length` over the cap of the request,
2888/// ends an attempt with a response body in flight. If the declared length is
2889/// 64 KiB or less, the fetcher reads the body to the end. The HTTP/1.1
2890/// connection then goes back to the pool. If the declared length is larger, or
2891/// if there is none, the fetcher closes the connection.
2892///
2893/// A fetch with [`FetchRequest::max_error_body`] reads the body of the
2894/// unsuccessful response that it reports, up to that cap, with or without a
2895/// declared length. If the body ends within the cap, the HTTP/1.1 connection
2896/// goes back to the pool. If it grows past the cap, the fetcher closes the
2897/// connection. [`Fetcher::fetch`] states the rule in "Error responses".
2898///
2899/// A 404 is the usual answer for an object that the remote does not hold. So
2900/// this rule saves a connection setup for each absent object.
2901///
2902/// All such reads of one attempt share one
2903/// [`progress_timeout`](FetcherOptions::progress_timeout)
2904/// window, whatever the number of hops. A peer can declare a short body on
2905/// each hop and send fewer bytes. Such a peer uses the window once, and the
2906/// later reads close their connections and do not wait.
2907#[derive(Clone)]
2908pub struct Fetcher {
2909 inner: Arc<Inner>,
2910 /// The counters that get the bytes of each response body of a request of
2911 /// this handle.
2912 received: Arc<[Arc<AtomicU64>]>,
2913}
2914
2915impl std::fmt::Debug for Fetcher {
2916 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2917 f.debug_struct("Fetcher")
2918 .field("mirrors", &self.inner.mirrors)
2919 .finish_non_exhaustive()
2920 }
2921}
2922
2923impl Fetcher {
2924 /// Creates a fetcher from `options`.
2925 ///
2926 /// If the mirror list is empty, the fetcher serves [`Target::Url`] requests
2927 /// alone.
2928 ///
2929 /// The fetcher has no counters of received body bytes.
2930 /// [`counted`](Fetcher::counted) gives a handle that has counters.
2931 ///
2932 /// The function is async, because [`TrustRoots::System`], the default,
2933 /// reads the host trust store on the blocking pool. An encrypted client key
2934 /// runs a key derivation function, also on the blocking pool. Under
2935 /// [`TrustRoots::Pem`] with no encrypted client key, all work is in memory,
2936 /// and the function never yields.
2937 ///
2938 /// # Trust store
2939 ///
2940 /// The function reads the system store if a fetch can open a handshake.
2941 /// That is the case if one or more mirrors are `https`. It is also the case
2942 /// if the mirror list is empty, because a request can then name an `https`
2943 /// URL. It is also the case if
2944 /// [`max_redirects`](FetcherOptions::max_redirects) is more than zero,
2945 /// because a redirect can go to an `https` URL.
2946 ///
2947 /// A fetcher with all mirrors `http` that follows no redirect reads no
2948 /// store and holds no trust anchor. If a request of that fetcher names an
2949 /// `https` URL of its own, the fetch fails before admission and names the
2950 /// origin. A host without a CA bundle still reaches a cleartext remote.
2951 ///
2952 /// Under either bypass variant of [`TrustRoots`], the function reads no
2953 /// store, so an empty host store fails no fetcher. With no encrypted client
2954 /// key, the function then never yields.
2955 ///
2956 /// # Errors
2957 ///
2958 /// - [`Error::Fetch`] if a [`low_speed`](FetcherOptions::low_speed) rule
2959 /// holds a zero.
2960 /// - [`Error::Fetch`] if a mirror URL is not a valid absolute URL, has no
2961 /// usable host, or holds a query string or userinfo.
2962 /// - [`Error::Fetch`] if a mirror URL names a port that is not a number
2963 /// from 0 to 65535.
2964 /// - [`Error::Unsupported`] if the scheme of a mirror URL is neither `http`
2965 /// nor `https`.
2966 /// - [`Error::Fetch`] if a header name or value is invalid, or if a header
2967 /// is `Host` or a header that the connection layer sets.
2968 /// - [`Error::Fetch`] if a mirror is cleartext `http`, the options hold a
2969 /// credential, and
2970 /// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
2971 /// is `false`. The credentials are
2972 /// [`basic_auth`](FetcherOptions::basic_auth),
2973 /// [`bearer_token`](FetcherOptions::bearer_token),
2974 /// [`signer`](FetcherOptions::signer), and an `Authorization`,
2975 /// `Proxy-Authorization`, or `Cookie` header.
2976 /// - [`Error::Fetch`] if two of these are set:
2977 /// [`basic_auth`](FetcherOptions::basic_auth),
2978 /// [`bearer_token`](FetcherOptions::bearer_token),
2979 /// [`signer`](FetcherOptions::signer), and an `Authorization` header.
2980 /// - [`Error::Fetch`] if [`basic_auth`](FetcherOptions::basic_auth) does
2981 /// not give a valid header value, or if
2982 /// [`bearer_token`](FetcherOptions::bearer_token) does not have the
2983 /// token68 syntax.
2984 /// - [`Error::Unsupported`] if a proxy URL is not `http://host[:port]`,
2985 /// `socks5://host[:port]`, or `socks5h://host[:port]`, from the options
2986 /// or from the environment.
2987 /// - [`Error::Unsupported`] if a SOCKS5 URL has a userinfo that
2988 /// [SOCKS proxies](Proxy#socks-proxies) refuses.
2989 /// - [`Error::Unsupported`] if a proxy variable has
2990 /// [white space](Proxy#white-space) around its value.
2991 /// - [`Error::Fetch`] if the TLS material does not parse or the TLS setup
2992 /// fails: a trust anchor, the client certificate, or the client key.
2993 /// [`ClientIdentity::key_passphrase`] states the refusals of a client
2994 /// key.
2995 /// - [`Error::Fetch`] if the system trust store holds no certificate, and
2996 /// one or more mirrors are `https` or the mirror list is empty.
2997 pub async fn new(options: FetcherOptions) -> Result<Fetcher> {
2998 let Checked {
2999 mirrors,
3000 headers,
3001 proxies,
3002 } = checked(&options)?;
3003 let max_outstanding = options.max_outstanding.max(1);
3004 // A fetcher with no mirror serves the URLs of its requests, and each
3005 // of them can be `https`. So it must hold trust anchors, and an empty
3006 // system store fails it as for an `https` mirror.
3007 let https = mirrors.is_empty() || mirrors.iter().any(|mirror| mirror.origin.tls);
3008 // A redirect can go from a cleartext mirror to a TLS origin. So the
3009 // fetcher also reads the system store if it follows redirects. If not,
3010 // a fetch reaches a TLS origin only through a URL target of its own. A
3011 // fetcher with no anchor refuses that target before admission.
3012 let reaches_tls = https || options.max_redirects > 0;
3013 let tls = client_config(&options.tls, options.http2, https, reaches_tls).await?;
3014 Ok(Fetcher {
3015 inner: Arc::new(Inner {
3016 mirrors,
3017 headers,
3018 has_trust_anchors: tls.has_trust_anchors,
3019 client_identity: options.tls.client_identity.is_some(),
3020 proxies,
3021 tls,
3022 allow_cleartext_credentials: options.allow_cleartext_credentials,
3023 signer: options.signer,
3024 max_retries: options.max_retries,
3025 max_redirects: options.max_redirects,
3026 connect_timeout: options.connect_timeout,
3027 progress_timeout: options.progress_timeout,
3028 low_speed: options.low_speed,
3029 fetch_timeout: options.fetch_timeout,
3030 max_outstanding,
3031 gate: Arc::new(Gate::new(max_outstanding)),
3032 h2_connection_window: h2_connection_window(max_outstanding),
3033 pool: Mutex::new(HashMap::new()),
3034 }),
3035 received: Arc::new([]),
3036 })
3037 }
3038
3039 /// Returns a handle on this fetcher that adds counters of received body
3040 /// bytes.
3041 ///
3042 /// The new handle shares the configuration, the connection pool, and the
3043 /// admission limit of this handle. It has the counters of this handle and
3044 /// the counters of `received`. A clone of the new handle has the same
3045 /// counters.
3046 ///
3047 /// Each response body of a request of the new handle adds the bytes that it
3048 /// takes from the connection to each of these counters. This includes the
3049 /// bytes of a body before it fails, the body of a [`Refetch`], a body that
3050 /// the caller drops before its end, and the response body of an upload. A
3051 /// request does not count a response that it does not give to the caller:
3052 /// a redirect, an unsuccessful status of a fetch, or a refused response.
3053 ///
3054 /// The counters of this handle do not change. A request of this handle adds
3055 /// to the counters of this handle alone. Each data frame costs one relaxed
3056 /// atomic add for each counter. A counter that the new handle has two times
3057 /// gets the bytes two times.
3058 pub fn counted(&self, received: Vec<Arc<AtomicU64>>) -> Fetcher {
3059 Fetcher {
3060 inner: Arc::clone(&self.inner),
3061 received: self.received.iter().cloned().chain(received).collect(),
3062 }
3063 }
3064
3065 /// Returns the number of requests that the fetcher admits at one time.
3066 ///
3067 /// The number is [`max_outstanding`](FetcherOptions::max_outstanding) of
3068 /// the options, and at least 1. All handles on one fetcher share this
3069 /// limit.
3070 pub fn max_outstanding(&self) -> usize {
3071 self.inner.max_outstanding
3072 }
3073
3074 /// Sends `request` to each destination in turn and returns the response.
3075 ///
3076 /// # Retries
3077 ///
3078 /// A path target goes to each mirror, in the mirror order. The fetch
3079 /// resolves the destination of a mirror at the attempt that uses it. A URL
3080 /// target has the one destination that the URL names.
3081 ///
3082 /// - The fetch tries each destination in order before it retries.
3083 /// - Transport failures and the statuses 408, 429, and 5xx are retryable.
3084 /// If one or more destinations of a round fail that way, the fetch
3085 /// repeats the round, up to [`max_retries`](FetcherOptions::max_retries)
3086 /// times. The delay before a repeat starts at 250ms, doubles each time,
3087 /// and stops at two seconds. A repeated round asks only the destinations
3088 /// with a retryable failure.
3089 /// - Each other unsuccessful status is definitive. The fetch does not ask
3090 /// that destination again, because its answer is the same in each round.
3091 /// - The expiry of [`connect_timeout`](FetcherOptions::connect_timeout),
3092 /// [`progress_timeout`](FetcherOptions::progress_timeout), or
3093 /// [`low_speed`](FetcherOptions::low_speed) is a transport failure. The
3094 /// fetch reports the deadline that expires first.
3095 ///
3096 /// The hop count belongs to one attempt. So a retryable status on a hop
3097 /// makes the whole attempt retryable, and the repeated round starts again
3098 /// from the destination that the route names.
3099 ///
3100 /// The retries end at the response head. So if a body fails in transit,
3101 /// the caller gets a failed read. [`refetching`](Fetcher::refetching)
3102 /// fetches such a body again.
3103 ///
3104 /// # Failure order
3105 ///
3106 /// A fetch ends if it has no more destinations to ask or no more rounds to
3107 /// repeat. In both cases, it reports a definitive answer if it got one, and
3108 /// the first retryable failure if not.
3109 ///
3110 /// A caller can act on a definitive answer, for example a 404 that states
3111 /// that the object is absent. So the fetch reports such an answer from any
3112 /// round, and an earlier retryable failure does not hide it. Of two
3113 /// definitive answers, the fetch reports the answer that it got first. In
3114 /// one round, this is the mirror order.
3115 ///
3116 /// # Redirects
3117 ///
3118 /// A 301, 302, 303, 307, or 308 sends the attempt to the URL of its
3119 /// `Location` header, up to [`max_redirects`](FetcherOptions::max_redirects)
3120 /// times. A fetch is a GET, so none of the five statuses changes the method
3121 /// of the next hop.
3122 ///
3123 /// The fetch resolves `Location` against the URL of the response that
3124 /// carries it. So `Location` can be an absolute URL, a relative URL
3125 /// (`/other/path`, `sibling`), or a scheme-relative URL (`//host/path`). The
3126 /// resolution normalizes the result, as the HTTP specification prescribes
3127 /// for a redirect:
3128 ///
3129 /// - it resolves dot segments
3130 /// - it reads a backslash as a path separator
3131 /// - it removes tabs and newlines
3132 /// - it percent-encodes a character that a path or a query cannot carry
3133 /// - it puts an IPv4 or an IPv6 host in canonical form
3134 /// - it removes the fragment.
3135 ///
3136 /// A [`Target::Url`] goes on the wire as the caller wrote it. So one string
3137 /// as a URL target and as a `Location` can reach the server as two
3138 /// different request targets.
3139 ///
3140 /// The fetch refuses two hops definitively: a scheme other than `http` or
3141 /// `https`, and a hop from `https` to `http`. The [`Error::Fetch`] names the
3142 /// URL that redirected and the URL that it named. On a fetcher with no trust
3143 /// anchors, the fetch also refuses a hop to a TLS origin in the same way.
3144 /// The fetch follows a hop from `http` to `https`.
3145 ///
3146 /// If a response with one of the five statuses has no readable `Location`,
3147 /// the fetch reports the status, whatever the hop count. This applies to a
3148 /// missing header, an empty value, a value that is not text, and a value
3149 /// that the resolution cannot read.
3150 ///
3151 /// `Authorization`, `Proxy-Authorization`, and `Cookie` from either layer
3152 /// go to the origin that the route names. They also go to a hop at that
3153 /// origin: the same scheme, host, and port.
3154 ///
3155 /// The fetch removes them for a hop at another origin. A removed credential
3156 /// stays removed for the rest of the attempt, also on a redirect back to the
3157 /// named origin. At that time, the operator of the other origin has the
3158 /// request.
3159 ///
3160 /// The [`signer`](FetcherOptions::signer) follows the same rule. It signs
3161 /// each hop at the named origin again, with the path and the query of that
3162 /// hop. It signs no hop at another origin, and no hop after it.
3163 ///
3164 /// All other headers go to each hop, also the `User-Agent` and the
3165 /// `Accept-Encoding` of the fetcher. The fetcher presents a configured
3166 /// client certificate to the origin that the route names and to no other
3167 /// origin. So the pool keeps the connections with the certificate apart
3168 /// from the connections without it.
3169 ///
3170 /// The fetch discards the body of an intermediate response as it discards
3171 /// the body of an unsuccessful response. So if the declared length is
3172 /// 64 KiB or less, the HTTP/1.1 connection goes back to the pool. A chain
3173 /// on one origin then uses one connection. If the intermediate responses
3174 /// declare more, or declare no length, the chain opens a connection for
3175 /// each hop.
3176 ///
3177 /// The validators go to each hop, because they describe the resource. A 304
3178 /// from any hop is the answer of the fetch. Each message names the URL of
3179 /// the response that answered, which after a redirect is the URL of the
3180 /// last hop.
3181 ///
3182 /// A fetch with [`max_error_body`](FetchRequest::max_error_body) and a
3183 /// redirect limit of zero gets each redirect as an unsuccessful response.
3184 /// So the caller reads its headers, for example `Location`, and its body.
3185 /// A redirect with no usable `Location` is also such a response, at any
3186 /// limit.
3187 ///
3188 /// # Content coding
3189 ///
3190 /// A fetch gives the bytes that the remote stores. So each request carries
3191 /// `Accept-Encoding: identity`, and asks for no content coding. Without
3192 /// that header, a server can compress a response and stay within the HTTP
3193 /// specification. The body then holds bytes other than the bytes that the
3194 /// checksum of the object names.
3195 ///
3196 /// A 200 response, or a 206 response to a request with a `Range` header,
3197 /// fails the attempt definitively with [`Error::ContentEncoded`] in two
3198 /// cases: a `Content-Encoding` other than `identity`, or a
3199 /// `Transfer-Encoding` other than `chunked` and `identity`. This applies
3200 /// whichever layer asked for the coding. A caller that wants a coded body
3201 /// decodes it outside the fetcher.
3202 ///
3203 /// `chunked` frames a message, and the connection removes the framing. So a
3204 /// response with `chunked` alone gives the body as the remote wrote it.
3205 ///
3206 /// # Error responses
3207 ///
3208 /// A request with [`max_error_body`](FetchRequest::max_error_body) set
3209 /// keeps the unsuccessful response that the fetch reports. The
3210 /// [`Error::HttpStatus`] then carries an [`ErrorResponse`] with the
3211 /// headers of that response, and its body if the whole body is within the
3212 /// cap.
3213 ///
3214 /// - The fetch reads the body of a failure only if the failure order can
3215 /// make it the reported failure. So it reads at most two bodies: one
3216 /// retryable failure and one definitive answer. It keeps the body of the
3217 /// failure that it reports. If each round gets a 503, the error holds
3218 /// the body of the first 503. A 503 and then a 404 give the body of the
3219 /// 404.
3220 /// - The read takes place within one
3221 /// [`progress_timeout`](FetcherOptions::progress_timeout) from the
3222 /// arrival of the response head, and within
3223 /// [`fetch_timeout`](FetcherOptions::fetch_timeout). The
3224 /// [`low_speed`](FetcherOptions::low_speed) rule does not apply to it.
3225 /// - The fetch does not read a body that declares a coding or a
3226 /// `Content-Length` over the cap. It discards such a body, and the error
3227 /// holds the headers alone.
3228 /// - A body that grows past the cap, fails in transit, or does not end
3229 /// within the window gives the headers alone. The fetch keeps no part of
3230 /// such a body.
3231 /// - The read never changes the retry class of the status.
3232 /// - The bytes of a kept body do not count in the received counters of
3233 /// [`counted`](Fetcher::counted).
3234 ///
3235 /// Before a body arrives, the read reserves at most 64 KiB, whatever
3236 /// length the response declares. The capacity of a kept body never passes
3237 /// the cap. So the fetch holds at most two kept bodies of at most the cap
3238 /// each, one retryable and one definitive, and one frame of the body that
3239 /// it reads.
3240 ///
3241 /// # Errors
3242 ///
3243 /// If more than one destination fails, the failure order rules state which
3244 /// error the fetch reports.
3245 ///
3246 /// - [`Error::Fetch`] before admission, if a path holds a `?` or a `#`, if
3247 /// the query of a [`Target::PathQuery`] holds a `#`, or if the fetcher
3248 /// has no mirror for a path target.
3249 /// - [`Error::Fetch`] before admission, if a URL target is not a valid
3250 /// absolute URL, or holds a fragment or userinfo.
3251 /// - [`Error::Unsupported`] if the scheme of a URL target is neither `http`
3252 /// nor `https`.
3253 /// - [`Error::Fetch`] before admission, if a request header is invalid, is
3254 /// `Host`, or is a header that the connection layer sets.
3255 /// - [`Error::Fetch`] before admission, if an `Authorization` header is
3256 /// beside [`basic_auth`](FetchRequest::basic_auth).
3257 /// - [`Error::Fetch`] before admission, if the fetcher has a
3258 /// [`signer`](FetcherOptions::signer) and the request carries
3259 /// [`basic_auth`](FetchRequest::basic_auth) or an `Authorization`
3260 /// header.
3261 /// - [`Error::Fetch`] before admission, if a credential can reach a
3262 /// cleartext destination, and neither
3263 /// [`allow_cleartext_credentials`](FetchRequest::allow_cleartext_credentials)
3264 /// nor [`FetcherOptions::allow_cleartext_credentials`] is `true`.
3265 /// - [`Error::Fetch`] before admission, if the route names a TLS
3266 /// destination and the fetcher holds no trust anchors.
3267 /// - [`Error::Fetch`] if a transport failure ends the rounds: a failed
3268 /// connect, handshake, or proxy `CONNECT`, or an expired deadline.
3269 /// - [`Error::Fetch`] if the fetch refuses a redirect hop, as the redirect
3270 /// rules state.
3271 /// - [`Error::Fetch`] if hyper cannot build a request, for example from an
3272 /// invalid validator value.
3273 /// - The error of the [`signer`](FetcherOptions::signer), unchanged, if it
3274 /// fails. An [`Error::Fetch`] if it returns a header that a request
3275 /// cannot carry. The fetch asks no other destination and repeats no
3276 /// round.
3277 /// - [`Error::Fetch`] if [`fetch_timeout`](FetcherOptions::fetch_timeout)
3278 /// expires.
3279 /// - [`Error::HttpStatus`] if a destination answers with a status other
3280 /// than 200 and 304, and other than 206 to a request with a `Range`
3281 /// header. This includes a redirect that the fetch does not
3282 /// follow: no usable `Location`, or a redirect limit of zero. With
3283 /// [`max_error_body`](FetchRequest::max_error_body), the error carries
3284 /// the response, as the rules of the error responses state.
3285 /// - [`Error::RedirectLimit`] if an attempt follows
3286 /// [`max_redirects`](FetcherOptions::max_redirects) redirects, and the
3287 /// next response names a URL to follow.
3288 /// - [`Error::FetchTooLarge`] if the `Content-Length` of the response is
3289 /// more than [`max_size`](FetchRequest::max_size).
3290 /// - [`Error::ContentEncoded`] if the response declares a coding, as the
3291 /// content coding rules state.
3292 pub async fn fetch(&self, request: FetchRequest<'_>) -> Result<Fetched> {
3293 let (fetched, _) = self
3294 .fetch_budgeted(&request, self.inner.max_retries)
3295 .await?;
3296 Ok(fetched)
3297 }
3298
3299 /// Returns a [`Refetch`] of `request`, which fetches a failed body again.
3300 ///
3301 /// [`Refetch`] states the budget that it spends.
3302 pub fn refetching<'r>(&self, request: FetchRequest<'r>) -> Refetch<'_, 'r> {
3303 Refetch {
3304 fetcher: self,
3305 request,
3306 left: self.inner.max_retries,
3307 round: 0,
3308 interrupted: Arc::new(AtomicBool::new(false)),
3309 }
3310 }
3311
3312 /// Fetches `request`, and repeats a round at most `max_retries` times.
3313 /// Returns the response and the number of repeated rounds.
3314 async fn fetch_budgeted(
3315 &self,
3316 request: &FetchRequest<'_>,
3317 max_retries: u32,
3318 ) -> Result<(Fetched, u32)> {
3319 // The target, the headers, their credentials, and the anchors of a TLS
3320 // destination are the same for each destination. So the fetch settles
3321 // all of them before admission, and reports a failure of them one
3322 // time. The fetch takes no permit and opens no socket for it.
3323 let route = self.route(request.target)?;
3324 if self.inner.signer.is_some() {
3325 refuse_beside_signer(request.headers, request.basic_auth.is_some(), false)?;
3326 }
3327 let headers = merge_headers(
3328 &self.inner.headers,
3329 request.headers,
3330 request.basic_auth,
3331 None,
3332 )?;
3333 if !request.allow_cleartext_credentials && !self.inner.allow_cleartext_credentials {
3334 self.check_cleartext(&route, &headers)?;
3335 }
3336 self.check_trust_anchors(&route)?;
3337 let permit = self.inner.gate.acquire(request.priority).await;
3338 let rounds = self.rounds(request, &route, &headers, permit, max_retries);
3339 let Some(limit) = self.inner.fetch_timeout else {
3340 return rounds.await;
3341 };
3342 // The expiry drops the rounds, the attempt in flight, and the permit.
3343 // So the slot is free before the fetch reports the failure.
3344 match within(limit, rounds).await {
3345 Some(result) => result,
3346 None => Err(Error::Fetch(format!(
3347 "fetch of {} timed out after {limit:?}",
3348 request.target.describe()
3349 ))),
3350 }
3351 }
3352
3353 /// Returns the destinations of a fetch of `target`, in the order in which
3354 /// the fetch asks them.
3355 ///
3356 /// A URL target names its one destination, which this function parses. A
3357 /// path target, with or without a query, goes to the mirrors, so a
3358 /// fetcher with no mirror has no destination for it. The signer of the
3359 /// fetcher, if there is one, gives the form of the path.
3360 fn route<'a>(&self, target: Target<'a>) -> Result<Route<'a>> {
3361 let (path, query) = match target {
3362 Target::Url(url) => return Ok(Route::One(parse_url(url)?)),
3363 Target::Path(path) => (path, None),
3364 Target::PathQuery { path, query } => (path, Some(query)),
3365 };
3366 check_path(path)?;
3367 if let Some(query) = query {
3368 check_query(path, query)?;
3369 }
3370 if self.inner.mirrors.is_empty() {
3371 return Err(Error::Fetch(format!(
3372 "fetch of the path {} has nowhere to go: no mirror is configured",
3373 target.describe()
3374 )));
3375 }
3376 let path = match &self.inner.signer {
3377 Some(signer) => signer.request_path(path)?,
3378 None => Cow::Borrowed(path),
3379 };
3380 Ok(Route::Mirrors { path, query })
3381 }
3382
3383 /// Refuses a fetch if its headers carry a credential that a cleartext
3384 /// destination gets in the clear.
3385 ///
3386 /// The fetch withholds a credential from no destination. So one cleartext
3387 /// destination that the fetch can reach is enough for a refusal. The other
3388 /// choice is to send the request without the credential, which gets a 401
3389 /// that names nothing.
3390 fn check_cleartext(
3391 &self,
3392 route: &Route<'_>,
3393 headers: &[(HeaderName, HeaderValue)],
3394 ) -> Result<()> {
3395 // A signer is a credential, as an `Authorization` header is.
3396 if self.inner.signer.is_none() && !headers.iter().any(|(name, _)| is_credential(name)) {
3397 return Ok(());
3398 }
3399 let Some(origin) = self.matching_origin(route, |origin| !origin.tls) else {
3400 return Ok(());
3401 };
3402 Err(Error::Fetch(format!(
3403 "the request carries credentials, which the cleartext origin {origin} would receive \
3404 in the clear: fetch over https, drop the credentials, or set \
3405 allow_cleartext_credentials on the request or on the fetcher"
3406 )))
3407 }
3408
3409 /// Refuses a fetch if its route names a TLS destination and the fetcher
3410 /// holds no trust anchors.
3411 ///
3412 /// A handshake verifies the server certificate against an anchor, so a
3413 /// fetcher with no anchor reaches no TLS origin. Only one case gets here: a
3414 /// request with an `https` URL of its own, on a fetcher with all mirrors in
3415 /// cleartext. Each other combination of route and anchors fails
3416 /// [`Fetcher::new`].
3417 ///
3418 /// The handshake reports this case as an unknown issuer. That is a
3419 /// retryable failure, which uses all rounds and all backoffs before it
3420 /// names the cause. So the refusal occurs here, before admission.
3421 ///
3422 /// This function reads the destinations of the route. A redirect hop names
3423 /// an origin that the server chooses. If that origin is TLS, the attempt
3424 /// refuses the hop with the same message, from [`no_trust_anchors`].
3425 fn check_trust_anchors(&self, route: &Route<'_>) -> Result<()> {
3426 if self.inner.has_trust_anchors {
3427 return Ok(());
3428 }
3429 let Some(origin) = self.matching_origin(route, |origin| origin.tls) else {
3430 return Ok(());
3431 };
3432 Err(no_trust_anchors(origin))
3433 }
3434
3435 /// Returns the `scheme://authority` of the first destination on `route`
3436 /// whose origin `wanted` accepts.
3437 fn matching_origin<'a>(
3438 &'a self,
3439 route: &'a Route<'_>,
3440 wanted: fn(&Origin) -> bool,
3441 ) -> Option<&'a str> {
3442 match route {
3443 Route::Mirrors { .. } => self
3444 .inner
3445 .mirrors
3446 .iter()
3447 .find(|mirror| wanted(&mirror.origin))
3448 .map(|mirror| mirror.prefix.as_str()),
3449 Route::One(destination) => {
3450 wanted(&destination.origin).then(|| destination.origin_url())
3451 }
3452 }
3453 }
3454
3455 /// Tries each destination in turn, and repeats the round at most
3456 /// `max_retries` times while a destination has a retryable failure.
3457 ///
3458 /// The permit moves into the body of a successful round. If no round
3459 /// succeeds, the permit drops with this future. A success returns the
3460 /// number of repeated rounds.
3461 async fn rounds(
3462 &self,
3463 request: &FetchRequest<'_>,
3464 route: &Route<'_>,
3465 headers: &[(HeaderName, HeaderValue)],
3466 permit: Permit,
3467 max_retries: u32,
3468 ) -> Result<(Fetched, u32)> {
3469 let destination_count = match route {
3470 Route::Mirrors { .. } => self.inner.mirrors.len(),
3471 Route::One(_) => 1,
3472 };
3473 // A destination with a definitive answer gives the same answer in each
3474 // round, so the fetch asks it once. A repeated round asks only the
3475 // destinations with a retryable failure.
3476 let mut settled = vec![false; destination_count];
3477 // The failure that both end paths report. A caller can act on a
3478 // definitive answer, so it has priority over a retryable failure from
3479 // any round. A destination that fails transiently and then answers 404
3480 // reports the 404. Of two failures of one kind, the fetch keeps the
3481 // first.
3482 let mut reported: Option<Error> = None;
3483 let mut definitive = false;
3484 let mut round = 0;
3485 loop {
3486 let mut retryable = false;
3487 for (position, settled) in settled.iter_mut().enumerate() {
3488 if *settled {
3489 continue;
3490 }
3491 // The fetch builds the destination of a mirror for the attempt
3492 // that uses it. So if the first mirror answers, the fetch builds
3493 // one destination, whatever the length of the list.
3494 let destination = match route {
3495 Route::Mirrors { path, query } => {
3496 Cow::Owned(self.inner.mirrors[position].destination(path, *query))
3497 }
3498 Route::One(destination) => Cow::Borrowed(destination),
3499 };
3500 // A fetch reads at most one body of each class, and keeps the
3501 // body of the failure that it reports.
3502 let keep = request.max_error_body.map(|cap| Keep {
3503 cap,
3504 retryable: reported.is_none(),
3505 definitive: !definitive,
3506 });
3507 let failure = match self.attempt(&destination, request, headers, keep).await {
3508 Ok(Attempted::Body(mut body)) => {
3509 body.permit = Some(permit);
3510 return Ok((Fetched::Body(body), round));
3511 }
3512 Ok(Attempted::NotModified) => return Ok((Fetched::NotModified, round)),
3513 Err(failure) => failure,
3514 };
3515 match failure {
3516 Failure::Retry(e) => {
3517 retryable = true;
3518 if reported.is_none() {
3519 reported = Some(e);
3520 }
3521 }
3522 Failure::Fatal(e) => {
3523 *settled = true;
3524 if !definitive {
3525 reported = Some(e);
3526 definitive = true;
3527 }
3528 }
3529 Failure::Final(e) => return Err(e),
3530 }
3531 }
3532 // If `retryable` is `true`, one or more destinations had a
3533 // retryable failure. If not, each destination gave a definitive
3534 // answer.
3535 if !retryable || round >= max_retries {
3536 return Err(reported.expect("a failed round holds a failure"));
3537 }
3538 round += 1;
3539 rt::Timer::after(backoff(round)).await;
3540 }
3541 }
3542
3543 /// Sends one request to one destination, and follows the redirects of the
3544 /// responses.
3545 ///
3546 /// The hop state of an attempt is three locals:
3547 ///
3548 /// - the destination, borrowed from the route until a redirect names
3549 /// another destination
3550 /// - the header list, which is the slice of the caller until a hop goes to
3551 /// another origin and a credential must come out
3552 /// - the count of followed redirects.
3553 ///
3554 /// If the first response answers the request, all three stay as they
3555 /// start. So the attempt builds no URL, copies no header list, and
3556 /// allocates no bookkeeping.
3557 ///
3558 /// `keep` names the unsuccessful responses whose headers and body the
3559 /// attempt keeps in the failure. The attempt discards each other one.
3560 async fn attempt(
3561 &self,
3562 destination: &Destination,
3563 request: &FetchRequest<'_>,
3564 headers: &[(HeaderName, HeaderValue)],
3565 keep: Option<Keep>,
3566 ) -> std::result::Result<Attempted, Failure> {
3567 // The origin that the route names. A credential and the client
3568 // certificate go to this origin alone.
3569 let named = &destination.origin;
3570 let mut hop = Cow::Borrowed(destination);
3571 let mut headers = Cow::Borrowed(headers);
3572 // The signer signs each hop at the named origin. It stays out of the
3573 // attempt after a hop at another origin, as a credential does.
3574 let mut signer = self.inner.signer.as_deref();
3575 let mut followed = 0u32;
3576 let progress_timeout = self.inner.progress_timeout;
3577 // One progress window applies to all drains of this attempt, whatever
3578 // the number of hops. A peer can answer each hop with a short declared
3579 // body and then stop. Such a peer uses the window on the first drain,
3580 // and each later drain drops its connection and does not wait. An
3581 // attempt that follows no redirect drains once, with the whole window.
3582 let drain_until = Instant::now() + progress_timeout;
3583 // The response head must arrive within the time of the rule, in whole
3584 // seconds, from the start of the attempt, whatever the number of hops.
3585 // A head carries no bytes for the rate. So the rate stays under the
3586 // limit from the start until the head arrives.
3587 let head_until = self
3588 .inner
3589 .low_speed
3590 .and_then(|low| Some((Instant::now().checked_add(low.whole_seconds())?, low)));
3591 loop {
3592 // Each hop makes its own proxy decision. The pool keeps a cleartext
3593 // hop behind a proxy under the proxy endpoint. So one such
3594 // connection carries requests for all cleartext origins.
3595 let via = self.inner.proxies.via(&hop.origin);
3596 let key = PoolKey {
3597 origin: match via {
3598 Via::Absolute(proxy) => proxy.endpoint.clone(),
3599 Via::Direct | Via::Tunnel(_) | Via::Socks(..) => hop.origin.clone(),
3600 },
3601 identity: self.presents_identity(&hop.origin, named),
3602 proxied: matches!(via, Via::Absolute(_)),
3603 };
3604 let url = hop.url();
3605 let (response, protocol, reuse) = match head_until {
3606 None => {
3607 self.send(&hop, &key, via, request, &headers, signer)
3608 .await?
3609 }
3610 Some((until, low)) => {
3611 // The send is in a box under the window. So the attempt
3612 // holds one inline copy of its state.
3613 let sent = Box::pin(self.send(&hop, &key, via, request, &headers, signer));
3614 match within(until.saturating_duration_since(Instant::now()), sent).await {
3615 Some(result) => result?,
3616 None => return Err(Failure::Retry(too_slow(url, low))),
3617 }
3618 }
3619 };
3620 let status = response.status();
3621 if status == StatusCode::NOT_MODIFIED {
3622 // A 304 carries no body, so the connection is ready for the
3623 // next request immediately. The validators describe the
3624 // resource. So a 304 from a hop is the answer for the caller,
3625 // as a 304 from the named destination is.
3626 if let Some(sender) = reuse {
3627 self.inner.put_h1(&key, sender);
3628 }
3629 return Ok(Attempted::NotModified);
3630 }
3631 // A limit of zero follows nothing. Each redirect status is then a
3632 // definitive answer.
3633 if is_redirect(status) && self.inner.max_redirects > 0 {
3634 let location = response
3635 .headers()
3636 .get(hyper::header::LOCATION)
3637 .and_then(|value| resolve_location(url, value));
3638 let Some(location) = location else {
3639 // There is no URL to follow. So the attempt reports the
3640 // status of the hop, whatever the hop count is.
3641 let failure = classify(status, url);
3642 return Err(self
3643 .conclude(&key, response, reuse, drain_until, failure, keep)
3644 .await);
3645 };
3646 // The limit stops the attempt at a URL that it can follow. So
3647 // the attempt reads the limit after the `Location` names a URL.
3648 if followed >= self.inner.max_redirects {
3649 self.discard(&key, response, reuse, drain_until).await;
3650 return Err(Failure::Fatal(Error::RedirectLimit {
3651 url: url.to_string(),
3652 hops: followed,
3653 }));
3654 }
3655 let next = redirect_destination(&hop, &location);
3656 // The attempt discards the intermediate body as it discards an
3657 // unsuccessful body. So a short body returns its HTTP/1.1
3658 // connection to the pool, and the next hop at this origin
3659 // uses it.
3660 self.discard(&key, response, reuse, drain_until).await;
3661 let next = next.map_err(Failure::Fatal)?;
3662 // A handshake verifies the server certificate against an
3663 // anchor. So the attempt refuses a hop to a TLS origin if the
3664 // fetcher holds no anchor. Without this check, the handshake
3665 // fails retryably, and uses all rounds and all backoffs on a
3666 // message about the peer.
3667 if next.origin.tls && !self.inner.has_trust_anchors {
3668 return Err(Failure::Fatal(no_trust_anchors(next.origin_url())));
3669 }
3670 // The operator of the origin that a request reaches gets its
3671 // credentials. So the attempt removes them for a hop at an
3672 // origin other than the named origin. They stay removed for the
3673 // rest of the attempt, also on a redirect back to the named
3674 // origin. At that time, the other operator controls the request.
3675 // The same applies to the signer.
3676 if next.origin != *named {
3677 signer = None;
3678 }
3679 if next.origin != *named && headers.iter().any(|(name, _)| is_credential(name)) {
3680 let scoped = headers
3681 .iter()
3682 .filter(|(name, _)| !is_credential(name))
3683 .cloned()
3684 .collect::<Vec<_>>();
3685 headers = Cow::Owned(scoped);
3686 }
3687 hop = Cow::Owned(next);
3688 followed += 1;
3689 continue;
3690 }
3691 // A 206 answers a request that names a range. A 206 to any other
3692 // request holds a part of the object that the caller did not ask
3693 // for, so it is an unsuccessful status.
3694 let ranged = status == StatusCode::PARTIAL_CONTENT
3695 && headers.iter().any(|(name, _)| name == hyper::header::RANGE);
3696 if status != StatusCode::OK && !ranged {
3697 let failure = classify(status, url);
3698 return Err(self
3699 .conclude(&key, response, reuse, drain_until, failure, keep)
3700 .await);
3701 }
3702 // A coded body holds bytes other than the bytes that the remote
3703 // stores. So the declared length tells nothing about the object,
3704 // and the attempt refuses the coding before it compares the cap.
3705 // The refusal names the coding, and a checksum mismatch cannot. The
3706 // refusal is definitive, because another attempt against the same
3707 // destination gets the same answer.
3708 if let Some(encoding) = declared_coding(response.headers()) {
3709 let url = url.to_string();
3710 self.discard(&key, response, reuse, drain_until).await;
3711 return Err(Failure::Fatal(Error::ContentEncoded { url, encoding }));
3712 }
3713 let validators = read_validators(response.headers());
3714 let content_length = content_length(response.headers());
3715 // The cap is the limit of the caller on the object. So the attempt
3716 // compares it with the response that carries the object, and with
3717 // no redirect before it.
3718 if let (Some(limit), Some(length)) = (request.max_size, content_length)
3719 && length > limit
3720 {
3721 self.discard(&key, response, reuse, drain_until).await;
3722 return Err(Failure::Fatal(Error::FetchTooLarge { limit }));
3723 }
3724 let protocol = match response.version() {
3725 Version::HTTP_2 => Protocol::Http2,
3726 _ => protocol,
3727 };
3728 return Ok(Attempted::Body(Body {
3729 incoming: response.into_body(),
3730 chunk: Bytes::new(),
3731 received: 0,
3732 max_size: request.max_size,
3733 status: status.as_u16(),
3734 validators,
3735 content_length,
3736 protocol,
3737 inner: self.inner.clone(),
3738 counters: self.received.clone(),
3739 key,
3740 reuse,
3741 permit: None,
3742 done: false,
3743 failed: None,
3744 deadline: rt::Deadline::new(progress_timeout),
3745 waiting: false,
3746 low_speed: self.inner.low_speed.map(Monitor::new),
3747 interrupted: None,
3748 request_body: None,
3749 }));
3750 }
3751 }
3752
3753 /// Takes or opens a connection for one hop, and sends the request over it.
3754 ///
3755 /// The function returns the response, its protocol, and the HTTP/1.1
3756 /// connection of the response. That connection goes back to the pool after
3757 /// the response is read to its end.
3758 ///
3759 /// A `signer` signs the request after the connection is taken. So the
3760 /// wait for a connect is not part of the age of the signature. If the
3761 /// signer fails, an HTTP/1.1 connection goes back to the pool unused.
3762 async fn send(
3763 &self,
3764 hop: &Destination,
3765 key: &PoolKey,
3766 via: Via<'_>,
3767 request: &FetchRequest<'_>,
3768 headers: &[(HeaderName, HeaderValue)],
3769 signer: Option<&dyn RequestSigner>,
3770 ) -> std::result::Result<(Response<Incoming>, Protocol, Option<H1Sender>), Failure> {
3771 let url = hop.url();
3772 let origin = &key.origin;
3773 let connect_timeout = self.inner.connect_timeout;
3774 let progress_timeout = self.inner.progress_timeout;
3775 let (sender, idle_since) = match self.inner.take_conn(key) {
3776 Some(taken) => taken,
3777 None => {
3778 // The open of a connection is the largest state of a fetch: the
3779 // TLS handshake and the state of hyper. It is also the rarest,
3780 // because it occurs only if the pool has no connection for this
3781 // origin. A box keeps that state out of the fetch future, which
3782 // each caller nests in its own future.
3783 //
3784 // A fetch measures 5064 bytes with the box and 36136 bytes
3785 // without it. A caller that wraps several helpers around one
3786 // fetch multiplies the saving.
3787 let opened = within(connect_timeout, Box::pin(self.connect(key, via))).await;
3788 match opened {
3789 Some(result) => (result?, None),
3790 None => {
3791 return Err(Failure::Retry(connect_timed_out(
3792 origin,
3793 via,
3794 connect_timeout,
3795 )));
3796 }
3797 }
3798 }
3799 };
3800 let headers = match signer {
3801 None => Cow::Borrowed(headers),
3802 Some(signer) => match signed(signer, &Method::GET, hop, SignPayload::Empty, headers) {
3803 Ok(signed) => signed,
3804 Err(failure) => {
3805 // The connection carried no request, so it goes back to
3806 // the pool as it came.
3807 if let Sender::H1(sender) = sender {
3808 let since = idle_since.unwrap_or_else(Instant::now);
3809 self.inner.put_idle_h1(key, sender, since);
3810 }
3811 return Err(failure);
3812 }
3813 },
3814 };
3815 match sender {
3816 Sender::H1(mut sender) => {
3817 let http_request = self
3818 .build_request(hop, request, &headers, Protocol::Http11, via)
3819 .map_err(Failure::Fatal)?;
3820 // The request and the wait for the response head share the
3821 // progress window, because the head is the first bytes of the
3822 // response.
3823 let sent = within(progress_timeout, async {
3824 sender.ready().await?;
3825 sender.send_request(http_request).await
3826 })
3827 .await;
3828 let response = match sent {
3829 Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
3830 None => return Err(Failure::Retry(stalled(url, progress_timeout))),
3831 };
3832 Ok((response, Protocol::Http11, Some(sender)))
3833 }
3834 Sender::H2(mut sender) => {
3835 let http_request = self
3836 .build_request(hop, request, &headers, Protocol::Http2, via)
3837 .map_err(Failure::Fatal)?;
3838 let sent = within(progress_timeout, async {
3839 sender.ready().await?;
3840 sender.send_request(http_request).await
3841 })
3842 .await;
3843 let response = match sent {
3844 Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
3845 None => return Err(Failure::Retry(stalled(url, progress_timeout))),
3846 };
3847 Ok((response, Protocol::Http2, None))
3848 }
3849 }
3850 }
3851
3852 /// Returns `true` if a connection to `hop` presents the configured client
3853 /// certificate.
3854 ///
3855 /// This is the case if a certificate is configured, the hop is the origin
3856 /// that the route names, and that origin is TLS. A cleartext connection
3857 /// presents no certificate. If no certificate is configured, the result is
3858 /// always `false`, so the pool holds one entry for each origin.
3859 fn presents_identity(&self, hop: &Origin, named: &Origin) -> bool {
3860 self.inner.client_identity && hop.tls && hop == named
3861 }
3862
3863 /// Ends an attempt with a response that the caller did not ask for.
3864 ///
3865 /// If the response declares a body of at most [`DRAIN_LIMIT`] bytes, the
3866 /// function reads it to the end. This frees its HTTP/1.1 connection for the
3867 /// next request. The function drops a larger declared body, or a body with
3868 /// no declared length. The connection then closes, because the rest of the
3869 /// response is still in flight.
3870 ///
3871 /// An HTTP/2 stream has no such cost, because its connection stays in the
3872 /// pool, whatever the stream did. So it needs no drain.
3873 ///
3874 /// `drain_until` is the limit for all reads of one attempt here. It is one
3875 /// progress window from the start of the attempt, and the reads share it. A
3876 /// read that reaches the end of the window drops the remaining response. A
3877 /// read that finds no time left drops the connection and reads nothing.
3878 async fn discard(
3879 &self,
3880 key: &PoolKey,
3881 response: Response<Incoming>,
3882 reuse: Option<H1Sender>,
3883 drain_until: Instant,
3884 ) {
3885 let length = content_length(response.headers());
3886 self.drain(key, length, response.into_body(), reuse, drain_until)
3887 .await;
3888 }
3889
3890 /// Ends an attempt with the unsuccessful response that `failure`
3891 /// classifies, and returns the failure.
3892 ///
3893 /// If `keep` asks for a response of the class of the failure, the
3894 /// function reads the response with [`capture`](Fetcher::capture) and
3895 /// puts it into the failure. Else it discards the response.
3896 async fn conclude(
3897 &self,
3898 key: &PoolKey,
3899 response: Response<Incoming>,
3900 reuse: Option<H1Sender>,
3901 drain_until: Instant,
3902 failure: Failure,
3903 keep: Option<Keep>,
3904 ) -> Failure {
3905 match failure.kept_cap(keep) {
3906 None => {
3907 self.discard(key, response, reuse, drain_until).await;
3908 failure
3909 }
3910 Some(cap) => {
3911 let kept = self.capture(key, response, reuse, cap).await;
3912 failure.with_response(kept)
3913 }
3914 }
3915 }
3916
3917 /// Reads the headers and the body of an unsuccessful response, for the
3918 /// error of the fetch.
3919 ///
3920 /// The function keeps the whole body if it is `cap` bytes or less, and
3921 /// keeps no part of a larger body. It reads no body that declares a
3922 /// coding or a length over the cap, and discards it as
3923 /// [`discard`](Fetcher::discard) does. A body that grows past the cap, or
3924 /// fails, closes its connection.
3925 ///
3926 /// Before the first byte, the function reserves at most
3927 /// [`CAPTURE_RESERVE`] bytes, whatever length the response declares. The
3928 /// capacity of the kept body never passes `cap`.
3929 ///
3930 /// All reads take place within one progress window from the call. The
3931 /// read stops at the end of the window, and the body is then absent. The
3932 /// bytes do not count in the received counters, because they are not part
3933 /// of an object. A clean end of the body returns an HTTP/1.1 connection to
3934 /// the pool.
3935 async fn capture(
3936 &self,
3937 key: &PoolKey,
3938 response: Response<Incoming>,
3939 reuse: Option<H1Sender>,
3940 cap: u64,
3941 ) -> ErrorResponse {
3942 let until = Instant::now() + self.inner.progress_timeout;
3943 let (parts, mut body) = response.into_parts();
3944 let headers = parts.headers;
3945 let length = content_length(&headers);
3946 if declared_coding(&headers).is_some() || length.is_some_and(|length| length > cap) {
3947 self.drain(key, length, body, reuse, until).await;
3948 return ErrorResponse::new(headers, None);
3949 }
3950 // The declared length is a claim of the server, so the reserve before
3951 // the first byte stays small. The vector grows as the bytes arrive.
3952 let reserve = length.unwrap_or(0).min(cap).min(CAPTURE_RESERVE);
3953 let mut bytes = Vec::with_capacity(usize::try_from(reserve).unwrap_or(0));
3954 let budget = until.saturating_duration_since(Instant::now());
3955 let read = within(budget, async {
3956 loop {
3957 let frame = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
3958 match frame {
3959 Some(Ok(frame)) => {
3960 // A trailer carries no bytes of the body.
3961 let Ok(data) = frame.into_data() else {
3962 continue;
3963 };
3964 if !extend_capped(&mut bytes, &data, cap) {
3965 return false;
3966 }
3967 }
3968 Some(Err(_)) => return false,
3969 None => return true,
3970 }
3971 }
3972 })
3973 .await;
3974 if read != Some(true) {
3975 // The rest of the response is still in flight, so the connection
3976 // closes when `reuse` drops.
3977 return ErrorResponse::new(headers, None);
3978 }
3979 if let Some(sender) = reuse {
3980 self.inner.put_h1(key, sender);
3981 }
3982 ErrorResponse::new(headers, Some(bytes))
3983 }
3984
3985 /// Reads a response body of the declared `length` to its end within
3986 /// `drain_until`, and returns its HTTP/1.1 connection to the pool.
3987 ///
3988 /// [`discard`](Fetcher::discard) states the rule.
3989 async fn drain(
3990 &self,
3991 key: &PoolKey,
3992 length: Option<u64>,
3993 mut body: Incoming,
3994 reuse: Option<H1Sender>,
3995 drain_until: Instant,
3996 ) {
3997 let Some(sender) = reuse else { return };
3998 if length.is_none_or(|length| length > DRAIN_LIMIT) {
3999 return;
4000 }
4001 let budget = drain_until.saturating_duration_since(Instant::now());
4002 if budget.is_zero() {
4003 return;
4004 }
4005 // The drain runs in the remaining window of the attempt. So a peer that
4006 // declares a short body and then stops costs the attempt no more than a
4007 // stalled body, whatever the hop count.
4008 let drained = within(budget, async {
4009 loop {
4010 let frame = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
4011 match frame {
4012 Some(Ok(_)) => continue,
4013 Some(Err(_)) => return false,
4014 None => return true,
4015 }
4016 }
4017 })
4018 .await;
4019 if drained == Some(true) {
4020 self.inner.put_h1(key, sender);
4021 }
4022 }
4023
4024 /// Sends `request` and tries each destination until one takes it.
4025 ///
4026 /// Each final status returns an [`Uploaded`], also 408, 429, and 5xx. The
4027 /// mirrors, the proxy, TLS, the client certificate, the headers, the
4028 /// credentials, the signer, and the cleartext rule apply to an upload as
4029 /// they apply to [`fetch`](Fetcher::fetch). An upload can also carry a
4030 /// [`BearerToken`] of its own as its credential. The fetcher sets no
4031 /// `Content-Type` header and no `Expect` header.
4032 ///
4033 /// The hand-over gives the request to hyper. A failure before the
4034 /// hand-over returns the error that a fetch returns. A failure after the
4035 /// hand-over returns [`Error::UploadInterrupted`].
4036 ///
4037 /// # Retries
4038 ///
4039 /// The fetcher tries an upload again only while no part of the request is
4040 /// sent. The request is unsent if the attempt fails before hyper accepts
4041 /// it, in one of these steps:
4042 ///
4043 /// - the connect
4044 /// - the `CONNECT` tunnel
4045 /// - the TLS handshake
4046 /// - the HTTP handshake
4047 /// - the wait for a ready connection.
4048 ///
4049 /// The request is also unsent if hyper gives it back unwritten. The bytes
4050 /// of a `CONNECT` go to the proxy alone and are no part of the request.
4051 ///
4052 /// An unsent attempt spends a round as a retryable failure of a fetch
4053 /// does. The upload asks the next mirror, then repeats the round after the
4054 /// backoff, up to [`max_retries`](FetcherOptions::max_retries) times. A 407
4055 /// to the `CONNECT` is definitive. If the rounds run out before the request
4056 /// is sent, the upload returns the [`Error::Fetch`] that a fetch returns.
4057 ///
4058 /// If the writer of a streamed body is dropped before it closes the body,
4059 /// the upload fails before the hand-over. It fails with [`Error::Fetch`]
4060 /// and sends nothing.
4061 ///
4062 /// All other outcomes count as sent. The upload then ends on the
4063 /// destination that took it, and asks no other mirror and no other round.
4064 /// A failure after the hand-over fails the upload with
4065 /// [`Error::UploadInterrupted`], because the server can have received the
4066 /// whole request and acted on it. An HTTP/2 stream that the server refuses
4067 /// or resets after the hand-over is such a failure.
4068 ///
4069 /// # Redirects
4070 ///
4071 /// For a body given whole, the upload follows a 307 or a 308. It keeps the
4072 /// method and sends the bytes again. The redirect rules of
4073 /// [`fetch`](Fetcher::fetch) apply: the redirect limit, the refusal of a
4074 /// hop from `https` to `http`, and the scope of the credentials and of the
4075 /// signer.
4076 ///
4077 /// The first hop sends the request. So a failure on a later hop, a refused
4078 /// hop, and a redirect past the limit each fail the upload with
4079 /// [`Error::UploadInterrupted`].
4080 ///
4081 /// The upload returns these redirects as their status in an [`Uploaded`]:
4082 ///
4083 /// - a redirect status other than 307 and 308
4084 /// - each redirect of a streamed body
4085 /// - a 307 or a 308 with no `Location` that the upload can read
4086 /// - each redirect if [`max_redirects`](FetcherOptions::max_redirects) is
4087 /// 0.
4088 ///
4089 /// # Unsuccessful answers
4090 ///
4091 /// An answer other than 2xx returns an [`Uploaded`] with its status and
4092 /// its headers, also when the upload cannot deliver its body. The upload
4093 /// does not deliver a body that declares a coding in `Content-Encoding` or
4094 /// `Transfer-Encoding`, or a `Content-Length` over
4095 /// [`max_response`](UploadRequest::max_response). It withholds such a
4096 /// body: [`Uploaded::body_withheld`] returns `true`, the body reads as
4097 /// empty, and the connection closes. So a definitive refusal, for example
4098 /// a 403 behind a proxy that compresses it, keeps its status, and the
4099 /// caller does not take it for an interrupted upload.
4100 ///
4101 /// A 2xx answer with such a body fails the upload with
4102 /// [`Error::UploadInterrupted`].
4103 ///
4104 /// # Connections
4105 ///
4106 /// An upload uses the pooled HTTP/2 connection of its origin. It takes an
4107 /// idle HTTP/1.1 connection from the pool only if the connection became
4108 /// idle less than 2 seconds ago. Otherwise, it opens a connection of its
4109 /// own.
4110 ///
4111 /// A server can close an idle connection at any time. If hyper began to
4112 /// write an upload over a connection that the server closed, the upload
4113 /// counts as sent. A server closes an idle connection at the end of its
4114 /// idle timeout, so it keeps a connection that became idle a short time
4115 /// ago.
4116 ///
4117 /// If a pooled HTTP/1.1 connection fails before hyper writes the request,
4118 /// the fetcher drops the connection. The upload then continues over a new
4119 /// connection and spends no round.
4120 ///
4121 /// The HTTP/1.1 connection of an upload goes back to the pool if both
4122 /// bodies end cleanly. That is, hyper takes the end of the request body
4123 /// before the response head arrives. Then the caller reads the response
4124 /// body to its end with no failure. Each of these closes the connection:
4125 ///
4126 /// - a response that closes the connection
4127 /// - an HTTP/1.0 response
4128 /// - an answer that arrives before the end of the request body
4129 /// - a response body that fails
4130 /// - a response that is dropped before its end.
4131 ///
4132 /// # The response ends the request body
4133 ///
4134 /// A server can answer before it reads the whole request body. If the
4135 /// response body ends or is dropped before the request body ends, the
4136 /// fetcher fails the request body. The writer then gets
4137 /// [`io::ErrorKind::BrokenPipe`](std::io::ErrorKind::BrokenPipe), and hyper
4138 /// stops the body.
4139 ///
4140 /// The stop of the body closes an HTTP/1.1 connection and resets an HTTP/2
4141 /// stream. The same applies to a response that the upload does not
4142 /// deliver: a followed redirect, a refused coding, a declared length over
4143 /// the cap, and a withheld body.
4144 ///
4145 /// # Deadlines
4146 ///
4147 /// - [`connect_timeout`](FetcherOptions::connect_timeout) bounds the open
4148 /// of a connection.
4149 /// - [`fetch_timeout`](FetcherOptions::fetch_timeout) bounds the upload
4150 /// from admission to the hand-over alone.
4151 /// - While a streamed body streams, the one bound is the stall window of
4152 /// [`UploadWriter`], which starts at the hand-over.
4153 /// - For a body given whole, a frame that the connection does not take for
4154 /// [`progress_timeout`](FetcherOptions::progress_timeout) ends the upload
4155 /// with [`Error::UploadInterrupted`].
4156 /// - The wait for the response head lasts
4157 /// [`response_timeout`](UploadRequest::response_timeout).
4158 /// - The response body has the progress window of a fetch.
4159 ///
4160 /// Before the hand-over, a wait of the writer has no bound of its own. This
4161 /// applies at the gate, during the connect, and during the backoff between
4162 /// rounds.
4163 /// The low-speed rule does not apply to an upload.
4164 ///
4165 /// # Errors
4166 ///
4167 /// If more than one destination fails before the hand-over, the failure
4168 /// order of [`fetch`](Fetcher::fetch) states which error the upload
4169 /// returns.
4170 ///
4171 /// - [`Error::Fetch`] before admission, if a path holds a `?` or a `#`, if
4172 /// the query of a [`Target::PathQuery`] holds a `#`, or if the fetcher
4173 /// has no mirror for a path target.
4174 /// - [`Error::Fetch`] before admission, if a URL target is not a valid
4175 /// absolute URL, or holds a fragment or userinfo.
4176 /// - [`Error::Unsupported`] if the scheme of a URL target is neither `http`
4177 /// nor `https`.
4178 /// - [`Error::Fetch`] before admission, if a request header is invalid, is
4179 /// `Host`, or is a header that the connection layer sets.
4180 /// - [`Error::Fetch`] before admission, if two credentials of the request
4181 /// meet: [`basic_auth`](UploadRequest::basic_auth),
4182 /// [`bearer_token`](UploadRequest::bearer_token), and an `Authorization`
4183 /// header. A bearer token that is not token68 also fails.
4184 /// - [`Error::Fetch`] before admission, if the fetcher has a
4185 /// [`signer`](FetcherOptions::signer) and the request carries one of
4186 /// these credentials: [`basic_auth`](UploadRequest::basic_auth),
4187 /// [`bearer_token`](UploadRequest::bearer_token), or an `Authorization`
4188 /// header.
4189 /// - [`Error::Fetch`] before admission, if a credential can reach a
4190 /// cleartext destination, and neither
4191 /// [`allow_cleartext_credentials`](UploadRequest::allow_cleartext_credentials)
4192 /// nor [`FetcherOptions::allow_cleartext_credentials`] is `true`.
4193 /// - [`Error::Fetch`] before admission, if the route names a TLS
4194 /// destination and the fetcher holds no trust anchors.
4195 /// - [`Error::Fetch`] before admission, if the method is `DELETE` and the
4196 /// body is not an empty [`UploadBody::bytes`].
4197 /// - [`Error::Fetch`] if a transport failure ends the rounds before the
4198 /// hand-over: a failed connect, handshake, or proxy `CONNECT`, or an
4199 /// expired deadline.
4200 /// - [`Error::Fetch`] if hyper cannot build the request.
4201 /// - The error of the [`signer`](FetcherOptions::signer), unchanged, if it
4202 /// fails before the hand-over. An [`Error::Fetch`] if it returns a
4203 /// header that a request cannot carry. The upload asks no other
4204 /// destination and repeats no round. A failure of the signer on a
4205 /// redirect hop is a failure after the hand-over.
4206 /// - [`Error::Fetch`] if the writer of a streamed body is dropped before
4207 /// the hand-over.
4208 /// - [`Error::Fetch`] if [`fetch_timeout`](FetcherOptions::fetch_timeout)
4209 /// expires before the hand-over.
4210 /// - [`Error::UploadInterrupted`] if a failure occurs after the hand-over.
4211 /// This includes a refused redirect hop, a redirect past the limit, and
4212 /// a 2xx response that declares a coding or a `Content-Length` over
4213 /// [`max_response`](UploadRequest::max_response). The message names the
4214 /// cause.
4215 ///
4216 /// # Examples
4217 ///
4218 /// ```no_run
4219 /// use ostrya_fetch::{Fetcher, FetcherOptions, UploadBody, UploadRequest};
4220 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
4221 /// let fetcher = Fetcher::new(FetcherOptions::new("https://example.com/repo")).await?;
4222 /// let body = UploadBody::bytes(b"report".to_vec());
4223 /// let uploaded = fetcher.upload(UploadRequest::path("inbox/report", body)).await?;
4224 /// println!("the server answered {}", uploaded.status());
4225 /// # Ok(())
4226 /// # }
4227 /// ```
4228 pub async fn upload(&self, request: UploadRequest<'_>) -> Result<Uploaded> {
4229 let UploadRequest {
4230 target,
4231 method,
4232 body,
4233 priority,
4234 max_response,
4235 headers,
4236 basic_auth,
4237 bearer_token,
4238 allow_cleartext_credentials,
4239 response_timeout,
4240 } = request;
4241 // As for a fetch, the checks of the request run before admission.
4242 // The check of the body that a DELETE does not send runs there too.
4243 let route = self.route(target)?;
4244 if self.inner.signer.is_some() {
4245 refuse_beside_signer(headers, basic_auth.is_some(), bearer_token.is_some())?;
4246 }
4247 let headers = merge_headers(&self.inner.headers, headers, basic_auth, bearer_token)?;
4248 if !allow_cleartext_credentials && !self.inner.allow_cleartext_credentials {
4249 self.check_cleartext(&route, &headers)?;
4250 }
4251 self.check_trust_anchors(&route)?;
4252 let method = match method {
4253 UploadMethod::Post => Method::POST,
4254 UploadMethod::Put => Method::PUT,
4255 UploadMethod::Delete => Method::DELETE,
4256 };
4257 let (end, bytes, sha256) = match body.form {
4258 UploadForm::Bytes { bytes, sha256 } => (BodyEnd::whole(&bytes), Some(bytes), sha256),
4259 UploadForm::Channel(end) => (end, None, None),
4260 };
4261 if method == Method::DELETE && !bytes.as_ref().is_some_and(Bytes::is_empty) {
4262 return Err(Error::Fetch(format!(
4263 "the delete of {} carries a body, which a delete does not send: pass an empty \
4264 UploadBody::bytes",
4265 target.describe()
4266 )));
4267 }
4268 let plan = UploadPlan {
4269 method,
4270 headers: &headers,
4271 bytes,
4272 sha256,
4273 max_response,
4274 response_timeout: response_timeout.unwrap_or(self.inner.progress_timeout),
4275 };
4276 let permit = self.inner.gate.acquire(priority).await;
4277 // This flag is set while hyper holds the request. The admission
4278 // deadline stops then, because the steps after the hand-over have
4279 // deadlines of their own.
4280 let handed = AtomicBool::new(false);
4281 let rounds = self.upload_rounds(&plan, &route, end, &handed);
4282 let mut uploaded = match self.inner.fetch_timeout {
4283 None => rounds.await?,
4284 Some(limit) => match before_hand_over(limit, &handed, rounds).await {
4285 Some(result) => result?,
4286 None => {
4287 return Err(Error::Fetch(format!(
4288 "upload of {} was not sent within {limit:?}",
4289 target.describe()
4290 )));
4291 }
4292 },
4293 };
4294 if !uploaded.withheld {
4295 uploaded.body.permit = Some(permit);
4296 }
4297 Ok(uploaded)
4298 }
4299
4300 /// Tries each destination in turn, as [`rounds`](Fetcher::rounds) does for
4301 /// a fetch.
4302 ///
4303 /// The function repeats the round while the request is unsent and a
4304 /// destination failed retryably. A request that is sent ends the rounds,
4305 /// whatever its outcome.
4306 async fn upload_rounds(
4307 &self,
4308 plan: &UploadPlan<'_>,
4309 route: &Route<'_>,
4310 end: BodyEnd,
4311 handed: &AtomicBool,
4312 ) -> Result<Uploaded> {
4313 let destination_count = match route {
4314 Route::Mirrors { .. } => self.inner.mirrors.len(),
4315 Route::One(_) => 1,
4316 };
4317 let mut settled = vec![false; destination_count];
4318 let mut reported: Option<Error> = None;
4319 let mut definitive = false;
4320 let mut round = 0;
4321 // An attempt takes the body when it hands the request over. If the
4322 // request comes back unsent, the attempt puts the body back here.
4323 let mut body = Some(end);
4324 loop {
4325 let mut retryable = false;
4326 for (position, settled) in settled.iter_mut().enumerate() {
4327 if *settled {
4328 continue;
4329 }
4330 let destination = match route {
4331 Route::Mirrors { path, query } => {
4332 Cow::Owned(self.inner.mirrors[position].destination(path, *query))
4333 }
4334 Route::One(destination) => Cow::Borrowed(destination),
4335 };
4336 match self
4337 .upload_attempt(&destination, plan, &mut body, handed)
4338 .await
4339 {
4340 Ok(uploaded) => return Ok(uploaded),
4341 Err(UploadFailure::Sent { url, message }) => {
4342 return Err(Error::UploadInterrupted { url, message });
4343 }
4344 Err(UploadFailure::Unsent(Failure::Retry(e))) => {
4345 retryable = true;
4346 if reported.is_none() {
4347 reported = Some(e);
4348 }
4349 }
4350 Err(UploadFailure::Unsent(Failure::Fatal(e))) => {
4351 *settled = true;
4352 if !definitive {
4353 reported = Some(e);
4354 definitive = true;
4355 }
4356 }
4357 Err(UploadFailure::Unsent(Failure::Final(e))) => return Err(e),
4358 }
4359 }
4360 if !retryable || round >= self.inner.max_retries {
4361 return Err(reported.expect("a failed round holds a failure"));
4362 }
4363 round += 1;
4364 rt::Timer::after(backoff(round)).await;
4365 }
4366 }
4367
4368 /// Runs one upload against one destination, and follows the redirects of a
4369 /// body given whole.
4370 ///
4371 /// The first hop that hyper takes sends the request. So a failure on a
4372 /// later hop is final: the function reports an interrupted upload, and the
4373 /// rounds stop. The function drops a response that the upload does not
4374 /// deliver. This also drops a request body that did not end, and closes
4375 /// the connection of an HTTP/1.1 hop.
4376 async fn upload_attempt(
4377 &self,
4378 destination: &Destination,
4379 plan: &UploadPlan<'_>,
4380 body: &mut Option<BodyEnd>,
4381 handed: &AtomicBool,
4382 ) -> std::result::Result<Uploaded, UploadFailure> {
4383 let named = &destination.origin;
4384 let mut hop = Cow::Borrowed(destination);
4385 let mut headers = Cow::Borrowed(plan.headers);
4386 let mut signer = self.inner.signer.as_deref();
4387 let mut followed = 0u32;
4388 loop {
4389 let via = self.inner.proxies.via(&hop.origin);
4390 let key = PoolKey {
4391 origin: match via {
4392 Via::Absolute(proxy) => proxy.endpoint.clone(),
4393 Via::Direct | Via::Tunnel(_) | Via::Socks(..) => hop.origin.clone(),
4394 },
4395 identity: self.presents_identity(&hop.origin, named),
4396 proxied: matches!(via, Via::Absolute(_)),
4397 };
4398 let url = hop.url();
4399 let sent = self
4400 .upload_send(&hop, &key, via, plan, &headers, signer, body, handed)
4401 .await;
4402 let (response, protocol, request_end, reuse) = match sent {
4403 Ok(sent) => sent,
4404 Err(UploadFailure::Unsent(failure)) if followed > 0 => {
4405 return Err(interrupted(url, failure.into_error().to_string()));
4406 }
4407 Err(failure) => return Err(failure),
4408 };
4409 let status = response.status();
4410 if let Some(bytes) = &plan.bytes
4411 && UPLOAD_REDIRECTS.contains(&status)
4412 && self.inner.max_redirects > 0
4413 && let Some(location) = response
4414 .headers()
4415 .get(hyper::header::LOCATION)
4416 .and_then(|value| resolve_location(url, value))
4417 {
4418 if followed >= self.inner.max_redirects {
4419 return Err(undelivered(
4420 url,
4421 Error::RedirectLimit {
4422 url: url.to_string(),
4423 hops: followed,
4424 },
4425 ));
4426 }
4427 let next =
4428 redirect_destination(&hop, &location).map_err(|e| undelivered(url, e))?;
4429 if next.origin.tls && !self.inner.has_trust_anchors {
4430 return Err(undelivered(url, no_trust_anchors(next.origin_url())));
4431 }
4432 // As for a fetch, a credential and the signer stay with the
4433 // origin that the route names.
4434 if next.origin != *named {
4435 signer = None;
4436 }
4437 if next.origin != *named && headers.iter().any(|(name, _)| is_credential(name)) {
4438 let scoped = headers
4439 .iter()
4440 .filter(|(name, _)| !is_credential(name))
4441 .cloned()
4442 .collect::<Vec<_>>();
4443 headers = Cow::Owned(scoped);
4444 }
4445 hop = Cow::Owned(next);
4446 followed += 1;
4447 *body = Some(BodyEnd::whole(bytes));
4448 continue;
4449 }
4450 let coding = declared_coding(response.headers());
4451 let content_length = content_length(response.headers());
4452 let over = content_length.is_some_and(|length| length > plan.max_response);
4453 // An answer other than 2xx keeps its status and its headers, so a
4454 // refusal of the server reaches the caller as a refusal. Its body
4455 // is withheld, and the connection closes.
4456 let withheld = !status.is_success() && (coding.is_some() || over);
4457 if !withheld {
4458 if let Some(encoding) = coding {
4459 return Err(undelivered(
4460 url,
4461 Error::ContentEncoded {
4462 url: url.to_string(),
4463 encoding,
4464 },
4465 ));
4466 }
4467 if over {
4468 return Err(undelivered(
4469 url,
4470 Error::FetchTooLarge {
4471 limit: plan.max_response,
4472 },
4473 ));
4474 }
4475 }
4476 let protocol = match response.version() {
4477 Version::HTTP_2 => Protocol::Http2,
4478 _ => protocol,
4479 };
4480 let (parts, incoming) = response.into_parts();
4481 // A withheld body ends at once. Its request body stops, and its
4482 // HTTP/1.1 connection does not go back to the pool, because the
4483 // rest of the response is still in flight.
4484 let (reuse, request_body) = if withheld {
4485 (None, None)
4486 } else {
4487 (reuse, Some(request_end))
4488 };
4489 return Ok(Uploaded {
4490 status: parts.status,
4491 headers: parts.headers,
4492 url: url.to_string(),
4493 withheld,
4494 body: Body {
4495 incoming,
4496 chunk: Bytes::new(),
4497 received: 0,
4498 max_size: Some(plan.max_response),
4499 status: parts.status.as_u16(),
4500 validators: Validators::default(),
4501 content_length: if withheld { None } else { content_length },
4502 protocol,
4503 inner: self.inner.clone(),
4504 counters: self.received.clone(),
4505 key,
4506 reuse,
4507 permit: None,
4508 done: withheld,
4509 failed: None,
4510 deadline: rt::Deadline::new(self.inner.progress_timeout),
4511 waiting: false,
4512 low_speed: None,
4513 interrupted: None,
4514 request_body,
4515 },
4516 });
4517 }
4518 }
4519
4520 /// Takes or opens a connection for one upload hop, and hands the request
4521 /// to hyper.
4522 ///
4523 /// An upload takes the pooled HTTP/2 connection, or an idle HTTP/1.1
4524 /// connection from [`Inner::take_upload`]. If a pooled HTTP/1.1 connection
4525 /// fails before hyper writes the request, the function drops it. The hop
4526 /// then continues over a new connection and spends no round.
4527 ///
4528 /// A failure before the hand-over leaves the body in `body`. A request
4529 /// that hyper gives back unwritten also leaves it there. A body that failed
4530 /// before the hand-over is never sent. The stall window of the body starts
4531 /// at the hand-over, and [`answer`] then bounds the wait for the response
4532 /// head.
4533 ///
4534 /// The HTTP/1.1 connection comes back with the response if it can carry
4535 /// the next request after the response body ends. That is, hyper took the
4536 /// end of the request body before the response head arrived, and the
4537 /// response does not close the connection. In each other case, the
4538 /// connection closes at the end of the exchange.
4539 ///
4540 /// A `signer` signs the request over each connection that the function
4541 /// takes or opens, when the connection is ready and before the function
4542 /// starts the request. So a request that goes again over a new connection
4543 /// carries a new signature. If the signer fails, an HTTP/1.1 connection
4544 /// goes back to the pool unused.
4545 #[allow(clippy::too_many_arguments)]
4546 async fn upload_send(
4547 &self,
4548 hop: &Destination,
4549 key: &PoolKey,
4550 via: Via<'_>,
4551 plan: &UploadPlan<'_>,
4552 headers: &[(HeaderName, HeaderValue)],
4553 signer: Option<&dyn RequestSigner>,
4554 body: &mut Option<BodyEnd>,
4555 handed: &AtomicBool,
4556 ) -> std::result::Result<UploadResponse, UploadFailure> {
4557 let url = hop.url();
4558 let unsent = |failure: Failure| -> std::result::Result<UploadResponse, UploadFailure> {
4559 Err(UploadFailure::Unsent(failure))
4560 };
4561 let exchange = body
4562 .as_ref()
4563 .expect("an upload attempt holds its body until it sends it")
4564 .exchange
4565 .clone();
4566 if let Some(reason) = exchange.aborted() {
4567 return unsent(Failure::Fatal(not_sent(url, reason)));
4568 }
4569 let progress_timeout = self.inner.progress_timeout;
4570 let mut pooled = self.inner.take_upload(key);
4571 loop {
4572 // If a pooled HTTP/1.1 connection fails before hyper writes the
4573 // request, the server closed it while it was idle.
4574 let stale_h1 = matches!(pooled, Some((Sender::H1(_), _)));
4575 let (mut sender, idle_since) = match pooled.take() {
4576 Some(taken) => taken,
4577 None => {
4578 let connect_timeout = self.inner.connect_timeout;
4579 match within(connect_timeout, Box::pin(self.connect(key, via))).await {
4580 Some(Ok(sender)) => (sender, None),
4581 Some(Err(failure)) => return unsent(failure),
4582 None => {
4583 return unsent(Failure::Retry(connect_timed_out(
4584 &key.origin,
4585 via,
4586 connect_timeout,
4587 )));
4588 }
4589 }
4590 }
4591 };
4592 let protocol = match sender {
4593 Sender::H1(_) => Protocol::Http11,
4594 Sender::H2(_) => Protocol::Http2,
4595 };
4596 let ready = match &mut sender {
4597 Sender::H1(sender) => within(progress_timeout, sender.ready()).await,
4598 Sender::H2(sender) => within(progress_timeout, sender.ready()).await,
4599 };
4600 match ready {
4601 Some(Ok(())) => {}
4602 Some(Err(_)) if stale_h1 => continue,
4603 Some(Err(e)) => return unsent(Failure::Retry(transport(url, e))),
4604 None => return unsent(Failure::Retry(stalled(url, progress_timeout))),
4605 }
4606 // The signature is made when the connection is ready to carry the
4607 // request. So a connection that fails here costs no signature, and
4608 // the wait for a stream slot is not part of the age of the
4609 // signature.
4610 let signed_headers = match signer {
4611 None => Cow::Borrowed(headers),
4612 Some(signer) => {
4613 // The signer reads a body given whole as the slice that
4614 // the request sends, with no copy, and with the digest
4615 // of the caller if it gave one. A streamed body is not
4616 // known yet.
4617 let payload = match (&plan.bytes, plan.sha256) {
4618 _ if plan.method == Method::DELETE => SignPayload::Empty,
4619 (Some(bytes), Some(sha256)) => SignPayload::Sha256 { bytes, sha256 },
4620 (Some(bytes), None) => SignPayload::Bytes(bytes),
4621 (None, _) => SignPayload::Streamed,
4622 };
4623 match signed(signer, &plan.method, hop, payload, headers) {
4624 Ok(signed) => signed,
4625 Err(failure) => {
4626 // The connection carried no request, so it goes
4627 // back to the pool as it came.
4628 if let Sender::H1(sender) = sender {
4629 let since = idle_since.unwrap_or_else(Instant::now);
4630 self.inner.put_idle_h1(key, sender, since);
4631 }
4632 return unsent(failure);
4633 }
4634 }
4635 }
4636 };
4637 let mut head = match self.upload_head(hop, plan, &signed_headers, protocol, via) {
4638 Ok(head) => head,
4639 Err(e) => return unsent(Failure::Fatal(e)),
4640 };
4641 let empty = match exchange.hand_over(progress_timeout) {
4642 Ok(empty) => empty,
4643 Err(reason) => return unsent(Failure::Fatal(not_sent(url, reason))),
4644 };
4645 // A `POST` or a `PUT` whose body is at its end states its length.
4646 // hyper writes no length for an HTTP/1.1 request at the end of its
4647 // body. Each of the two methods defines content, so a server that
4648 // waits for the framing reads `0`. A `DELETE` sends no body.
4649 if empty && plan.method != Method::DELETE {
4650 head.headers_mut()
4651 .insert(hyper::header::CONTENT_LENGTH, HeaderValue::from_static("0"));
4652 }
4653 let end = body
4654 .take()
4655 .expect("an upload attempt holds its body until it sends it");
4656 let request = head.map(|()| RequestBody::Upload(end));
4657 handed.store(true, Ordering::Relaxed);
4658 let window = plan.response_timeout;
4659 let (answered, h1) = match sender {
4660 Sender::H1(mut sender) => {
4661 let answered =
4662 answer(sender.try_send_request(request), &exchange, window).await;
4663 (answered, Some(sender))
4664 }
4665 Sender::H2(mut sender) => {
4666 let answered =
4667 answer(sender.try_send_request(request), &exchange, window).await;
4668 (answered, None)
4669 }
4670 };
4671 let response = match answered {
4672 Answer::Sent(Ok(response)) => response,
4673 Answer::Sent(Err(mut e)) => {
4674 let Some(request) = e.take_message() else {
4675 exchange.cut();
4676 return Err(interrupted(url, with_cause(&e.into_error())));
4677 };
4678 // hyper gives the request back if the connection failed
4679 // before hyper wrote a part of it. So the body is whole,
4680 // and the request is unsent.
4681 exchange.withdraw();
4682 if let RequestBody::Upload(end) = request.into_body() {
4683 *body = Some(end);
4684 }
4685 handed.store(false, Ordering::Relaxed);
4686 if stale_h1 {
4687 continue;
4688 }
4689 return unsent(Failure::Retry(transport(url, e.into_error())));
4690 }
4691 Answer::Aborted(reason) => return Err(interrupted(url, reason)),
4692 Answer::Silent(window) => {
4693 return Err(interrupted(
4694 url,
4695 format!("no response within {window:?} of the end of the request body"),
4696 ));
4697 }
4698 };
4699 // A head that arrived before hyper took the end of the body is an
4700 // early answer. The body is cut when the response ends, and the
4701 // cut closes the connection.
4702 let reuse = h1.filter(|_| exchange.has_ended() && !closes(&response));
4703 return Ok((response, protocol, RequestEnd { exchange }, reuse));
4704 }
4705 }
4706
4707 /// Starts the upload request against `destination`, in the form that
4708 /// `protocol` and `via` give it.
4709 ///
4710 /// [`request_head`](Fetcher::request_head) does the same for a fetch.
4711 fn upload_head(
4712 &self,
4713 destination: &Destination,
4714 plan: &UploadPlan<'_>,
4715 headers: &[(HeaderName, HeaderValue)],
4716 protocol: Protocol,
4717 via: Via<'_>,
4718 ) -> Result<Request<()>> {
4719 self.request_head(plan.method.clone(), destination, headers, protocol, via)?
4720 .body(())
4721 .map_err(|e| Error::Fetch(format!("invalid request for {}: {e}", destination.url())))
4722 }
4723
4724 /// Builds the GET for `request` against `destination`, with `headers` and
4725 /// the validators of the request.
4726 fn build_request(
4727 &self,
4728 destination: &Destination,
4729 request: &FetchRequest<'_>,
4730 headers: &[(HeaderName, HeaderValue)],
4731 protocol: Protocol,
4732 via: Via<'_>,
4733 ) -> Result<Request<RequestBody>> {
4734 let mut builder = self.request_head(Method::GET, destination, headers, protocol, via)?;
4735 if let Some(validators) = request.validators {
4736 if let Some(etag) = &validators.etag {
4737 builder = builder.header(hyper::header::IF_NONE_MATCH, etag);
4738 }
4739 if let Some(last_modified) = &validators.last_modified {
4740 builder = builder.header(hyper::header::IF_MODIFIED_SINCE, last_modified);
4741 }
4742 }
4743 builder
4744 .body(RequestBody::Empty)
4745 .map_err(|e| Error::Fetch(format!("invalid request for {}: {e}", destination.url())))
4746 }
4747
4748 /// Starts the request of `method` against `destination`, with `headers`.
4749 ///
4750 /// An HTTP/1.1 request carries the origin-form target and a `Host` header,
4751 /// as an origin server expects. The absolute form is for proxy requests,
4752 /// and a plain static-file server answers 404 to it. An HTTP/2 request
4753 /// carries the absolute URL, and hyper fills the `:scheme` and
4754 /// `:authority` pseudo-headers from it.
4755 ///
4756 /// A request to a cleartext origin over a proxy connection carries the
4757 /// absolute form, which tells the proxy where to send it. Its `Host`
4758 /// header names the origin.
4759 ///
4760 /// The request also carries the credential of the proxy, if the merged
4761 /// headers hold no `Proxy-Authorization`. A `Proxy-Authorization` header
4762 /// that the caller set states the value for the proxy. Two values of one
4763 /// name give the proxy two answers to one question.
4764 ///
4765 /// A `CONNECT` tunnel carries the proxy credential of the fetcher on the
4766 /// `CONNECT` alone. So the request over the tunnel is the request that a
4767 /// direct connection sends.
4768 fn request_head(
4769 &self,
4770 method: Method,
4771 destination: &Destination,
4772 headers: &[(HeaderName, HeaderValue)],
4773 protocol: Protocol,
4774 via: Via<'_>,
4775 ) -> Result<hyper::http::request::Builder> {
4776 let absolute = protocol == Protocol::Http2 || matches!(via, Via::Absolute(_));
4777 let url = if absolute {
4778 destination.url()
4779 } else {
4780 destination.target()
4781 };
4782 let uri =
4783 Uri::try_from(url).map_err(|e| Error::Fetch(format!("invalid url {url}: {e}")))?;
4784 let mut builder = Request::builder().method(method).uri(uri);
4785 if protocol == Protocol::Http11 {
4786 builder = builder.header(hyper::header::HOST, &destination.authority);
4787 }
4788 for (name, value) in headers {
4789 builder = builder.header(name, value);
4790 }
4791 if let Via::Absolute(proxy) = via
4792 && let ProxyKind::Http {
4793 credential: Some(credential),
4794 } = &proxy.kind
4795 && !headers
4796 .iter()
4797 .any(|(name, _)| *name == hyper::header::PROXY_AUTHORIZATION)
4798 {
4799 builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
4800 }
4801 Ok(builder)
4802 }
4803
4804 /// Opens a connection for `key`, and selects the protocol over ALPN if the
4805 /// origin is TLS.
4806 ///
4807 /// The key states the client configuration of the handshake. So a
4808 /// connection that presents the client certificate and a connection that
4809 /// presents none are two pool entries. The pool gives neither to the hop
4810 /// of the other.
4811 ///
4812 /// `via` states what the connection reaches. The key of a proxied
4813 /// cleartext origin is the proxy endpoint. So the socket goes where the key
4814 /// names, and the requests over it carry the absolute form.
4815 ///
4816 /// The key of a tunneled TLS origin is the origin. So the socket goes to
4817 /// the proxy, and the handshake runs over the `CONNECT` exchange.
4818 ///
4819 /// The key of an origin behind a SOCKS5 proxy is the origin. The socket
4820 /// goes to the proxy, and the SOCKS5 exchange runs first. Under
4821 /// `socks5://`, the fetcher resolves a host name first and tries each
4822 /// address over a connection of its own, as [`socks_each`] states. Then
4823 /// the connection goes on as a direct connection does, for a cleartext
4824 /// origin and for a TLS origin.
4825 ///
4826 /// A failure states if another attempt can get a different result. A proxy
4827 /// that refuses the tunnel with 407 refuses the credential of the fetcher,
4828 /// and no round of retries changes it. A SOCKS5 proxy that accepts no
4829 /// offered method or refuses the user name and the password does the
4830 /// same. A host name that SOCKS5 cannot send is definitive too. Each other
4831 /// failure is retryable.
4832 async fn connect(&self, key: &PoolKey, via: Via<'_>) -> std::result::Result<Sender, Failure> {
4833 let origin = &key.origin;
4834 let tcp = match via {
4835 Via::Direct => rt::TcpStream::connect(&origin.host, origin.port)
4836 .await
4837 .map_err(|e| {
4838 Failure::Retry(Error::Fetch(format!(
4839 "connect to {}:{} failed: {e}",
4840 origin.host, origin.port
4841 )))
4842 })?,
4843 // The key of a proxied cleartext origin is the proxy endpoint.
4844 Via::Absolute(proxy) | Via::Tunnel(proxy) => connect_proxy(proxy).await?,
4845 Via::Socks(proxy, socks) => socks_connect(proxy, socks, origin).await?,
4846 };
4847 if !origin.tls {
4848 // Cleartext HTTP/2 needs prior knowledge or an upgrade. The
4849 // fetcher uses neither. So a cleartext origin speaks HTTP/1.1,
4850 // over a proxy and over a direct connection.
4851 return self
4852 .handshake_h1(key, FuturesIo::new(tcp))
4853 .await
4854 .map_err(Failure::Retry);
4855 }
4856 let tcp = match via {
4857 Via::Tunnel(proxy) => self.tunnel(proxy, origin, tcp).await?,
4858 Via::Direct | Via::Absolute(_) | Via::Socks(..) => tcp,
4859 };
4860 let server_name =
4861 rustls::pki_types::ServerName::try_from(origin.host.clone()).map_err(|e| {
4862 Failure::Retry(Error::Fetch(format!(
4863 "invalid server name {}: {e}",
4864 origin.host
4865 )))
4866 })?;
4867 let config = if key.identity {
4868 &self.inner.tls.with_identity
4869 } else {
4870 &self.inner.tls.without_identity
4871 };
4872 let stream = futures_rustls::TlsConnector::from(config.clone())
4873 .connect(server_name, tcp)
4874 .await
4875 .map_err(|e| {
4876 Failure::Retry(Error::Fetch(format!(
4877 "tls handshake with {} failed: {e}",
4878 origin.host
4879 )))
4880 })?;
4881 let h2 = stream.get_ref().1.alpn_protocol() == Some(b"h2");
4882 let io = FuturesIo::new(stream);
4883 if h2 {
4884 self.handshake_h2(key, io).await.map_err(Failure::Retry)
4885 } else {
4886 self.handshake_h1(key, io).await.map_err(Failure::Retry)
4887 }
4888 }
4889
4890 /// Asks `proxy` for a tunnel to `origin`, and returns the socket of the
4891 /// tunnel.
4892 ///
4893 /// The `CONNECT` goes over the HTTP/1.1 client of hyper, which reads the
4894 /// answer and gives the socket back. A 2xx to a `CONNECT` is an upgrade,
4895 /// and the upgraded I/O is the stream of the handshake. The connection
4896 /// future delivers it, so the future runs in its own task and ends with the
4897 /// upgrade.
4898 ///
4899 /// Bytes in the buffer after the response fail the connect. Nothing comes
4900 /// after a `CONNECT` response before the client speaks. So a proxy that
4901 /// sent bytes does not speak the protocol of the tunnel. A TLS handshake
4902 /// over that stream starts to read after those bytes.
4903 async fn tunnel(
4904 &self,
4905 proxy: &ProxyEndpoint,
4906 origin: &Origin,
4907 tcp: rt::TcpStream,
4908 ) -> std::result::Result<rt::TcpStream, Failure> {
4909 let refused = |what: String| Failure::Retry(Error::Fetch(what));
4910 let authority = connect_authority(origin);
4911 let host = HeaderValue::try_from(&authority).map_err(|_| {
4912 Failure::Fatal(Error::Fetch(format!(
4913 "the proxy {} cannot be asked to reach {authority}, which is not a usable host",
4914 proxy.named
4915 )))
4916 })?;
4917 let mut builder = Request::builder()
4918 .method(Method::CONNECT)
4919 .uri(&authority)
4920 .header(hyper::header::HOST, host);
4921 if let ProxyKind::Http {
4922 credential: Some(credential),
4923 } = &proxy.kind
4924 {
4925 builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
4926 }
4927 let request = builder.body(RequestBody::Empty).map_err(|e| {
4928 refused(format!(
4929 "the connect request to the proxy {} for {authority} is invalid: {e}",
4930 proxy.named
4931 ))
4932 })?;
4933 let (mut sender, connection) = hyper::client::conn::http1::handshake(FuturesIo::new(tcp))
4934 .await
4935 .map_err(|e| {
4936 refused(format!(
4937 "http/1.1 handshake with the proxy {} failed: {e}",
4938 proxy.named
4939 ))
4940 })?;
4941 // The connection future delivers the upgrade, so it runs beside the
4942 // request. The future and its task end with the upgrade.
4943 drop(rt::spawn(async move {
4944 let _ = connection.with_upgrades().await;
4945 }));
4946 let response = async {
4947 sender.ready().await?;
4948 sender.send_request(request).await
4949 }
4950 .await
4951 .map_err(|e| {
4952 refused(format!(
4953 "connect to {authority} through the proxy {} failed: {e}",
4954 proxy.named
4955 ))
4956 })?;
4957 let status = response.status();
4958 if !status.is_success() {
4959 let message = format!(
4960 "the proxy {} answered the connect to {authority} with {}",
4961 proxy.named,
4962 status.as_u16()
4963 );
4964 // A 407 refuses the credential of the fetcher, or the absence of
4965 // one. Each round of retries offers the same again.
4966 return Err(match status {
4967 StatusCode::PROXY_AUTHENTICATION_REQUIRED => Failure::Fatal(Error::Fetch(message)),
4968 _ => Failure::Retry(Error::Fetch(message)),
4969 });
4970 }
4971 let upgraded = hyper::upgrade::on(response).await.map_err(|e| {
4972 refused(format!(
4973 "the proxy {} accepted the connect to {authority} without tunneling it: {e}",
4974 proxy.named
4975 ))
4976 })?;
4977 let parts = upgraded
4978 .downcast::<FuturesIo<rt::TcpStream>>()
4979 .map_err(|_| {
4980 refused(format!(
4981 "the tunnel through the proxy {} to {authority} is not the socket it was \
4982 opened over",
4983 proxy.named
4984 ))
4985 })?;
4986 if !parts.read_buf.is_empty() {
4987 return Err(refused(format!(
4988 "the proxy {} sent {} bytes after the connect to {authority}, which nothing may \
4989 follow",
4990 proxy.named,
4991 parts.read_buf.len()
4992 )));
4993 }
4994 Ok(parts.io.into_inner())
4995 }
4996
4997 /// Completes an HTTP/1.1 handshake, and runs the connection in its own
4998 /// task.
4999 async fn handshake_h1<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
5000 where
5001 S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
5002 {
5003 let (sender, connection) =
5004 hyper::client::conn::http1::handshake(io)
5005 .await
5006 .map_err(|e| {
5007 Error::Fetch(format!(
5008 "http/1.1 handshake with {} failed: {e}",
5009 key.origin.host
5010 ))
5011 })?;
5012 drop(rt::spawn(async move {
5013 // The connection ends when the last sender drops or the peer closes
5014 // it. An error here shows on the next request over it.
5015 let _ = connection.await;
5016 }));
5017 Ok(Sender::H1(sender))
5018 }
5019
5020 /// Completes an HTTP/2 handshake, runs the connection in its own task, and
5021 /// puts it in the pool.
5022 ///
5023 /// The next requests to this origin multiplex over the connection. The
5024 /// function opens the connection through the builder of hyper. Only the
5025 /// builder sets the flow-control windows and the keep-alive ping.
5026 async fn handshake_h2<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
5027 where
5028 S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
5029 {
5030 let (sender, connection) = hyper::client::conn::http2::Builder::new(RtExecutor)
5031 .timer(RtTimer)
5032 .initial_stream_window_size(H2_STREAM_WINDOW)
5033 .initial_connection_window_size(self.inner.h2_connection_window)
5034 .keep_alive_interval(H2_KEEP_ALIVE_INTERVAL)
5035 .keep_alive_timeout(H2_KEEP_ALIVE_TIMEOUT)
5036 .handshake(io)
5037 .await
5038 .map_err(|e| {
5039 Error::Fetch(format!(
5040 "http/2 handshake with {} failed: {e}",
5041 key.origin.host
5042 ))
5043 })?;
5044 drop(rt::spawn(async move {
5045 let _ = connection.await;
5046 }));
5047 self.inner.put_h2(key, sender.clone());
5048 Ok(Sender::H2(sender))
5049 }
5050}
5051
5052impl Inner {
5053 /// Returns a pooled connection for `key`, if one is still usable.
5054 ///
5055 /// An HTTP/1.1 connection comes with the instant at which it became idle.
5056 /// [`Inner::put_idle_h1`] takes that instant back if the connection
5057 /// carried no request.
5058 fn take_conn(&self, key: &PoolKey) -> Option<(Sender, Option<Instant>)> {
5059 let mut pool = self.pool.lock().expect("fetcher pool mutex");
5060 let entry = pool.get_mut(key)?;
5061 if let Some(h2) = &entry.h2 {
5062 if h2.is_closed() {
5063 entry.h2 = None;
5064 } else {
5065 return Some((Sender::H2(h2.clone()), None));
5066 }
5067 }
5068 while let Some(h1) = entry.h1.pop() {
5069 if !h1.sender.is_closed() {
5070 return Some((Sender::H1(h1.sender), Some(h1.since)));
5071 }
5072 }
5073 None
5074 }
5075
5076 /// Returns a pooled connection that an upload can take for `key`.
5077 ///
5078 /// This is the HTTP/2 connection. If there is none, it is the HTTP/1.1
5079 /// connection that became idle last, if it became idle less than
5080 /// [`UPLOAD_IDLE`] ago.
5081 ///
5082 /// A server can close an idle connection at any time. If hyper began to
5083 /// write a request over a connection that the server closed, the request
5084 /// counts as sent. A server closes an idle connection at the end of its
5085 /// idle timeout, which is seconds or more. So the server keeps a connection
5086 /// that became idle a short time ago.
5087 ///
5088 /// An older idle connection stays in the pool for a fetch. If a fetch over
5089 /// it fails, the fetcher sends the fetch again.
5090 ///
5091 /// An HTTP/1.1 connection comes with the instant at which it became idle,
5092 /// as [`Inner::take_conn`] gives it.
5093 fn take_upload(&self, key: &PoolKey) -> Option<(Sender, Option<Instant>)> {
5094 let mut pool = self.pool.lock().expect("fetcher pool mutex");
5095 let entry = pool.get_mut(key)?;
5096 match &entry.h2 {
5097 Some(h2) if h2.is_closed() => entry.h2 = None,
5098 Some(h2) => return Some((Sender::H2(h2.clone()), None)),
5099 None => {}
5100 }
5101 while let Some(h1) = entry.h1.last() {
5102 if h1.sender.is_closed() {
5103 entry.h1.pop();
5104 continue;
5105 }
5106 if h1.since.elapsed() >= UPLOAD_IDLE {
5107 return None;
5108 }
5109 return entry
5110 .h1
5111 .pop()
5112 .map(|h1| (Sender::H1(h1.sender), Some(h1.since)));
5113 }
5114 None
5115 }
5116
5117 /// Returns an idle HTTP/1.1 connection to the pool.
5118 ///
5119 /// The function finds the existing entry of an origin by reference. A new
5120 /// entry needs a key of its own, and the host string of that key is an
5121 /// allocation. The lookup by reference keeps that allocation off the warm
5122 /// path of each object fetch.
5123 fn put_h1(&self, key: &PoolKey, sender: H1Sender) {
5124 self.put_idle_h1(key, sender, Instant::now());
5125 }
5126
5127 /// Returns an HTTP/1.1 connection to the pool that has been idle since
5128 /// `since`.
5129 ///
5130 /// A connection that the fetcher took and did not use goes back with the
5131 /// instant at which it became idle. So [`Inner::take_upload`] reads its
5132 /// true idle time.
5133 fn put_idle_h1(&self, key: &PoolKey, sender: H1Sender, since: Instant) {
5134 if sender.is_closed() {
5135 return;
5136 }
5137 let idle = IdleH1 { sender, since };
5138 let mut pool = self.pool.lock().expect("fetcher pool mutex");
5139 if let Some(entry) = pool.get_mut(key) {
5140 entry.h1.push(idle);
5141 return;
5142 }
5143 pool.entry(key.clone()).or_default().h1.push(idle);
5144 }
5145
5146 /// Records the HTTP/2 connection of the origin, and keeps a usable
5147 /// connection that is already in the pool.
5148 ///
5149 /// Two concurrent connects to one origin each complete a handshake. The
5150 /// connection that loses the race serves only the request that opened it,
5151 /// and closes with that request. So it does not replace a pooled entry
5152 /// that other requests multiplex over. A replaced entry stays open, with
5153 /// no pool reference, until its own senders drop.
5154 ///
5155 /// The function finds the existing entry of an origin by reference, as
5156 /// [`Inner::put_h1`] does.
5157 fn put_h2(&self, key: &PoolKey, sender: H2Sender) {
5158 let mut pool = self.pool.lock().expect("fetcher pool mutex");
5159 if let Some(entry) = pool.get_mut(key) {
5160 match &entry.h2 {
5161 Some(pooled) if !pooled.is_closed() => {}
5162 _ => entry.h2 = Some(sender),
5163 }
5164 return;
5165 }
5166 pool.entry(key.clone()).or_default().h2 = Some(sender);
5167 }
5168}
5169
5170/// A fetch that starts again if its body fails in transit.
5171///
5172/// A body fails in transit in these cases:
5173///
5174/// - the connection reports an error
5175/// - the peer stays silent past the
5176/// [`progress_timeout`](FetcherOptions::progress_timeout) window
5177/// - the transfer is slower than the
5178/// [`low_speed`](FetcherOptions::low_speed) rule allows.
5179///
5180/// Each refetch spends one repeat of
5181/// [`max_retries`](FetcherOptions::max_retries), the count that also limits
5182/// the rounds of the fetch. So the rounds of each fetch and the refetches
5183/// between them share one budget. A refetch sends the request again, from
5184/// the first destination. It sends the `Range` header of the request again,
5185/// if the request has one, and adds no `Range` header of its own. So a
5186/// refetch asks for the whole body again, or for the same part of it.
5187///
5188/// A body that fails in another way is not fetched again, because another
5189/// fetch fails in the same way. Examples are the size cap and a failure of
5190/// the consumer, such as a checksum mismatch.
5191pub struct Refetch<'f, 'r> {
5192 fetcher: &'f Fetcher,
5193 request: FetchRequest<'r>,
5194 /// The repeats left in the budget.
5195 left: u32,
5196 /// The repeats spent. The next delay doubles from this count.
5197 round: u32,
5198 /// The flag that the body of the latest fetch sets if it fails in transit.
5199 interrupted: Arc<AtomicBool>,
5200}
5201
5202impl Refetch<'_, '_> {
5203 /// Fetches the request, with the rest of the budget for its rounds.
5204 ///
5205 /// # Errors
5206 ///
5207 /// This method returns the errors that [`Fetcher::fetch`] returns.
5208 pub async fn fetch(&mut self) -> Result<Fetched> {
5209 self.interrupted.store(false, Ordering::Relaxed);
5210 let (mut fetched, used) = self
5211 .fetcher
5212 .fetch_budgeted(&self.request, self.left)
5213 .await?;
5214 self.left -= used;
5215 self.round += used;
5216 if let Fetched::Body(body) = &mut fetched {
5217 body.interrupted = Some(self.interrupted.clone());
5218 }
5219 Ok(fetched)
5220 }
5221
5222 /// Prepares the next refetch, or returns `error` if no refetch applies.
5223 ///
5224 /// `error` is the error that ended the consumer of the latest body, in the
5225 /// error type of the caller. If that body failed in transit and a repeat
5226 /// is left, the method spends the repeat. It then waits for the backoff
5227 /// delay before the next [`fetch`](Refetch::fetch).
5228 ///
5229 /// The consumer drops the body before it calls this method. So the delay
5230 /// holds no connection and no admission permit.
5231 ///
5232 /// # Errors
5233 ///
5234 /// Returns `error` as it is if the latest body did not fail in transit, or
5235 /// if no repeat is left.
5236 pub async fn retry<E>(&mut self, error: E) -> std::result::Result<(), E> {
5237 if !self.interrupted.load(Ordering::Relaxed) || self.left == 0 {
5238 return Err(error);
5239 }
5240 self.left -= 1;
5241 self.round += 1;
5242 rt::Timer::after(backoff(self.round)).await;
5243 Ok(())
5244 }
5245}
5246
5247/// The result of one attempt.
5248#[allow(clippy::large_enum_variant)]
5249enum Attempted {
5250 Body(Body),
5251 NotModified,
5252}
5253
5254/// A failure that ends a body. Each later read gives it again.
5255struct Failed {
5256 kind: std::io::ErrorKind,
5257 message: String,
5258}
5259
5260impl Failed {
5261 fn error(&self) -> std::io::Error {
5262 std::io::Error::new(self.kind, self.message.clone())
5263 }
5264}
5265
5266/// The response body of a fetch or of an upload.
5267///
5268/// A read gives the bytes of the response in bounded chunks. The body releases
5269/// its connection and the admission permit when it reaches its end or is
5270/// dropped. A body dropped before its end closes an HTTP/1.1 connection and
5271/// resets an HTTP/2 stream, because the rest of the response is still in
5272/// flight.
5273///
5274/// # Failures
5275///
5276/// A failure ends the body. The failed read and each later read fail with the
5277/// same error. So a consumer that reads past a failure never gets a clean end
5278/// of stream, and cannot take a truncated object for a complete one. The
5279/// failures and their error kinds are:
5280///
5281/// - the size cap: [`FileTooLarge`](std::io::ErrorKind::FileTooLarge)
5282/// - the progress window and the low-speed rule:
5283/// [`TimedOut`](std::io::ErrorKind::TimedOut)
5284/// - a transport failure: [`Other`](std::io::ErrorKind::Other).
5285///
5286/// A failure releases neither the connection nor the permit. The drop of the
5287/// body releases both.
5288pub struct Body {
5289 incoming: Incoming,
5290 /// Bytes received from the connection and not yet copied to the caller.
5291 chunk: Bytes,
5292 /// The bytes taken from the connection. The caller is behind this count by
5293 /// the bytes still in `chunk`. The size cap applies to this count.
5294 received: u64,
5295 max_size: Option<u64>,
5296 status: u16,
5297 validators: Validators,
5298 content_length: Option<u64>,
5299 protocol: Protocol,
5300 inner: Arc<Inner>,
5301 /// The counters of the fetcher handle that made the request. Each data
5302 /// frame adds its bytes to each of them.
5303 counters: Arc<[Arc<AtomicU64>]>,
5304 /// The pool entry of the connection of this body. The connection goes back
5305 /// to this entry.
5306 key: PoolKey,
5307 /// The HTTP/1.1 connection to return to the pool at the end of the body.
5308 reuse: Option<H1Sender>,
5309 /// The admission permit, which the body holds while it is in flight.
5310 permit: Option<Permit>,
5311 done: bool,
5312 /// The failure that ended the body, if one did.
5313 failed: Option<Failed>,
5314 /// The time that the peer can stay silent while a read waits for it.
5315 deadline: rt::Deadline,
5316 /// `true` while the window runs, from the read that finds nothing until
5317 /// the next frame arrives.
5318 ///
5319 /// The window measures the silence since a read wanted bytes. It keeps
5320 /// running also when no read is outstanding. A body that no read found
5321 /// empty is not on the clock.
5322 waiting: bool,
5323 /// The low-speed rule of the body, if the fetcher has one.
5324 low_speed: Option<Monitor>,
5325 /// The flag that reports a failure in transit to a [`Refetch`], which
5326 /// fetches the body again. The size cap is not a failure in transit,
5327 /// because another fetch of the body grows past the cap in the same way.
5328 interrupted: Option<Arc<AtomicBool>>,
5329 /// The request body of an upload. It fails when this body ends, or when
5330 /// this body is dropped before the request body ends.
5331 request_body: Option<RequestEnd>,
5332}
5333
5334/// The low-speed state of one body: the delivered bytes, the last samples of
5335/// that count, and the time below the limit.
5336struct Monitor {
5337 rule: LowSpeed,
5338 /// The bytes that the body delivered since its first read.
5339 counted: u64,
5340 /// `counted` at the last [`RATE_SPAN`] samples. The slot of the next
5341 /// sample holds the oldest sample. A slot that no sample filled holds the
5342 /// count at the first read, which is zero.
5343 samples: [u64; RATE_SPAN],
5344 /// The samples taken since the first read.
5345 taken: u64,
5346 /// The whole seconds for which the rate stayed at or below the limit, or
5347 /// `None` while the rate is above it. A body starts below the limit, at
5348 /// zero.
5349 below: Option<u64>,
5350 /// The time to the next sample.
5351 deadline: rt::Deadline,
5352 /// `true` after the measurement starts, which is at the first read.
5353 started: bool,
5354}
5355
5356impl Monitor {
5357 /// Creates the monitor for `rule`. The measurement starts at the first
5358 /// read.
5359 fn new(rule: LowSpeed) -> Monitor {
5360 Monitor {
5361 rule,
5362 counted: 0,
5363 samples: [0; RATE_SPAN],
5364 taken: 0,
5365 below: Some(0),
5366 deadline: rt::Deadline::new(SAMPLE_PERIOD),
5367 started: false,
5368 }
5369 }
5370
5371 /// Returns `true` if the rate stayed below the limit for the time of the
5372 /// rule.
5373 ///
5374 /// Each expiry of the timer takes one sample. If the next sample is not
5375 /// due, the poll leaves the timer to wake the task at the due time.
5376 fn below_rate(&mut self, cx: &mut Context<'_>) -> bool {
5377 while self.deadline.poll_expired(cx).is_ready() {
5378 if self.sample() {
5379 return true;
5380 }
5381 self.deadline.restart();
5382 }
5383 false
5384 }
5385
5386 /// Takes one sample, and returns `true` if the rate now stayed below the
5387 /// limit for the time of the rule.
5388 fn sample(&mut self) -> bool {
5389 self.taken += 1;
5390 let slot = (self.taken % RATE_SPAN as u64) as usize;
5391 let span = self.taken.min(RATE_SPAN as u64);
5392 let carried = self.counted - self.samples[slot];
5393 self.samples[slot] = self.counted;
5394 // A sample of exactly the limit counts as below it, as in the `ostree`
5395 // command. The samples of that command span a little more than their
5396 // whole seconds.
5397 if carried > u64::from(self.rule.limit) * span {
5398 self.below = None;
5399 return false;
5400 }
5401 let below = self.below.map_or(0, |seconds| seconds + 1);
5402 self.below = Some(below);
5403 Duration::from_secs(below) >= self.rule.time
5404 }
5405}
5406
5407impl std::fmt::Debug for Body {
5408 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5409 f.debug_struct("Body")
5410 .field("protocol", &self.protocol)
5411 .field("content_length", &self.content_length)
5412 .field("received", &self.received)
5413 .finish_non_exhaustive()
5414 }
5415}
5416
5417impl Body {
5418 /// Returns the status of the response that carries the body.
5419 ///
5420 /// The status of a fetch is 200, or 206 for a request with a `Range`
5421 /// header. A caller that sends `Range` reads the status to tell a part of
5422 /// the object from the whole object. The status of the body of an upload
5423 /// is [`Uploaded::status`].
5424 pub fn status(&self) -> u16 {
5425 self.status
5426 }
5427
5428 /// Returns the validators to send on the next fetch of this target.
5429 pub fn validators(&self) -> &Validators {
5430 &self.validators
5431 }
5432
5433 /// Returns the `Content-Length` that the response declared, if it declared
5434 /// one.
5435 pub fn content_length(&self) -> Option<u64> {
5436 self.content_length
5437 }
5438
5439 /// Returns the HTTP version that carried the response.
5440 pub fn protocol(&self) -> Protocol {
5441 self.protocol
5442 }
5443
5444 /// Returns the number of bytes that the body took from the connection.
5445 ///
5446 /// The body takes a frame whole and gives it out in as many reads as the
5447 /// buffers of the caller need. So this count can be up to one frame ahead
5448 /// of the bytes that the caller read. The size cap applies to this count.
5449 /// A caller that needs the count of delivered bytes counts them in its own
5450 /// read loop.
5451 pub fn received(&self) -> u64 {
5452 self.received
5453 }
5454
5455 /// Latches a failure that ends the body, and returns it.
5456 ///
5457 /// The body keeps the connection and the permit, so the drop releases
5458 /// them. The drop closes the connection, because a response still in
5459 /// flight does not go back to the pool.
5460 fn fail(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
5461 let failed = Failed { kind, message };
5462 let error = failed.error();
5463 self.failed = Some(failed);
5464 error
5465 }
5466
5467 /// Latches a failure in transit, and returns it. A [`Refetch`] can repeat
5468 /// the fetch for such a failure.
5469 fn interrupt(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
5470 if let Some(interrupted) = &self.interrupted {
5471 interrupted.store(true, Ordering::Relaxed);
5472 }
5473 self.fail(kind, message)
5474 }
5475
5476 /// Returns the failure of the low-speed rule, if the rate stayed at or
5477 /// below the limit for the time of the rule.
5478 ///
5479 /// Returns `None` while the rate holds, or if no rule applies.
5480 fn poll_low_speed(&mut self, cx: &mut Context<'_>) -> Option<std::io::Error> {
5481 let monitor = self.low_speed.as_mut()?;
5482 if !monitor.below_rate(cx) {
5483 return None;
5484 }
5485 let LowSpeed { limit, time } = monitor.rule;
5486 Some(self.interrupt(
5487 std::io::ErrorKind::TimedOut,
5488 format!("fetched body averaged below {limit} bytes per second for {time:?}"),
5489 ))
5490 }
5491}
5492
5493/// The read trait of `futures-io`.
5494impl AsyncRead for Body {
5495 fn poll_read(
5496 self: Pin<&mut Self>,
5497 cx: &mut Context<'_>,
5498 buf: &mut [u8],
5499 ) -> Poll<std::io::Result<usize>> {
5500 if buf.is_empty() {
5501 return Poll::Ready(Ok(0));
5502 }
5503 let me = self.get_mut();
5504 if let Some(failed) = &me.failed {
5505 return Poll::Ready(Err(failed.error()));
5506 }
5507 // The low-speed measurement starts at the first read. So the time for
5508 // which a body waits for its consumer before that read is not counted.
5509 if let Some(monitor) = &mut me.low_speed
5510 && !monitor.started
5511 {
5512 monitor.deadline.restart();
5513 monitor.started = true;
5514 }
5515 loop {
5516 if !me.chunk.is_empty() {
5517 let n = me.chunk.len().min(buf.len());
5518 buf[..n].copy_from_slice(&me.chunk[..n]);
5519 me.chunk = me.chunk.slice(n..);
5520 return Poll::Ready(Ok(n));
5521 }
5522 if me.done {
5523 return Poll::Ready(Ok(0));
5524 }
5525 let frame = match Pin::new(&mut me.incoming).poll_frame(cx) {
5526 Poll::Ready(frame) => frame,
5527 Poll::Pending => {
5528 // Nothing arrived since the last frame. So the read fails
5529 // when the progress window runs out, or when the rate
5530 // stayed below the low-speed limit for the time of the rule.
5531 if let Some(error) = me.poll_low_speed(cx) {
5532 return Poll::Ready(Err(error));
5533 }
5534 if !me.waiting {
5535 me.deadline.restart();
5536 me.waiting = true;
5537 }
5538 return match me.deadline.poll_expired(cx) {
5539 Poll::Ready(()) => {
5540 let window = me.deadline.window();
5541 Poll::Ready(Err(me.interrupt(
5542 std::io::ErrorKind::TimedOut,
5543 format!("fetched body delivered nothing for {window:?}"),
5544 )))
5545 }
5546 Poll::Pending => Poll::Pending,
5547 };
5548 }
5549 };
5550 match frame {
5551 Some(Ok(frame)) => {
5552 // The peer delivered. The window stops until the next read
5553 // finds nothing.
5554 me.waiting = false;
5555 // Trailers carry no payload, so the loop polls again for
5556 // data.
5557 if let Ok(data) = frame.into_data() {
5558 me.received += data.len() as u64;
5559 for counter in me.counters.iter() {
5560 counter.fetch_add(data.len() as u64, Ordering::Relaxed);
5561 }
5562 if let Some(limit) = me.max_size
5563 && me.received > limit
5564 {
5565 return Poll::Ready(Err(me.fail(
5566 std::io::ErrorKind::FileTooLarge,
5567 format!("fetched body exceeds the {limit}-byte cap"),
5568 )));
5569 }
5570 if let Some(monitor) = &mut me.low_speed {
5571 monitor.counted += data.len() as u64;
5572 }
5573 me.chunk = data;
5574 if let Some(error) = me.poll_low_speed(cx) {
5575 return Poll::Ready(Err(error));
5576 }
5577 }
5578 }
5579 Some(Err(e)) => {
5580 // hyper reports a body error once, and then reports the end
5581 // of the body. Without the latch, the next read returns a
5582 // clean end of stream for a truncated object.
5583 let message = with_cause(&e);
5584 return Poll::Ready(Err(me.interrupt(std::io::ErrorKind::Other, message)));
5585 }
5586 None => {
5587 me.done = true;
5588 // The whole response arrived, so the connection can serve
5589 // the next request. The response to an upload ends its
5590 // request body, and hyper then stops the send of that body.
5591 if let Some(sender) = me.reuse.take() {
5592 me.inner.put_h1(&me.key, sender);
5593 }
5594 me.request_body = None;
5595 me.permit = None;
5596 return Poll::Ready(Ok(0));
5597 }
5598 }
5599 }
5600 }
5601}
5602
5603/// The read trait of tokio.
5604#[cfg(feature = "tokio")]
5605impl rt::tokio_io::AsyncRead for Body {
5606 fn poll_read(
5607 self: Pin<&mut Self>,
5608 cx: &mut Context<'_>,
5609 buf: &mut rt::tokio_io::ReadBuf<'_>,
5610 ) -> Poll<std::io::Result<()>> {
5611 let unfilled = buf.initialize_unfilled();
5612 let n = ready!(AsyncRead::poll_read(self, cx, unfilled))?;
5613 buf.advance(n);
5614 Poll::Ready(Ok(()))
5615 }
5616}
5617
5618/// The writing end of a streamed [`UploadBody`], from
5619/// [`UploadBody::channel`].
5620///
5621/// The writer and the upload run together. So a caller writes from a task
5622/// other than the task that awaits [`Fetcher::upload`], or joins the two
5623/// futures.
5624///
5625/// # Frames
5626///
5627/// Writes fill a frame of 64 KiB. The writer gives a full frame to the
5628/// connection through a slot of one frame. If the slot is still full, a write
5629/// waits until hyper takes the frame in it.
5630///
5631/// - [`flush`](AsyncWrite::poll_flush) hands over a part-filled frame, and
5632/// waits until hyper takes it.
5633/// - [`close`](AsyncWrite::poll_close) hands over the rest, ends the body,
5634/// and waits until hyper takes the end.
5635///
5636/// A flush of less than 4 KiB hands over a copy of the bytes and keeps the
5637/// frame buffer. A larger frame moves to the connection as it is, and the next
5638/// write allocates the next buffer.
5639///
5640/// # Memory
5641///
5642/// The writer holds at most two frames: the frame that it fills and the frame
5643/// in the slot. The connection holds more for each upload in flight.
5644///
5645/// Over HTTP/1.1, hyper takes another frame while it holds fewer than 16
5646/// frames and less than 408 KiB. So it holds up to 472 KiB. Over HTTP/2, it
5647/// holds up to two frames.
5648///
5649/// # Stalls
5650///
5651/// After the upload hands its request to the connection, a frame can wait in
5652/// the slot for the [`progress_timeout`](FetcherOptions::progress_timeout) of
5653/// its fetcher. If it does, the wait fails with
5654/// [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut), and the body
5655/// fails. Before the hand-over, a wait has no bound of its own.
5656///
5657/// # Failures
5658///
5659/// If the writer is dropped before close, the body fails. So hyper ends the
5660/// request unfinished, and the server never receives a truncated body as a
5661/// whole body. A writer dropped before the hand-over leaves the request
5662/// unsent.
5663///
5664/// A write fails with
5665/// [`io::ErrorKind::BrokenPipe`](std::io::ErrorKind::BrokenPipe) in these
5666/// cases:
5667///
5668/// - after close
5669/// - after the upload is done with the body
5670/// - after the response ended before the body.
5671///
5672/// A failure is latched: each later call fails in the same way.
5673pub struct UploadWriter {
5674 exchange: Arc<Exchange>,
5675 /// The frame that the writer fills. If a frame is handed over whole, the
5676 /// buffer has no capacity, and the next write allocates the next frame.
5677 buffer: Vec<u8>,
5678 /// The timer of the stall window. The first wait on a full slot after the
5679 /// hand-over arms it. If the timer fires before the frame in the slot
5680 /// waited the whole window, the writer arms it again for the rest.
5681 stall: Option<rt::Deadline>,
5682 /// The failure that ended the writer, if one did.
5683 failed: Option<Failed>,
5684}
5685
5686impl std::fmt::Debug for UploadWriter {
5687 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5688 f.debug_struct("UploadWriter")
5689 .field("buffered", &self.buffer.len())
5690 .finish_non_exhaustive()
5691 }
5692}
5693
5694/// The message of a write after the upload is done with the body.
5695const UPLOAD_ENDED: &str = "the upload of this body has ended";
5696
5697impl UploadWriter {
5698 /// Returns `true` if the request of this body is handed over to a
5699 /// connection.
5700 ///
5701 /// The value becomes `true` at the hand-over. It becomes `false` again if
5702 /// the connection gives the request back unwritten, until the next round
5703 /// hands it over. A caller that counts the bytes that a request sent counts
5704 /// the bytes that it wrote after the hand-over.
5705 pub fn is_handed_over(&self) -> bool {
5706 self.exchange.lock().stall.is_some()
5707 }
5708
5709 /// Latches a failure that ends the writer, and returns it.
5710 fn fail(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
5711 let failed = Failed { kind, message };
5712 let error = failed.error();
5713 self.failed = Some(failed);
5714 error
5715 }
5716
5717 /// Moves the buffer into the slot as the next frame, when the slot is
5718 /// free.
5719 ///
5720 /// The function copies a frame of less than [`SMALL_FRAME`] bytes, and
5721 /// keeps the buffer for the next frames. So a small frame that waits in the
5722 /// connection holds no more memory than its bytes. A larger frame moves as
5723 /// it is, and the next write allocates the next buffer.
5724 fn poll_hand_over(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5725 let mut slot = self.exchange.lock();
5726 if slot.gone || slot.aborted.is_some() {
5727 drop(slot);
5728 return Poll::Ready(Err(
5729 self.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
5730 ));
5731 }
5732 if slot.frame.is_some() {
5733 park(&mut slot.writer, cx);
5734 let end = slot.stall_end();
5735 drop(slot);
5736 return self.poll_stall(cx, end);
5737 }
5738 let frame = if self.buffer.len() < SMALL_FRAME {
5739 let frame = Bytes::copy_from_slice(&self.buffer);
5740 self.buffer.clear();
5741 frame
5742 } else {
5743 Bytes::from(std::mem::take(&mut self.buffer))
5744 };
5745 slot.frame = Some(frame);
5746 slot.restart_stall();
5747 let reader = slot.reader.take();
5748 drop(slot);
5749 wake(reader);
5750 Poll::Ready(Ok(()))
5751 }
5752
5753 /// Waits until hyper takes the frame in the slot.
5754 fn poll_taken(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5755 let mut slot = self.exchange.lock();
5756 if slot.gone || slot.aborted.is_some() {
5757 drop(slot);
5758 return Poll::Ready(Err(
5759 self.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
5760 ));
5761 }
5762 if slot.frame.is_none() {
5763 return Poll::Ready(Ok(()));
5764 }
5765 park(&mut slot.writer, cx);
5766 let end = slot.stall_end();
5767 drop(slot);
5768 self.poll_stall(cx, end)
5769 }
5770
5771 /// Polls the stall window of the frame in the slot. At `end`, the frame
5772 /// waited the whole window.
5773 ///
5774 /// The poll is pending while the window runs. It gives the failure of the
5775 /// body when the window runs out. Before the hand-over, `end` is `None`.
5776 /// The poll is then pending alone, and the take of the frame wakes the
5777 /// writer.
5778 fn poll_stall(
5779 &mut self,
5780 cx: &mut Context<'_>,
5781 mut end: Option<Instant>,
5782 ) -> Poll<std::io::Result<()>> {
5783 while let Some(at) = end {
5784 ready!(poll_until(&mut self.stall, cx, at));
5785 match self.exchange.check_stall() {
5786 Ok(message) => {
5787 return Poll::Ready(Err(self.fail(std::io::ErrorKind::TimedOut, message)));
5788 }
5789 Err(later) => end = later,
5790 }
5791 }
5792 Poll::Pending
5793 }
5794}
5795
5796/// The write trait of `futures-io`.
5797impl AsyncWrite for UploadWriter {
5798 fn poll_write(
5799 self: Pin<&mut Self>,
5800 cx: &mut Context<'_>,
5801 buf: &[u8],
5802 ) -> Poll<std::io::Result<usize>> {
5803 let me = self.get_mut();
5804 if let Some(failed) = &me.failed {
5805 return Poll::Ready(Err(failed.error()));
5806 }
5807 let slot = me.exchange.lock();
5808 let refused = if slot.gone || slot.aborted.is_some() {
5809 Some(UPLOAD_ENDED)
5810 } else if slot.closed {
5811 Some("the upload body is closed")
5812 } else {
5813 None
5814 };
5815 drop(slot);
5816 if let Some(message) = refused {
5817 return Poll::Ready(Err(me.fail(std::io::ErrorKind::BrokenPipe, message.into())));
5818 }
5819 if buf.is_empty() {
5820 return Poll::Ready(Ok(0));
5821 }
5822 if me.buffer.len() == UPLOAD_FRAME {
5823 ready!(me.poll_hand_over(cx))?;
5824 }
5825 if me.buffer.capacity() == 0 {
5826 me.buffer.reserve_exact(UPLOAD_FRAME);
5827 }
5828 let n = (UPLOAD_FRAME - me.buffer.len()).min(buf.len());
5829 me.buffer.extend_from_slice(&buf[..n]);
5830 Poll::Ready(Ok(n))
5831 }
5832
5833 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5834 let me = self.get_mut();
5835 if let Some(failed) = &me.failed {
5836 return Poll::Ready(Err(failed.error()));
5837 }
5838 if !me.buffer.is_empty() {
5839 ready!(me.poll_hand_over(cx))?;
5840 }
5841 me.poll_taken(cx)
5842 }
5843
5844 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5845 let me = self.get_mut();
5846 if let Some(failed) = &me.failed {
5847 return Poll::Ready(Err(failed.error()));
5848 }
5849 if !me.buffer.is_empty() {
5850 ready!(me.poll_hand_over(cx))?;
5851 }
5852 let mut slot = me.exchange.lock();
5853 let reader = if slot.closed {
5854 None
5855 } else {
5856 slot.closed = true;
5857 slot.reader.take()
5858 };
5859 if slot.ended {
5860 drop(slot);
5861 wake(reader);
5862 return Poll::Ready(Ok(()));
5863 }
5864 if slot.gone || slot.aborted.is_some() {
5865 drop(slot);
5866 return Poll::Ready(Err(
5867 me.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
5868 ));
5869 }
5870 park(&mut slot.writer, cx);
5871 // The stall window runs over a frame that waits in the slot. An empty
5872 // slot waits for hyper to poll the end, and that wait is no stall of
5873 // the body.
5874 let end = slot.stall_end();
5875 drop(slot);
5876 wake(reader);
5877 me.poll_stall(cx, end)
5878 }
5879}
5880
5881/// The write trait of tokio.
5882#[cfg(feature = "tokio")]
5883impl rt::tokio_io::AsyncWrite for UploadWriter {
5884 fn poll_write(
5885 self: Pin<&mut Self>,
5886 cx: &mut Context<'_>,
5887 buf: &[u8],
5888 ) -> Poll<std::io::Result<usize>> {
5889 AsyncWrite::poll_write(self, cx, buf)
5890 }
5891
5892 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5893 AsyncWrite::poll_flush(self, cx)
5894 }
5895
5896 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
5897 AsyncWrite::poll_close(self, cx)
5898 }
5899}
5900
5901impl Drop for UploadWriter {
5902 fn drop(&mut self) {
5903 let mut slot = self.exchange.lock();
5904 if slot.closed {
5905 return;
5906 }
5907 let wakers =
5908 slot.abort(|| "the upload writer was dropped before it closed the body".into());
5909 drop(slot);
5910 wakers.into_iter().for_each(wake);
5911 }
5912}
5913
5914/// Returns `true` if a header name carries credentials, which no cleartext
5915/// destination gets.
5916///
5917/// The value of these three header names is a secret, whatever it holds. The
5918/// fetcher sends each other header as the caller wrote it, except `Host` and
5919/// the connection-layer names, which both layers refuse. A caller can put a
5920/// secret into such a header, and the fetcher cannot tell.
5921fn is_credential(name: &HeaderName) -> bool {
5922 *name == hyper::header::AUTHORIZATION
5923 || *name == hyper::header::PROXY_AUTHORIZATION
5924 || *name == hyper::header::COOKIE
5925}
5926
5927/// Returns `true` if the connection layer sets a header of this name, so that
5928/// no caller can set it.
5929///
5930/// A `HeaderName` holds its name in lower case, and [`CONNECTION_HEADERS`] is
5931/// in lower case too.
5932fn is_connection_header(name: &HeaderName) -> bool {
5933 CONNECTION_HEADERS.contains(&name.as_str())
5934}
5935
5936/// Returns the error for a layer that sets a header of the connection layer.
5937fn connection_header_refused(name: &HeaderName) -> Error {
5938 Error::Fetch(format!(
5939 "the {name} header is set by the connection layer, which frames the request and \
5940 holds its connection: drop the header"
5941 ))
5942}
5943
5944/// Checks that a request path can go after the base path of a mirror.
5945///
5946/// A target is the base path with the request path added as written. So a `?`
5947/// or a `#` in that path is a delimiter. A `?` sends its tail as a query string
5948/// that the server matches on. A `#` and its tail drop out when the URL is
5949/// built, and the request asks for a different resource.
5950fn check_path(path: &str) -> Result<()> {
5951 if let Some(at) = path.find(['?', '#']) {
5952 let found = &path[at..=at];
5953 return Err(Error::Fetch(format!(
5954 "fetch path {path} carries {found}: a path holds no query and no fragment"
5955 )));
5956 }
5957 Ok(())
5958}
5959
5960/// Checks that the query string `query` of a request for `path` can go after
5961/// the path.
5962///
5963/// The target is the path with `?` and the query added as written. So a `#`
5964/// in the query is a delimiter. The `#` and its tail drop out when the URL is
5965/// built, and the server gets a query other than the query of the caller.
5966fn check_query(path: &str, query: &str) -> Result<()> {
5967 if query.contains('#') {
5968 return Err(Error::Fetch(format!(
5969 "fetch query of {path}?{query} carries #: a query holds no fragment"
5970 )));
5971 }
5972 Ok(())
5973}
5974
5975/// Returns the headers of one request: the headers of the fetcher, with the
5976/// headers of the request merged over them.
5977///
5978/// A request header replaces the fetcher header of the same name. The
5979/// credentials of the request replace the `Authorization` of the fetcher,
5980/// whichever of the two layers set it. These credentials are basic-auth
5981/// credentials or a bearer token, never both.
5982///
5983/// Two request headers of one name both reach the wire, as two fetcher headers
5984/// do. A request that adds no header and no credentials sends the list of the
5985/// fetcher as it is. Each object fetch takes this path.
5986///
5987/// A credential value is marked sensitive. So an HTTP/2 connection never adds
5988/// it to its header compression table.
5989fn merge_headers<'a>(
5990 fetcher: &'a [(HeaderName, HeaderValue)],
5991 extra: &[(String, String)],
5992 basic_auth: Option<&BasicAuth>,
5993 bearer_token: Option<&BearerToken>,
5994) -> Result<Cow<'a, [(HeaderName, HeaderValue)]>> {
5995 if extra.is_empty() && basic_auth.is_none() && bearer_token.is_none() {
5996 return Ok(Cow::Borrowed(fetcher));
5997 }
5998 if basic_auth.is_some() && bearer_token.is_some() {
5999 return Err(Error::Fetch(BASIC_AND_BEARER.into()));
6000 }
6001 let credential = usize::from(basic_auth.is_some() || bearer_token.is_some());
6002 let mut added = Vec::with_capacity(extra.len() + credential);
6003 for (name, value) in extra {
6004 let name = HeaderName::try_from(name.as_str())
6005 .map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
6006 if name == hyper::header::HOST {
6007 return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
6008 }
6009 if is_connection_header(&name) {
6010 return Err(connection_header_refused(&name));
6011 }
6012 if name == hyper::header::AUTHORIZATION && basic_auth.is_some() {
6013 return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
6014 }
6015 if name == hyper::header::AUTHORIZATION && bearer_token.is_some() {
6016 return Err(Error::Fetch(AMBIGUOUS_BEARER.into()));
6017 }
6018 let mut value = HeaderValue::try_from(value.as_str())
6019 .map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
6020 value.set_sensitive(is_credential(&name));
6021 added.push((name, value));
6022 }
6023 if let Some(auth) = basic_auth {
6024 added.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
6025 }
6026 if let Some(token) = bearer_token {
6027 added.push((hyper::header::AUTHORIZATION, bearer_value(token)?));
6028 }
6029 let mut headers = Vec::with_capacity(fetcher.len() + added.len());
6030 headers.extend(
6031 fetcher
6032 .iter()
6033 .filter(|(name, _)| !added.iter().any(|(replaced, _)| replaced == name))
6034 .cloned(),
6035 );
6036 headers.extend(added);
6037 Ok(Cow::Owned(headers))
6038}
6039
6040/// Refuses a credential beside a request signer: basic-auth credentials if
6041/// `basic_auth` is `true`, a bearer token if `bearer_token` is `true`, or an
6042/// `Authorization` entry in `headers`.
6043///
6044/// A signature can set `Authorization`, as each of these can. So the signer
6045/// goes alone, and a choice of one sends a credential that the caller did not
6046/// choose. [`Fetcher::new`] refuses these on the fetcher, and a fetch and an
6047/// upload refuse them on a request.
6048fn refuse_beside_signer(
6049 headers: &[(String, String)],
6050 basic_auth: bool,
6051 bearer_token: bool,
6052) -> Result<()> {
6053 if basic_auth {
6054 return Err(Error::Fetch(SIGNER_AND_BASIC.into()));
6055 }
6056 if bearer_token {
6057 return Err(Error::Fetch(SIGNER_AND_BEARER.into()));
6058 }
6059 if headers.iter().any(|(name, _)| {
6060 HeaderName::try_from(name.as_str()).is_ok_and(|name| name == hyper::header::AUTHORIZATION)
6061 }) {
6062 return Err(Error::Fetch(SIGNER_AND_AUTHORIZATION.into()));
6063 }
6064 Ok(())
6065}
6066
6067/// Returns the [`SignRequest`] of one request of `method` to `hop`, with
6068/// `payload`.
6069///
6070/// The path and the query come from the origin-form target of the hop, which
6071/// splits at its first `?`. The authority is the text of the `Host` header.
6072fn sign_request<'a>(
6073 method: &'a Method,
6074 hop: &'a Destination,
6075 payload: SignPayload<'a>,
6076) -> SignRequest<'a> {
6077 let target = hop.target();
6078 let (path, query) = match target.split_once('?') {
6079 Some((path, query)) => (path, Some(query)),
6080 None => (target, None),
6081 };
6082 SignRequest {
6083 method: method.as_str(),
6084 authority: hop.authority_text(),
6085 path,
6086 query,
6087 payload,
6088 }
6089}
6090
6091/// Returns `headers` with the headers that `signer` gives for one request of
6092/// `method` to `hop`, with `payload`.
6093///
6094/// [`merge_headers`] merges the headers of the signer as headers of a
6095/// request. So each one replaces a header of the same name, and a `Host`
6096/// header or a header of the connection layer is refused. Each value of the
6097/// signer is marked sensitive, because a signature header such as a session
6098/// token is a credential whatever its name is. An error of the signer, or a
6099/// refused header, is a [`Failure::Final`].
6100fn signed<'a>(
6101 signer: &dyn RequestSigner,
6102 method: &Method,
6103 hop: &Destination,
6104 payload: SignPayload<'_>,
6105 headers: &'a [(HeaderName, HeaderValue)],
6106) -> std::result::Result<Cow<'a, [(HeaderName, HeaderValue)]>, Failure> {
6107 let added = signer
6108 .sign(&sign_request(method, hop, payload))
6109 .map_err(Failure::Final)?;
6110 let merged = merge_headers(headers, &added, None, None).map_err(Failure::Final)?;
6111 if added.is_empty() {
6112 return Ok(merged);
6113 }
6114 // A name of the signer replaces each header of that name, so each entry
6115 // of such a name holds a value of the signer.
6116 let mut merged = merged.into_owned();
6117 for (name, value) in &mut merged {
6118 if added
6119 .iter()
6120 .any(|(added, _)| name.as_str().eq_ignore_ascii_case(added))
6121 {
6122 value.set_sensitive(true);
6123 }
6124 }
6125 Ok(Cow::Owned(merged))
6126}
6127
6128/// The state that the refusals of [`Fetcher::new`] that read no file give.
6129struct Checked {
6130 mirrors: Vec<Mirror>,
6131 headers: Vec<(HeaderName, HeaderValue)>,
6132 proxies: Proxies,
6133}
6134
6135/// Makes each refusal of [`Fetcher::new`] that reads no file, in its order,
6136/// and gives the mirrors, the headers, and the proxies of `options`.
6137fn checked(options: &FetcherOptions) -> Result<Checked> {
6138 // A limit of zero or a time of zero measures nothing. No rate is under
6139 // a zero limit, and each transfer fails a zero time immediately.
6140 if let Some(low) = options.low_speed
6141 && (low.limit == 0 || low.time.is_zero())
6142 {
6143 return Err(Error::Fetch(format!(
6144 "low-speed limit {} bytes per second over {:?}: neither may be zero",
6145 low.limit, low.time
6146 )));
6147 }
6148 let mirrors = options
6149 .mirrors
6150 .iter()
6151 .map(|url| parse_mirror(url))
6152 .collect::<Result<Vec<_>>>()?;
6153 // The fetcher sends a credential with each request to each mirror. So
6154 // one cleartext entry in the list puts the credential on the wire in
6155 // the clear, and the fetcher refuses such a configuration, unless the
6156 // caller permits it. A fetch that withholds the credential gets a 401
6157 // that does not state why.
6158 let cleartext = if options.allow_cleartext_credentials {
6159 None
6160 } else {
6161 options
6162 .mirrors
6163 .iter()
6164 .zip(&mirrors)
6165 .find(|(_, mirror)| !mirror.origin.tls)
6166 .map(|(url, _)| url.as_str())
6167 };
6168 let credential = match (&options.basic_auth, &options.bearer_token) {
6169 (Some(_), Some(_)) => return Err(Error::Fetch(BASIC_AND_BEARER.into())),
6170 (Some(_), None) => Some("basic-auth credentials"),
6171 (None, Some(_)) => Some("the bearer token"),
6172 (None, None) if options.signer.is_some() => Some("the signature of the request signer"),
6173 (None, None) => None,
6174 };
6175 if options.signer.is_some() {
6176 refuse_beside_signer(
6177 &options.headers,
6178 options.basic_auth.is_some(),
6179 options.bearer_token.is_some(),
6180 )?;
6181 }
6182 if let Some(credential) = credential
6183 && let Some(url) = cleartext
6184 {
6185 return Err(Error::Fetch(format!(
6186 "{credential} would reach the http mirror {url} in the clear: \
6187 use https mirrors, drop the credentials, or set \
6188 FetcherOptions::allow_cleartext_credentials"
6189 )));
6190 }
6191 let mut headers = vec![
6192 (
6193 hyper::header::USER_AGENT,
6194 HeaderValue::from_static(USER_AGENT),
6195 ),
6196 (
6197 hyper::header::ACCEPT_ENCODING,
6198 HeaderValue::from_static(IDENTITY),
6199 ),
6200 ];
6201 // The length of the part of the list that the fetcher sets. A
6202 // configured header of one of those names replaces that entry, as a
6203 // request header replaces a fetcher header of the same name. Without
6204 // this rule, both go on the wire and give one question two answers.
6205 // After this part, the list holds configured headers, and two entries
6206 // of one name both go on the wire.
6207 let mut base = headers.len();
6208 for (name, value) in &options.headers {
6209 let name = HeaderName::try_from(name.as_str())
6210 .map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
6211 if name == hyper::header::HOST {
6212 return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
6213 }
6214 if is_connection_header(&name) {
6215 return Err(connection_header_refused(&name));
6216 }
6217 if name == hyper::header::AUTHORIZATION && options.basic_auth.is_some() {
6218 return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
6219 }
6220 if name == hyper::header::AUTHORIZATION && options.bearer_token.is_some() {
6221 return Err(Error::Fetch(AMBIGUOUS_BEARER.into()));
6222 }
6223 if is_credential(&name)
6224 && let Some(url) = cleartext
6225 {
6226 return Err(Error::Fetch(format!(
6227 "the {name} header carries credentials, which the http mirror {url} \
6228 would receive in the clear: use https mirrors, drop the header, or set \
6229 FetcherOptions::allow_cleartext_credentials"
6230 )));
6231 }
6232 let mut value = HeaderValue::try_from(value.as_str())
6233 .map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
6234 value.set_sensitive(is_credential(&name));
6235 if let Some(at) = headers[..base].iter().position(|(held, _)| *held == name) {
6236 headers.remove(at);
6237 base -= 1;
6238 }
6239 headers.push((name, value));
6240 }
6241 if let Some(auth) = &options.basic_auth {
6242 headers.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
6243 }
6244 if let Some(token) = &options.bearer_token {
6245 headers.push((hyper::header::AUTHORIZATION, bearer_value(token)?));
6246 }
6247 let proxies = resolve_proxy(&options.proxy)?;
6248 Ok(Checked {
6249 mirrors,
6250 headers,
6251 proxies,
6252 })
6253}
6254
6255/// Makes each refusal of [`Fetcher::new`] that reads no file, in the order of
6256/// [`Fetcher::new`], with the same errors.
6257///
6258/// The check reads the low-speed rule, the mirrors, the credentials, the
6259/// headers, and the proxy of `options`. For [`Proxy::Environment`], it reads
6260/// the proxy variables of the process environment. It reads no file and no
6261/// trust store, parses no TLS material, builds no client, resolves no name,
6262/// and opens no connection. A caller can check the options of a fetcher with
6263/// it before it reads the files that complete the options, for example a
6264/// token file or a PEM file.
6265///
6266/// [`Fetcher::new`] makes these refusals first, and then the refusals of the
6267/// TLS setup. So a success of this check does not show that [`Fetcher::new`]
6268/// succeeds.
6269///
6270/// # Errors
6271///
6272/// - [`Error::Fetch`] if a [`low_speed`](FetcherOptions::low_speed) rule
6273/// holds a zero.
6274/// - [`Error::Fetch`] if a mirror URL is not a valid absolute URL, has no
6275/// usable host, or holds a query string or userinfo.
6276/// - [`Error::Fetch`] if a mirror URL names a port that is not a number
6277/// from 0 to 65535.
6278/// - [`Error::Unsupported`] if the scheme of a mirror URL is neither `http`
6279/// nor `https`.
6280/// - [`Error::Fetch`] if a header name or value is invalid, or if a header
6281/// is `Host` or a header that the connection layer sets.
6282/// - [`Error::Fetch`] if a mirror is cleartext `http`, the options hold a
6283/// credential, and
6284/// [`allow_cleartext_credentials`](FetcherOptions::allow_cleartext_credentials)
6285/// is `false`. [`Fetcher::new`] lists the credentials.
6286/// - [`Error::Fetch`] if two of these are set:
6287/// [`basic_auth`](FetcherOptions::basic_auth),
6288/// [`bearer_token`](FetcherOptions::bearer_token),
6289/// [`signer`](FetcherOptions::signer), and an `Authorization` header.
6290/// - [`Error::Fetch`] if [`basic_auth`](FetcherOptions::basic_auth) does
6291/// not give a valid header value, or if
6292/// [`bearer_token`](FetcherOptions::bearer_token) does not have the
6293/// token68 syntax.
6294/// - [`Error::Unsupported`] if a proxy URL is not `http://host[:port]`,
6295/// `socks5://host[:port]`, or `socks5h://host[:port]`, from the options
6296/// or from the environment.
6297/// - [`Error::Unsupported`] if a SOCKS5 URL has a userinfo that
6298/// [SOCKS proxies](Proxy#socks-proxies) refuses, or if an `http://` proxy
6299/// URL has a userinfo that the fetcher cannot send.
6300/// - [`Error::Unsupported`] if a proxy variable has
6301/// [white space](Proxy#white-space) around its value.
6302///
6303/// # Examples
6304///
6305/// ```
6306/// use ostrya_fetch::{Error, FetcherOptions, Proxy, check_options};
6307///
6308/// let mut options = FetcherOptions::new("https://example.com/repo");
6309/// options.proxy = Proxy::Url("http://proxy.example.com:3128".into());
6310/// check_options(&options).unwrap();
6311/// options.proxy = Proxy::Url("ftp://proxy.example.com".into());
6312/// assert!(matches!(check_options(&options), Err(Error::Unsupported(_))));
6313/// options.headers = vec![("Host".into(), "other.example.com".into())];
6314/// assert!(matches!(check_options(&options), Err(Error::Fetch(_))));
6315/// ```
6316pub fn check_options(options: &FetcherOptions) -> Result<()> {
6317 checked(options).map(drop)
6318}
6319
6320/// Resolves the proxy configuration into the state that a fetch reads.
6321///
6322/// The function resolves each form once. So a fetch reads no environment and
6323/// parses no URL. A proxy URL that the fetcher cannot connect through fails
6324/// the constructor, from the options and from the environment. A value read
6325/// under a meaning of this crate sends the request to a place that the caller
6326/// did not name.
6327fn resolve_proxy(proxy: &Proxy) -> Result<Proxies> {
6328 match proxy {
6329 Proxy::None => Ok(Proxies::default()),
6330 Proxy::Environment => resolve_variables(&environment()),
6331 Proxy::Variables(variables) => resolve_variables(variables),
6332 Proxy::Url(url) => {
6333 let endpoint = Arc::new(parse_proxy(url)?);
6334 Ok(Proxies {
6335 http: Some(endpoint.clone()),
6336 https: Some(endpoint),
6337 exempt_all: false,
6338 exempt: Vec::new(),
6339 })
6340 }
6341 }
6342}
6343
6344/// Returns the proxy variables of the process environment.
6345///
6346/// An empty value counts as unset. So the function leaves it out, and
6347/// [`variable`] has one rule to apply.
6348fn environment() -> Vec<(String, String)> {
6349 PROXY_VARIABLES
6350 .iter()
6351 .filter_map(|name| {
6352 let value = std::env::var(name).ok()?;
6353 (!value.is_empty()).then(|| ((*name).to_owned(), value))
6354 })
6355 .collect()
6356}
6357
6358/// Resolves the variable forms of [`Proxy`] into the state that a fetch reads.
6359fn resolve_variables(variables: &[(String, String)]) -> Result<Proxies> {
6360 let all = variable(variables, "all_proxy", Some("ALL_PROXY"));
6361 let http = variable(variables, "http_proxy", None);
6362 let https = variable(variables, "https_proxy", Some("HTTPS_PROXY"));
6363 // The loop parses each variable that holds a value. The choice of the
6364 // proxy for each scheme comes after the loop, from the parsed values. So
6365 // the fetcher refuses a proxy URL that it cannot connect through, also if
6366 // no fetch reads it. An example is `all_proxy` beside both
6367 // scheme-specific variables.
6368 //
6369 // The loop parses one URL for both schemes once, and holds it as one
6370 // endpoint. So the pool key of a proxy connection is the same, whichever
6371 // variable named it.
6372 //
6373 // The loop refuses a value with white space at its start or end before
6374 // the parse, because the parse trims it. The rule is the same: the loop
6375 // checks each variable that it reads, also if no fetch uses it.
6376 // The message names the variable, and leaves out the value, which can hold
6377 // a password.
6378 let mut endpoints: Vec<(&str, Arc<ProxyEndpoint>)> = Vec::new();
6379 for (name, url) in [all, http, https].into_iter().flatten() {
6380 if url.trim() != url {
6381 return Err(Error::Unsupported(format!(
6382 "the proxy variable {name} has white space at the start or the end of \
6383 its value"
6384 )));
6385 }
6386 if !endpoints.iter().any(|(named, _)| *named == url) {
6387 endpoints.push((url, Arc::new(parse_proxy(url)?)));
6388 }
6389 }
6390 let parsed = |held: Option<(&str, &str)>| {
6391 held.and_then(|(_, url)| endpoints.iter().find(|(named, _)| *named == url))
6392 .map(|(_, endpoint)| endpoint.clone())
6393 };
6394 let (http, https) = (parsed(http.or(all)), parsed(https.or(all)));
6395 let mut exempt_all = false;
6396 let mut exempt = Vec::new();
6397 for entry in variable(variables, "no_proxy", Some("NO_PROXY"))
6398 .map(|(_, value)| value)
6399 .unwrap_or_default()
6400 .split(',')
6401 .map(str::trim)
6402 .filter(|entry| !entry.is_empty())
6403 {
6404 if entry == "*" {
6405 exempt_all = true;
6406 continue;
6407 }
6408 exempt.extend(parse_exemption(entry));
6409 }
6410 Ok(Proxies {
6411 http,
6412 https,
6413 exempt_all,
6414 exempt,
6415 })
6416}
6417
6418/// Returns the name and the value of one proxy variable.
6419///
6420/// The function reads the lower-case name first, then the upper-case name if
6421/// there is one. An empty value counts as unset. Of two entries of one name,
6422/// the function reads the first entry with a value.
6423fn variable<'a>(
6424 variables: &'a [(String, String)],
6425 lower: &str,
6426 upper: Option<&str>,
6427) -> Option<(&'a str, &'a str)> {
6428 let held = |name: &str| {
6429 variables
6430 .iter()
6431 .find(|(held, value)| held == name && !value.is_empty())
6432 .map(|(held, value)| (held.as_str(), value.as_str()))
6433 };
6434 held(lower).or_else(|| upper.and_then(held))
6435}
6436
6437/// Reads one `no_proxy` entry, or returns `None` if it names no host.
6438///
6439/// An IPv6 literal holds colons of its own. So the function reads a port from
6440/// the bracketed form and from an entry with one colon. An unbracketed entry
6441/// with more colons is an address, with no port.
6442///
6443/// A port text that is not a number from 0 to 65535 leaves the whole entry as
6444/// one host text. No origin host holds that text, so the entry exempts
6445/// nothing.
6446///
6447/// The function drops an entry with no host after it removes the leading `.`
6448/// and the port. `.` and `:8080` are the two forms of such an entry. An empty
6449/// host text is the suffix of each host, so it exempts every origin if it
6450/// stays.
6451fn parse_exemption(entry: &str) -> Option<Exemption> {
6452 let (host, port) = match entry
6453 .strip_prefix('[')
6454 .and_then(|rest| rest.split_once(']'))
6455 {
6456 Some((inside, rest)) => (inside, rest.strip_prefix(':')),
6457 None => match entry.split_once(':') {
6458 Some((host, port)) if !port.contains(':') => (host, Some(port)),
6459 _ => (entry, None),
6460 },
6461 };
6462 // One leading `.` states the suffix match that the comparison makes in
6463 // all cases. So the code removes it, and the two forms of one entry are
6464 // one entry. A second `.` is part of the host text of the entry, which no
6465 // origin host holds.
6466 let named = |host: &str| host.strip_prefix('.').unwrap_or(host).to_ascii_lowercase();
6467 let (host, port) = match port.map(str::parse::<u16>) {
6468 Some(Ok(port)) => (named(host), Some(port)),
6469 Some(Err(_)) => (named(entry), None),
6470 None => (named(host), None),
6471 };
6472 (!host.is_empty()).then_some(Exemption { host, port })
6473}
6474
6475/// Reads a proxy URL into the endpoint of a connection.
6476///
6477/// The request to a proxy names the origin. So the URL names an endpoint and
6478/// nothing else. A path other than `/`, a query, or a fragment states a value
6479/// that the request has no place for, and the function refuses it. The
6480/// scheme is `http`, with the default port 80, or `socks5` or `socks5h`, with
6481/// the default port 1080. Under `socks5` the client resolves the origin host,
6482/// and under `socks5h` the proxy resolves it.
6483///
6484/// Userinfo is the credential of the proxy. For an `http` proxy, the function
6485/// percent-decodes it and sends it as `Proxy-Authorization: Basic`, as a proxy
6486/// that works with other clients expects. For a SOCKS5 proxy, it becomes the
6487/// user name and the password of RFC 1929. A userinfo holds a password, so
6488/// each refusal names the URL with the userinfo left out.
6489fn parse_proxy(url: &str) -> Result<ProxyEndpoint> {
6490 let refused = |what: &str| {
6491 Error::Unsupported(format!(
6492 "proxy url {}: {what}",
6493 without_userinfo(url.trim())
6494 ))
6495 };
6496 let url = url.trim();
6497 let has_scheme = |scheme: &str| {
6498 url.get(..scheme.len())
6499 .is_some_and(|text| text.eq_ignore_ascii_case(scheme))
6500 };
6501 let (scheme, default_port, socks) = if has_scheme(PROXY_SCHEME) {
6502 (PROXY_SCHEME, 80, None)
6503 } else if has_scheme(SOCKS5_SCHEME) {
6504 (SOCKS5_SCHEME, 1080, Some(ResolveSide::Client))
6505 } else if has_scheme(SOCKS5H_SCHEME) {
6506 (SOCKS5H_SCHEME, 1080, Some(ResolveSide::Proxy))
6507 } else {
6508 return Err(refused(
6509 "a proxy is reached over http://host[:port], socks5://host[:port], or \
6510 socks5h://host[:port] alone",
6511 ));
6512 };
6513 if url.contains('#') {
6514 return Err(refused("a proxy url carries no fragment"));
6515 }
6516 let uri = Uri::try_from(url).map_err(|e| refused(&format!("invalid url: {e}")))?;
6517 // A `/` or a `?` in the userinfo moves a part of the password into the
6518 // path or the query. So these refusals do not show the path or the query.
6519 if uri.query().is_some() {
6520 return Err(refused("a proxy url carries no query string"));
6521 }
6522 if !matches!(uri.path(), "" | "/") {
6523 return Err(refused("a proxy url carries no path"));
6524 }
6525 // `Uri::host` holds an IPv6 literal in brackets. The brackets belong to
6526 // the authority. A connect resolves the bracketed form to nothing.
6527 let literal = uri.host().ok_or_else(|| refused("the url has no host"))?;
6528 let authority = uri
6529 .authority()
6530 .expect("a url holding a host holds an authority")
6531 .as_str();
6532 let userinfo = authority.rsplit_once('@').map(|(userinfo, _)| userinfo);
6533 let kind = if let Some(resolve) = socks {
6534 let credential = userinfo
6535 .map(socks::Credential::from_userinfo)
6536 .transpose()
6537 .map_err(|e| refused(&e.to_string()))?;
6538 ProxyKind::Socks(SocksProxy {
6539 resolve,
6540 credential,
6541 })
6542 } else {
6543 let credential = userinfo
6544 .map(|userinfo| {
6545 proxy_credential(userinfo).ok_or_else(|| {
6546 refused(
6547 "the userinfo is not a percent-encoded user name and password the proxy \
6548 can be sent",
6549 )
6550 })
6551 })
6552 .transpose()?;
6553 ProxyKind::Http { credential }
6554 };
6555 let host = literal
6556 .strip_prefix('[')
6557 .and_then(|inner| inner.strip_suffix(']'))
6558 .unwrap_or(literal)
6559 .to_ascii_lowercase();
6560 // `Uri` accepts an authority whose port it cannot read, and reports no
6561 // port for it. So the code reads the port text from the authority and
6562 // refuses it. The default port does not replace it.
6563 let port_text = authority
6564 .rsplit_once('@')
6565 .map_or(authority, |(_, host)| host)
6566 .strip_prefix(literal)
6567 .and_then(|rest| rest.strip_prefix(':'));
6568 let port = match (uri.port_u16(), port_text) {
6569 (Some(port), _) => port,
6570 (None, None) => default_port,
6571 (None, Some(text)) => {
6572 return Err(refused(&format!(
6573 "the port {text:?} is not a number from 0 to 65535"
6574 )));
6575 }
6576 };
6577 let named = if port == default_port {
6578 format!("{scheme}{literal}")
6579 } else {
6580 format!("{scheme}{literal}:{port}")
6581 };
6582 Ok(ProxyEndpoint {
6583 endpoint: Origin {
6584 tls: false,
6585 host,
6586 port,
6587 },
6588 kind,
6589 named,
6590 })
6591}
6592
6593/// Returns the `Proxy-Authorization` value of the userinfo of one proxy URL.
6594///
6595/// The function percent-decodes the two fields, because a URL states a `:` or
6596/// an `@` of a credential in that encoding. `None` states that the userinfo
6597/// holds something else: an escape that is not two hexadecimal digits, or a
6598/// field whose bytes are not text.
6599fn proxy_credential(userinfo: &str) -> Option<HeaderValue> {
6600 let (user, password) = userinfo.split_once(':').unwrap_or((userinfo, ""));
6601 let field = |text: &str| String::from_utf8(percent_decode(text)?).ok();
6602 basic_auth_value(&BasicAuth {
6603 user: field(user)?,
6604 password: field(password)?,
6605 })
6606 .ok()
6607}
6608
6609/// Percent-decodes one field of the userinfo of a proxy URL.
6610///
6611/// `%` starts an escape of exactly two hexadecimal digits. `None` states that
6612/// the field holds a different escape, which the fetcher refuses. The bytes as
6613/// written can give the proxy a credential other than the one that the caller
6614/// meant. The 407 answer to that credential names nothing.
6615fn percent_decode(field: &str) -> Option<Vec<u8>> {
6616 let bytes = field.as_bytes();
6617 let mut decoded = Vec::with_capacity(bytes.len());
6618 let mut at = 0;
6619 while at < bytes.len() {
6620 if bytes[at] != b'%' {
6621 decoded.push(bytes[at]);
6622 at += 1;
6623 continue;
6624 }
6625 let escape = bytes.get(at + 1..at + 3)?;
6626 if !escape.iter().all(u8::is_ascii_hexdigit) {
6627 return None;
6628 }
6629 let text = std::str::from_utf8(escape).ok()?;
6630 decoded.push(u8::from_str_radix(text, 16).ok()?);
6631 at += 3;
6632 }
6633 Some(decoded)
6634}
6635
6636/// Returns the `host:port` that names the target of a `CONNECT`, and the
6637/// origin in a message of a SOCKS5 hop.
6638///
6639/// The port is always written, whatever the default of the scheme. The proxy
6640/// opens a TCP connection, which names a port and reads no scheme. An IPv6
6641/// literal keeps the brackets that separate the address from the port.
6642fn connect_authority(origin: &Origin) -> String {
6643 if origin.host.contains(':') {
6644 format!("[{}]:{}", origin.host, origin.port)
6645 } else {
6646 format!("{}:{}", origin.host, origin.port)
6647 }
6648}
6649
6650/// Returns the failure of a SOCKS5 exchange that asks `proxy` to connect to
6651/// `origin`.
6652///
6653/// The error names the proxy and the origin, and keeps the class of the
6654/// SOCKS5 failure.
6655fn socks_failure(proxy: &ProxyEndpoint, origin: &Origin, e: socks::SocksError) -> Failure {
6656 let error = Error::Fetch(format!(
6657 "connect to {} through the proxy {} failed: {}",
6658 connect_authority(origin),
6659 proxy.named,
6660 e.reason
6661 ));
6662 match e.class {
6663 socks::Class::Definitive => Failure::Fatal(error),
6664 socks::Class::Retryable => Failure::Retry(error),
6665 }
6666}
6667
6668/// Opens a TCP connection to `proxy`.
6669///
6670/// A failure is retryable and names the proxy.
6671async fn connect_proxy(proxy: &ProxyEndpoint) -> std::result::Result<rt::TcpStream, Failure> {
6672 rt::TcpStream::connect(&proxy.endpoint.host, proxy.endpoint.port)
6673 .await
6674 .map_err(|e| {
6675 Failure::Retry(Error::Fetch(format!(
6676 "connect to the proxy {} failed: {e}",
6677 proxy.named
6678 )))
6679 })
6680}
6681
6682/// Opens a connection through the SOCKS5 `proxy` to `origin`, and returns
6683/// the stream after the handshake.
6684///
6685/// The function checks the host name before the resolve and before the
6686/// connect to the proxy, under each resolve side. So a name that SOCKS5
6687/// cannot send fails as definitive with no resolver and no reachable proxy.
6688///
6689/// If the client resolves the name, the function gives the addresses of
6690/// [`rt::resolve`] to [`socks_each`]. A failed resolve is retryable and names
6691/// the origin host. Each other case uses one connection to the proxy and one
6692/// handshake: the proxy resolves the name, or the origin host is an IP
6693/// address.
6694async fn socks_connect(
6695 proxy: &ProxyEndpoint,
6696 socks: &SocksProxy,
6697 origin: &Origin,
6698) -> std::result::Result<rt::TcpStream, Failure> {
6699 let target = socks::Target::new(&origin.host, origin.port);
6700 target
6701 .check()
6702 .map_err(|e| socks_failure(proxy, origin, e))?;
6703 if let (socks::Host::Name(name), ResolveSide::Client) = (&target.host, socks.resolve) {
6704 let addrs = rt::resolve(name, origin.port).await.map_err(|e| {
6705 Failure::Retry(Error::Fetch(format!(
6706 "connect to {} through the proxy {} failed: cannot resolve {name}: {e}",
6707 connect_authority(origin),
6708 proxy.named
6709 )))
6710 })?;
6711 return socks_each(proxy, socks, origin, &addrs).await;
6712 }
6713 let mut tcp = connect_proxy(proxy).await?;
6714 socks::handshake(&mut tcp, &target, socks.credential.as_ref())
6715 .await
6716 .map_err(|e| socks_failure(proxy, origin, e))?;
6717 Ok(tcp)
6718}
6719
6720/// Asks the SOCKS5 `proxy` to connect to each address of `addrs` in turn, and
6721/// returns the stream of the first address that the proxy connects.
6722///
6723/// A refused `CONNECT` ends the connection to the proxy, so each address gets
6724/// a new connection. A definitive failure ends the loop, because each later
6725/// address gets the same answer. A failed connect to the proxy also ends the
6726/// loop. If the proxy refuses each address, the retryable failure names the
6727/// last address, the number of addresses, and the last reason.
6728///
6729/// `addrs` is not empty. The one caller gives the output of [`rt::resolve`],
6730/// which gives an error in place of an empty list.
6731async fn socks_each(
6732 proxy: &ProxyEndpoint,
6733 socks: &SocksProxy,
6734 origin: &Origin,
6735 addrs: &[SocketAddr],
6736) -> std::result::Result<rt::TcpStream, Failure> {
6737 let mut last = None;
6738 for addr in addrs {
6739 let mut tcp = connect_proxy(proxy).await?;
6740 let target = socks::Target {
6741 host: socks::Host::Ip(addr.ip()),
6742 port: addr.port(),
6743 };
6744 match socks::handshake(&mut tcp, &target, socks.credential.as_ref()).await {
6745 Ok(()) => return Ok(tcp),
6746 Err(e) if e.class == socks::Class::Definitive => {
6747 return Err(socks_failure(proxy, origin, e));
6748 }
6749 Err(e) => last = Some((addr, e)),
6750 }
6751 }
6752 let authority = connect_authority(origin);
6753 let (addr, e) = last.expect("the address list is never empty");
6754 let count = match addrs.len() {
6755 1 => "1 address".to_owned(),
6756 n => format!("{n} addresses"),
6757 };
6758 Err(Failure::Retry(Error::Fetch(format!(
6759 "connect to {authority} through the proxy {} failed at {addr}, the last of {count}: {}",
6760 proxy.named, e.reason
6761 ))))
6762}
6763
6764/// Returns the `Authorization` value of basic credentials, marked sensitive.
6765fn basic_auth_value(auth: &BasicAuth) -> Result<HeaderValue> {
6766 let encoded =
6767 ostrya_core::base64::encode(format!("{}:{}", auth.user, auth.password).as_bytes());
6768 let mut value = HeaderValue::try_from(format!("Basic {encoded}"))
6769 .map_err(|_| Error::Fetch("invalid basic-auth credentials".into()))?;
6770 value.set_sensitive(true);
6771 Ok(value)
6772}
6773
6774/// Returns the `Authorization` value of a bearer token, marked sensitive.
6775///
6776/// The fetcher sends the token as written, so it must hold the token68 syntax
6777/// of the header. The token is a secret, so a refusal names no part of it.
6778fn bearer_value(token: &BearerToken) -> Result<HeaderValue> {
6779 let refused = || {
6780 Error::Fetch(
6781 "the bearer token is not token68: it holds letters, digits, -, ., _, ~, +, or /, \
6782 then any number of ="
6783 .into(),
6784 )
6785 };
6786 if !is_token68(&token.token) {
6787 return Err(refused());
6788 }
6789 let mut value =
6790 HeaderValue::try_from(format!("Bearer {}", token.token)).map_err(|_| refused())?;
6791 value.set_sensitive(true);
6792 Ok(value)
6793}
6794
6795/// Returns `true` if `token` holds the token68 syntax.
6796///
6797/// The syntax is one or more ASCII letters, digits, `-`, `.`, `_`, `~`, `+`,
6798/// or `/`, then any number of `=`.
6799fn is_token68(token: &str) -> bool {
6800 let body = token.trim_end_matches('=');
6801 !body.is_empty()
6802 && body
6803 .bytes()
6804 .all(|byte| byte.is_ascii_alphanumeric() || b"-._~+/".contains(&byte))
6805}
6806
6807/// Returns the origin of one absolute URL, and the authority of that origin.
6808///
6809/// The function checks the scheme before it parses the URL. So a URL that the
6810/// fetcher cannot serve gets a message that names the scheme. An example is a
6811/// `file://` URL, which is not a well-formed HTTP URL.
6812///
6813/// The function refuses userinfo. Credentials that never reach the wire get a
6814/// 401 answer, which points at nothing. `credentials` names the field that
6815/// carries them.
6816///
6817/// A userinfo holds a password. So the refusal names the scheme and the host.
6818/// A message about a URL before the parse reaches its authority names the URL
6819/// with the userinfo left out.
6820fn parse_authority(url: &str, credentials: &str) -> Result<(Uri, Origin, String)> {
6821 let scheme = url
6822 .split_once("://")
6823 .map(|(scheme, _)| scheme)
6824 .ok_or_else(|| {
6825 Error::Fetch(format!(
6826 "url {} is not an absolute http or https url",
6827 without_userinfo(url)
6828 ))
6829 })?;
6830 let tls = match scheme {
6831 _ if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
6832 _ if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
6833 other => {
6834 return Err(Error::Unsupported(format!(
6835 "fetch url scheme {other}: only http and https are fetched"
6836 )));
6837 }
6838 };
6839 let scheme = if tls { "https" } else { "http" };
6840 let uri = Uri::try_from(url)
6841 .map_err(|e| Error::Fetch(format!("invalid url {}: {e}", without_userinfo(url))))?;
6842 // `Uri::host` puts an IPv6 literal in brackets. The brackets belong to the
6843 // authority, and the `Host` header and the absolute URL carry them. A
6844 // connect resolves the bracketed form to nothing, and a TLS server name
6845 // cannot come from it.
6846 let literal = uri
6847 .host()
6848 .ok_or_else(|| Error::Fetch(format!("url {} has no host", without_userinfo(url))))?;
6849 if uri
6850 .authority()
6851 .is_some_and(|authority| authority.as_str().contains('@'))
6852 {
6853 return Err(Error::Fetch(format!(
6854 "the {scheme} url for {literal} carries userinfo, which the fetcher does not send: \
6855 pass credentials as {credentials}"
6856 )));
6857 }
6858 // A host is one origin in each case of its letters. So the pool key holds
6859 // it in lower case. A `Location` header repeats the case that the origin
6860 // server wrote. With two cases of one host in the pool, the fetcher opens
6861 // two connections and two HTTP/2 sessions to it.
6862 let host = literal
6863 .strip_prefix('[')
6864 .and_then(|inner| inner.strip_suffix(']'))
6865 .unwrap_or(literal)
6866 .to_ascii_lowercase();
6867 // `Uri` accepts an authority whose port it cannot read, and reports no
6868 // port for it. Examples are `h:99999`, `h:`, and `h:abc`. A fallback to the
6869 // default of the scheme serves the request from a port that the caller did
6870 // not name. The rebuilt authority also drops the port. So the code reads
6871 // the port text from the authority and refuses it.
6872 //
6873 // `Uri` also reads the port with the integer parse of `std`, which takes a
6874 // leading `+`. A port is ASCII digits alone, so the code refuses a port
6875 // text with any other byte. Leading zeros are digits, and `080` names the
6876 // port 80.
6877 let port_text = uri
6878 .authority()
6879 .and_then(|authority| authority.as_str().strip_prefix(literal))
6880 .and_then(|rest| rest.strip_prefix(':'));
6881 let default_port = if tls { 443 } else { 80 };
6882 let digits = port_text.is_none_or(|text| text.bytes().all(|b| b.is_ascii_digit()));
6883 let port = match (uri.port_u16().filter(|_| digits), port_text) {
6884 (Some(port), _) => port,
6885 (None, None) => default_port,
6886 (None, Some(text)) => {
6887 // A password with a `?` or a `#` ends the authority before the
6888 // `@`. So the userinfo check passes, and a URL with userinfo can
6889 // get this message.
6890 return Err(Error::Fetch(format!(
6891 "url {} names the port {text:?}, which is not a number from 0 to 65535",
6892 without_userinfo(url)
6893 )));
6894 }
6895 };
6896 let authority = if port == default_port {
6897 literal.to_string()
6898 } else {
6899 format!("{literal}:{port}")
6900 };
6901 Ok((uri, Origin { tls, host, port }, authority))
6902}
6903
6904/// Returns the form of a URL for a message, before the parse reaches the
6905/// authority and refuses the userinfo.
6906///
6907/// Userinfo holds a password, so the function leaves out the part of the
6908/// authority before the `@`. The password arrives as the caller wrote it. It
6909/// can hold a `/`, a `?`, or a `#`, which are the characters that end an
6910/// authority. So the end of the authority is known only after the userinfo is
6911/// found.
6912///
6913/// The function reads an `@` at any position after the scheme as the end of a
6914/// userinfo. It leaves out all text up to the last `@`, so no password of any
6915/// form reaches the message. When the text has no valid scheme before the
6916/// first `://`, the userinfo starts at the start of the text.
6917///
6918/// If a URL has an `@` in its path and no userinfo, the message loses its
6919/// host. A redaction that reads no well-formed authority has this cost.
6920fn without_userinfo(url: &str) -> Cow<'_, str> {
6921 let start = scheme_len(url);
6922 match url[start..].rfind('@') {
6923 Some(at) => Cow::Owned(format!("{}{}", &url[..start], &url[start + at + 1..])),
6924 None => Cow::Borrowed(url),
6925 }
6926}
6927
6928/// Returns the length of the `<scheme>://` prefix of `url`, or 0.
6929///
6930/// The prefix counts only when the text before the first `://` is a valid
6931/// scheme: an ASCII letter, then ASCII letters, digits, `+`, `-`, or `.`.
6932fn scheme_len(url: &str) -> usize {
6933 let Some(end) = url.find("://") else {
6934 return 0;
6935 };
6936 let mut chars = url[..end].chars();
6937 let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
6938 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
6939 if valid { end + 3 } else { 0 }
6940}
6941
6942/// Returns the `Host` header value of one authority.
6943fn host_header(url: &str, authority: &str) -> Result<HeaderValue> {
6944 HeaderValue::try_from(authority).map_err(|_| {
6945 Error::Fetch(format!(
6946 "url {} has an unusable host",
6947 without_userinfo(url)
6948 ))
6949 })
6950}
6951
6952/// Checks that `url` is a base URL that a fetcher takes as a mirror.
6953///
6954/// The check opens no connection and reads no file. It refuses these parts:
6955///
6956/// - a scheme other than `http` and `https`
6957/// - userinfo
6958/// - a query string
6959/// - a fragment
6960/// - an empty host
6961/// - a port that is not a number from 0 to 65535 in ASCII digits.
6962///
6963/// A port with leading zeros is the number that its digits give.
6964///
6965/// The check refuses an `@` at any position, also in the path and in the
6966/// query. The authority of a URL ends at the first `/`, `?`, or `#`. So a
6967/// password with one of those ends the authority before the `@`. The rest of
6968/// the userinfo then reads as a path or a query.
6969///
6970/// No refusal names the part of the URL before the last `@`.
6971///
6972/// # Errors
6973///
6974/// - [`Error::Fetch`] if `url` holds a `#` or an `@`.
6975/// - [`Error::Unsupported`] if the scheme is neither `http` nor `https`.
6976/// - [`Error::Fetch`] if `url` is not a valid absolute URL, or has no host.
6977/// - [`Error::Fetch`] if `url` holds a query string, or names a port that is
6978/// not valid.
6979/// - [`Error::Fetch`] if a `Host` header cannot hold the authority.
6980pub fn check_base_url(url: &str) -> Result<()> {
6981 if url.contains('#') {
6982 return Err(Error::Fetch(format!(
6983 "url {} carries a fragment, which no request sends",
6984 without_userinfo(url)
6985 )));
6986 }
6987 if url.contains('@') {
6988 return Err(Error::Fetch(format!(
6989 "url {} holds an '@', which can mark userinfo: a base url carries no userinfo, so \
6990 pass the credential in the options and not in the url",
6991 without_userinfo(url)
6992 )));
6993 }
6994 let mirror = parse_mirror(url)?;
6995 if mirror.origin.host.is_empty() {
6996 return Err(Error::Fetch(format!(
6997 "url {} has no host",
6998 without_userinfo(url)
6999 )));
7000 }
7001 Ok(())
7002}
7003
7004/// Parses one base URL into a [`Mirror`].
7005fn parse_mirror(url: &str) -> Result<Mirror> {
7006 let (uri, origin, authority) = parse_authority(url, "FetcherOptions::basic_auth")?;
7007 // A request target is the base path of the mirror with the object path
7008 // added. So a query string of the base URL drops out with no message. The
7009 // code refuses it. A presigned URL that lost its signature gets a 403
7010 // answer, which does not point at the URL that caused it.
7011 //
7012 // A password with a `?` ends the authority there, and the rest of the
7013 // userinfo reads as the query. So the message names the URL with the
7014 // userinfo left out, and does not quote the query.
7015 if uri.query().is_some() {
7016 return Err(Error::Fetch(format!(
7017 "mirror url {} carries a query string, which the fetcher does not send",
7018 without_userinfo(url)
7019 )));
7020 }
7021 let scheme = if origin.tls { "https" } else { "http" };
7022 Ok(Mirror {
7023 authority: host_header(url, &authority)?,
7024 prefix: format!("{scheme}://{authority}"),
7025 base: uri.path().trim_end_matches('/').to_string(),
7026 origin,
7027 })
7028}
7029
7030/// Parses the absolute URL of a request into its [`Destination`].
7031///
7032/// The query string is part of the name of the request, so it reaches the
7033/// wire as written. The function refuses a fragment. A fragment is never sent,
7034/// so a URL with one asks for a resource other than the resource that the
7035/// caller named.
7036fn parse_url(url: &str) -> Result<Destination> {
7037 if url.contains('#') {
7038 return Err(Error::Fetch(format!(
7039 "fetch url {} carries a fragment, which no request sends",
7040 without_userinfo(url)
7041 )));
7042 }
7043 let (uri, origin, authority) = parse_authority(url, "FetchRequest::basic_auth")?;
7044 let scheme = if origin.tls { "https" } else { "http" };
7045 let path_and_query = uri.path_and_query().map_or("/", |pq| pq.as_str());
7046 // The code builds the one string of the destination from the parts of the
7047 // parse. The whole string is the absolute URL. Its tail from the prefix
7048 // length is the origin-form target.
7049 let mut text =
7050 String::with_capacity(scheme.len() + 3 + authority.len() + 1 + path_and_query.len());
7051 text.push_str(scheme);
7052 text.push_str("://");
7053 text.push_str(&authority);
7054 let path_at = text.len();
7055 if !path_and_query.starts_with('/') {
7056 text.push('/');
7057 }
7058 text.push_str(path_and_query);
7059 Ok(Destination {
7060 authority: host_header(url, &authority)?,
7061 url: text,
7062 path_at,
7063 origin,
7064 })
7065}
7066
7067/// Returns `true` if `response` closes its HTTP/1.1 connection when it ends.
7068///
7069/// This is an HTTP/1.0 response, or a response whose `Connection` header holds
7070/// `close`.
7071fn closes(response: &Response<Incoming>) -> bool {
7072 response.version() != Version::HTTP_11
7073 || response
7074 .headers()
7075 .get_all(hyper::header::CONNECTION)
7076 .iter()
7077 .filter_map(|value| value.to_str().ok())
7078 .flat_map(|value| value.split(','))
7079 .any(|token| token.trim().eq_ignore_ascii_case("close"))
7080}
7081
7082/// Returns the `Content-Length` that a response declared, if it is usable.
7083fn content_length(headers: &hyper::HeaderMap) -> Option<u64> {
7084 headers
7085 .get(hyper::header::CONTENT_LENGTH)?
7086 .to_str()
7087 .ok()?
7088 .parse()
7089 .ok()
7090}
7091
7092/// Returns the coding that a response declared, if the body needs a decode.
7093///
7094/// `Content-Encoding` codes the content, and `Transfer-Encoding` codes the
7095/// message that carries the content. A body under either holds bytes other
7096/// than the bytes that the remote stores, so the function reads both headers.
7097/// If a response declares both, the function returns its content coding.
7098fn declared_coding(headers: &hyper::HeaderMap) -> Option<String> {
7099 coding(headers, hyper::header::CONTENT_ENCODING, &[IDENTITY]).or_else(|| {
7100 coding(
7101 headers,
7102 hyper::header::TRANSFER_ENCODING,
7103 &[IDENTITY, CHUNKED],
7104 )
7105 })
7106}
7107
7108/// Returns the coding that a response declared under `name`, if it is not in
7109/// `undone`.
7110///
7111/// `undone` holds the codings that leave the body as the remote wrote it. A
7112/// value is a comma-separated list of codings, and several headers of one name
7113/// state one list together. So the function reads each token of each value.
7114///
7115/// A value whose tokens are all empty names no coding. The function adds it
7116/// to no result, so a stray separator reaches no message. The result is the
7117/// text of the response, in its order, so the refusal names the value of the
7118/// server. A response with nothing to refuse builds no string.
7119fn coding(headers: &hyper::HeaderMap, name: HeaderName, undone: &[&str]) -> Option<String> {
7120 let declared = || {
7121 headers
7122 .get_all(&name)
7123 .iter()
7124 .map(|value| String::from_utf8_lossy(value.as_bytes()))
7125 .filter(|value| value.split(',').any(|token| !token.trim().is_empty()))
7126 };
7127 if !declared().any(|value| value.split(',').any(|token| names_a_coding(token, undone))) {
7128 return None;
7129 }
7130 Some(declared().collect::<Vec<_>>().join(", "))
7131}
7132
7133/// Returns `true` if one token of a coding list names a coding that is not in
7134/// `undone`.
7135///
7136/// The comparison ignores case and the space around the token. An empty token
7137/// names nothing.
7138fn names_a_coding(token: &str, undone: &[&str]) -> bool {
7139 let token = token.trim();
7140 !token.is_empty() && !undone.iter().any(|name| token.eq_ignore_ascii_case(name))
7141}
7142
7143/// Reads the cache validators of a response.
7144fn read_validators(headers: &hyper::HeaderMap) -> Validators {
7145 let text = |name: HeaderName| {
7146 headers
7147 .get(name)
7148 .and_then(|v| v.to_str().ok())
7149 .map(str::to_string)
7150 };
7151 Validators {
7152 etag: text(hyper::header::ETAG),
7153 last_modified: text(hyper::header::LAST_MODIFIED),
7154 }
7155}
7156
7157/// Returns `true` if a response with this status sends the attempt to another
7158/// URL.
7159fn is_redirect(status: StatusCode) -> bool {
7160 REDIRECTS.contains(&status)
7161}
7162
7163/// Returns the URL of a `Location` header, resolved against `from`, the URL of
7164/// the response that carried it.
7165///
7166/// A `Location` can be an absolute URL, a URL relative to the URL of the
7167/// response, or a scheme-relative URL. The resolution is the one that the URL
7168/// specification states. The function drops a fragment of the result. A
7169/// fragment names a part of a representation and reaches no request, and the
7170/// HTTP specification tells a redirect to drop it.
7171///
7172/// The resolution normalizes its result. A [`Target::Url`] reaches the wire as
7173/// the caller wrote it. The changes are:
7174///
7175/// - it resolves dot segments: `/deep/../root` becomes `/root`, and `/./p`
7176/// becomes `/p`
7177/// - it reads a backslash as a path separator: `/a\b` becomes `/a/b`
7178/// - it removes tabs and newlines
7179/// - it percent-encodes a character that a path or a query cannot carry:
7180/// `?q='x'` becomes `?q=%27x%27`
7181/// - it puts an IPv4 or an IPv6 host in canonical form: `2130706433` and
7182/// `0177.0.0.1` both become `127.0.0.1`.
7183///
7184/// If the signature of a signed request target covers one of those
7185/// characters, the target reaches the server in a new encoding. The server
7186/// reads it as a different target, and answers 403.
7187///
7188/// `None` states that the header holds no URL for a request. This covers a
7189/// value that is not text, an empty value, and a value that the resolution
7190/// cannot read. A value that resolves to the URL of the response itself, a
7191/// fragment alone such as `#frag`, is a hop of its own. It spends one of the
7192/// hops of the attempt.
7193fn resolve_location(from: &str, location: &HeaderValue) -> Option<String> {
7194 let location = location.to_str().ok()?;
7195 // An empty value resolves to the URL of the response that carried it. The
7196 // attempt then follows the hop that it just made, so the code returns
7197 // `None` for it.
7198 if location.is_empty() {
7199 return None;
7200 }
7201 let mut resolved = url::Url::parse(from).ok()?.join(location).ok()?;
7202 resolved.set_fragment(None);
7203 Some(resolved.into())
7204}
7205
7206/// Reads the URL that a redirect named into the destination of the next hop.
7207///
7208/// The function refuses two hops. Both refusals name the URL that redirected
7209/// and the URL that it named:
7210///
7211/// - a scheme other than `http` or `https`, under which the fetcher serves
7212/// nothing
7213/// - a hop from `https` to `http`, which puts a request that the caller made
7214/// over TLS on the wire in the clear.
7215///
7216/// The function follows a hop from `http` to `https`.
7217///
7218/// The input is the resolved URL, normalized by [`resolve_location`]. The
7219/// parse reads it as it reads a [`Target::Url`]. So that parse refuses
7220/// userinfo and a port that the URL parser cannot read, with its own message.
7221/// A userinfo holds a password, so the two refusals of this function name the
7222/// URL with the userinfo left out.
7223fn redirect_destination(from: &Destination, to: &str) -> Result<Destination> {
7224 let refused = |what: &str| {
7225 Error::Fetch(format!(
7226 "{} redirects to {}, {what}",
7227 from.url(),
7228 without_userinfo(to)
7229 ))
7230 };
7231 let tls = match to.split_once("://").map(|(scheme, _)| scheme) {
7232 Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
7233 Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
7234 _ => return Err(refused("which is not an absolute http or https url")),
7235 };
7236 if from.origin.tls && !tls {
7237 return Err(refused(
7238 "which is cleartext: a request made over tls is not followed onto http",
7239 ));
7240 }
7241 parse_url(to)
7242}
7243
7244/// Returns the error of a fetch of a TLS origin on a fetcher that holds no
7245/// trust anchors.
7246///
7247/// The route or a redirect hop can name the origin.
7248fn no_trust_anchors(origin: &str) -> Error {
7249 Error::Fetch(format!(
7250 "the certificate of the tls origin {origin} has nothing to verify against: the \
7251 fetcher holds no trust anchors, so set TlsOptions::roots"
7252 ))
7253}
7254
7255/// Classifies an unsuccessful status as retryable or definitive.
7256fn classify(status: StatusCode, url: &str) -> Failure {
7257 let error = Error::HttpStatus {
7258 status: status.as_u16(),
7259 url: url.to_string(),
7260 response: None,
7261 };
7262 if status.is_server_error()
7263 || status == StatusCode::REQUEST_TIMEOUT
7264 || status == StatusCode::TOO_MANY_REQUESTS
7265 {
7266 Failure::Retry(error)
7267 } else {
7268 Failure::Fatal(error)
7269 }
7270}
7271
7272/// Returns the error of a transport failure against one URL.
7273fn transport(url: &str, error: hyper::Error) -> Error {
7274 Error::Fetch(format!("{url}: {error}"))
7275}
7276
7277/// Returns the error of a response that did not deliver its head within the
7278/// progress window.
7279fn stalled(url: &str, limit: Duration) -> Error {
7280 Error::Fetch(format!("{url}: no response after {limit:?}"))
7281}
7282
7283/// Returns the error of a connect that did not complete within `limit`.
7284///
7285/// The window covers the connect to the endpoint of the hop. So the error of
7286/// a proxied hop names the proxy. The fetcher reaches the origin over that
7287/// connection, and nothing contacts the origin before the connection is open.
7288/// Under `socks5://`, the window also covers the resolve of the origin host
7289/// name, and the error still names the proxy.
7290fn connect_timed_out(origin: &Origin, via: Via<'_>, limit: Duration) -> Error {
7291 Error::Fetch(match via {
7292 Via::Direct => format!(
7293 "connect to {}:{} timed out after {limit:?}",
7294 origin.host, origin.port
7295 ),
7296 Via::Absolute(proxy) | Via::Tunnel(proxy) | Via::Socks(proxy, _) => format!(
7297 "connect to the proxy {} timed out after {limit:?}",
7298 proxy.named
7299 ),
7300 })
7301}
7302
7303/// Returns the error of an upload whose body failed before the hand-over. The
7304/// request was never sent.
7305fn not_sent(url: &str, reason: String) -> Error {
7306 Error::Fetch(format!("upload to {url} not sent: {reason}"))
7307}
7308
7309/// Returns the failure of an upload that failed after hyper took its request.
7310fn interrupted(url: &str, message: String) -> UploadFailure {
7311 UploadFailure::Sent {
7312 url: url.to_string(),
7313 message,
7314 }
7315}
7316
7317/// Returns the failure of an upload that does not deliver its response, for
7318/// `cause`.
7319///
7320/// hyper took the request, so the upload is interrupted. The message names
7321/// the cause.
7322fn undelivered(url: &str, cause: Error) -> UploadFailure {
7323 interrupted(url, cause.to_string())
7324}
7325
7326/// Appends `data` to `bytes` if the result holds at most `cap` bytes, and
7327/// returns `false` otherwise.
7328///
7329/// The capacity of `bytes` doubles as it grows, and never passes `cap`.
7330fn extend_capped(bytes: &mut Vec<u8>, data: &[u8], cap: u64) -> bool {
7331 let needed = bytes.len().saturating_add(data.len());
7332 if needed as u64 > cap {
7333 return false;
7334 }
7335 if needed > bytes.capacity() {
7336 let doubled = bytes.capacity().saturating_mul(2).max(needed);
7337 let grown = usize::try_from(cap).map_or(doubled, |cap| doubled.min(cap));
7338 bytes.reserve_exact(grown - bytes.len());
7339 }
7340 bytes.extend_from_slice(data);
7341 true
7342}
7343
7344/// Returns the message of an error and of its cause.
7345///
7346/// The message of a hyper error is generic, and its cause names what the
7347/// connection did.
7348fn with_cause(error: &dyn std::error::Error) -> String {
7349 match error.source() {
7350 Some(cause) => format!("{error}: {cause}"),
7351 None => error.to_string(),
7352 }
7353}
7354
7355/// Returns the error of a response that did not deliver its head within the
7356/// time of the low-speed rule.
7357fn too_slow(url: &str, rule: LowSpeed) -> Error {
7358 let LowSpeed { limit, time } = rule;
7359 Error::Fetch(format!(
7360 "{url}: transfer below {limit} bytes per second for {time:?}"
7361 ))
7362}
7363
7364/// Runs `future` under a deadline, and returns `None` if `limit` expires
7365/// first.
7366///
7367/// The function drops the future on expiry, which cancels its work.
7368async fn within<F: Future>(limit: Duration, future: F) -> Option<F::Output> {
7369 // The future is pinned before the race. So the block that awaits it holds
7370 // a pointer, and no second copy of it. A caller that fetches many objects
7371 // holds one such future for each object in flight, and its size is a cost
7372 // on the stack.
7373 let mut future = core::pin::pin!(future);
7374 futures_lite::future::or(async { Some(future.as_mut().await) }, async {
7375 rt::Timer::after(limit).await;
7376 None
7377 })
7378 .await
7379}
7380
7381/// Runs `future` under a deadline of `limit` that applies while `handed` is
7382/// `false`, and returns `None` if the deadline expires first.
7383///
7384/// The deadline runs from the call. An upload sets `handed` when hyper takes
7385/// the request. The request then has deadlines of its own, and the function
7386/// drops the timer. A request that comes back unsent clears `handed`, and the
7387/// function arms the timer again for the rest of the deadline.
7388async fn before_hand_over<F: Future>(
7389 limit: Duration,
7390 handed: &AtomicBool,
7391 future: F,
7392) -> Option<F::Output> {
7393 let mut future = core::pin::pin!(future);
7394 let end = Instant::now().checked_add(limit);
7395 let mut deadline: Option<rt::Deadline> = None;
7396 std::future::poll_fn(|cx| {
7397 if let Poll::Ready(output) = future.as_mut().poll(cx) {
7398 return Poll::Ready(Some(output));
7399 }
7400 if handed.load(Ordering::Relaxed) {
7401 deadline = None;
7402 return Poll::Pending;
7403 }
7404 // An end past the range of the clock is never reached. A timer of the
7405 // whole limit stands for it.
7406 let deadline = deadline.get_or_insert_with(|| {
7407 rt::Deadline::new(
7408 end.map_or(limit, |end| end.saturating_duration_since(Instant::now())),
7409 )
7410 });
7411 deadline.poll_expired(cx).map(|()| None)
7412 })
7413 .await
7414}
7415
7416/// Waits for the answer to a request that hyper took.
7417///
7418/// While a streamed body streams, nothing bounds the wait here, because the
7419/// stall window of the writer bounds the body. A body given whole has no
7420/// writer, so its stall window runs here. A frame that hyper does not take
7421/// within the window fails the body and ends the wait.
7422///
7423/// A body that fails ends the wait at once, also if hyper does not poll it
7424/// again. The window for the response head starts when hyper takes the end of
7425/// the body.
7426async fn answer<F: Future>(send: F, exchange: &Exchange, window: Duration) -> Answer<F::Output> {
7427 let mut send = core::pin::pin!(send);
7428 let mut head: Option<rt::Deadline> = None;
7429 let mut stall: Option<rt::Deadline> = None;
7430 std::future::poll_fn(|cx| {
7431 if let Poll::Ready(output) = send.as_mut().poll(cx) {
7432 return Poll::Ready(Answer::Sent(output));
7433 }
7434 while head.is_none() {
7435 match exchange.watch(cx) {
7436 Watch::Streaming(None) => return Poll::Pending,
7437 Watch::Streaming(Some(end)) => {
7438 if poll_until(&mut stall, cx, end).is_pending() {
7439 return Poll::Pending;
7440 }
7441 if let Ok(reason) = exchange.check_stall() {
7442 return Poll::Ready(Answer::Aborted(reason));
7443 }
7444 }
7445 Watch::Aborted(reason) => return Poll::Ready(Answer::Aborted(reason)),
7446 Watch::Ended => {
7447 stall = None;
7448 head = Some(rt::Deadline::new(window));
7449 }
7450 }
7451 }
7452 head.as_mut()
7453 .expect("the head window runs once the body has ended")
7454 .poll_expired(cx)
7455 .map(|()| Answer::Silent(window))
7456 })
7457 .await
7458}
7459
7460/// Returns the delay before retry round `round`: 250 ms, doubled for each
7461/// round, up to 2 seconds.
7462fn backoff(round: u32) -> Duration {
7463 let ms = 250u64 << (round - 1).min(3);
7464 Duration::from_millis(ms)
7465}
7466
7467// The fetcher, its bodies, and the parts of an upload move freely across tasks
7468// and threads.
7469const _: fn() = || {
7470 fn assert_send_sync<T: Send + Sync>() {}
7471 assert_send_sync::<Fetcher>();
7472 assert_send_sync::<Body>();
7473 assert_send_sync::<Fetched>();
7474 assert_send_sync::<BearerToken>();
7475 assert_send_sync::<UploadBody>();
7476 assert_send_sync::<UploadWriter>();
7477 assert_send_sync::<UploadRequest<'static>>();
7478 assert_send_sync::<Uploaded>();
7479 assert_send_sync::<ErrorResponse>();
7480};
7481
7482#[cfg(test)]
7483mod tests {
7484 use super::*;
7485
7486 /// The connection window holds one stream window for each request that
7487 /// the fetcher admits, and stops at the ceiling of the protocol.
7488 #[test]
7489 fn the_connection_window_covers_every_admitted_stream() {
7490 assert_eq!(h2_connection_window(1), H2_STREAM_WINDOW);
7491 assert_eq!(h2_connection_window(8), 8 * H2_STREAM_WINDOW);
7492 assert_eq!(h2_connection_window(usize::MAX), H2_MAX_WINDOW);
7493 }
7494
7495 #[test]
7496 fn mirror_urls_join_base_and_path() {
7497 let mirror = parse_mirror("https://example.com/repo/").unwrap();
7498 assert_eq!(
7499 mirror.destination("objects/ab/cd.filez", None).url(),
7500 "https://example.com/repo/objects/ab/cd.filez"
7501 );
7502 assert_eq!(mirror.origin.port, 443);
7503 assert!(mirror.origin.tls);
7504
7505 let root = parse_mirror("http://example.com").unwrap();
7506 assert_eq!(
7507 root.destination("summary", None).url(),
7508 "http://example.com/summary"
7509 );
7510 assert_eq!(root.origin.port, 80);
7511 assert!(!root.origin.tls);
7512
7513 // A non-default port stays in the URL and in the host header. A leading
7514 // slash on the path is not doubled.
7515 let ported = parse_mirror("http://127.0.0.1:8080/r").unwrap();
7516 let config = ported.destination("/config", None);
7517 assert_eq!(config.url(), "http://127.0.0.1:8080/r/config");
7518 assert_eq!(config.target(), "/r/config");
7519 assert_eq!(ported.authority, "127.0.0.1:8080");
7520 assert_eq!(root.authority, "example.com");
7521 }
7522
7523 /// A query string goes after the request path, as written, in the URL
7524 /// and in the origin-form target.
7525 #[test]
7526 fn mirror_urls_join_base_path_and_query() {
7527 let mirror = parse_mirror("http://127.0.0.1:8080/base/").unwrap();
7528 let destination = mirror.destination("_ostrya/refs/v1", Some("pattern=a%2Fb&pattern=c"));
7529 assert_eq!(
7530 destination.url(),
7531 "http://127.0.0.1:8080/base/_ostrya/refs/v1?pattern=a%2Fb&pattern=c"
7532 );
7533 assert_eq!(
7534 destination.target(),
7535 "/base/_ostrya/refs/v1?pattern=a%2Fb&pattern=c"
7536 );
7537 // An empty query keeps its `?`.
7538 let root = parse_mirror("https://example.com").unwrap();
7539 assert_eq!(
7540 root.destination("/p", Some("")).url(),
7541 "https://example.com/p?"
7542 );
7543 }
7544
7545 /// An IPv6 literal has brackets in the authority, and has none where the
7546 /// address itself is used. The brackets reach neither the connect nor the
7547 /// TLS server name, and both fail on them.
7548 #[test]
7549 fn an_ipv6_literal_keeps_its_brackets_only_in_the_authority() {
7550 let ported = parse_mirror("http://[::1]:8080/r").unwrap();
7551 assert_eq!(ported.origin.host, "::1");
7552 assert_eq!(ported.origin.port, 8080);
7553 assert_eq!(ported.authority, "[::1]:8080");
7554 assert_eq!(
7555 ported.destination("summary", None).url(),
7556 "http://[::1]:8080/r/summary"
7557 );
7558
7559 let tls = parse_mirror("https://[2001:db8::1]/repo").unwrap();
7560 assert_eq!(tls.origin.host, "2001:db8::1");
7561 assert_eq!(tls.origin.port, 443);
7562 assert_eq!(tls.authority, "[2001:db8::1]");
7563 assert_eq!(
7564 tls.destination("summary", None).url(),
7565 "https://[2001:db8::1]/repo/summary"
7566 );
7567 // The server name the TLS handshake is opened with comes from the same
7568 // field, and rejects the bracketed form.
7569 rustls::pki_types::ServerName::try_from(tls.origin.host.clone()).unwrap();
7570 }
7571
7572 #[test]
7573 fn mirror_urls_are_validated() {
7574 let err = parse_mirror("file:///srv/repo").unwrap_err();
7575 assert!(matches!(err, Error::Unsupported(_)), "{err}");
7576 let err = parse_mirror("/srv/repo").unwrap_err();
7577 assert!(err.to_string().contains("not an absolute"), "{err}");
7578 let err = parse_mirror("http://").unwrap_err();
7579 assert!(err.to_string().contains("invalid url"), "{err}");
7580
7581 // Neither a query nor userinfo reaches the wire. So the parse refuses
7582 // a URL with one, and does not serve it with the part missing.
7583 let err = parse_mirror("https://host/repo?X-Amz-Signature=deadbeef").unwrap_err();
7584 assert!(err.to_string().contains("query string"), "{err}");
7585 let err = parse_mirror("https://user:pass@host/repo").unwrap_err();
7586 assert!(err.to_string().contains("userinfo"), "{err}");
7587 // A bare user with no password is userinfo too.
7588 let err = parse_mirror("http://user@host/repo").unwrap_err();
7589 assert!(err.to_string().contains("userinfo"), "{err}");
7590 }
7591
7592 /// A base URL check takes each URL a mirror takes, and refuses a
7593 /// fragment and an empty host as well. A refusal holds no password.
7594 #[test]
7595 fn a_base_url_check_refuses_what_a_mirror_cannot_carry() {
7596 for url in [
7597 "http://host",
7598 "https://host/repo/",
7599 "http://127.0.0.1:8080/r",
7600 "https://[::1]:8443/",
7601 "HTTPS://host/repo",
7602 ] {
7603 check_base_url(url).unwrap();
7604 }
7605 let refused = |url: &str, part: &str| {
7606 let err = check_base_url(url).unwrap_err();
7607 let text = err.to_string();
7608 assert!(text.contains(part), "{url}: {text}");
7609 assert!(!text.contains("secret"), "{url}: {text}");
7610 };
7611 refused("https://user:secret@host/repo", "userinfo");
7612 refused("https://host/repo?q=1", "query string");
7613 refused("https://host/repo#part", "fragment");
7614 refused("https://u:secret@host/repo#part", "fragment");
7615 refused("http://", "invalid url");
7616 refused("http:///repo", "invalid url");
7617 refused("http://:80/repo", "has no host");
7618 refused("http://host:99999/repo", "not a number");
7619 refused("http://host:x/repo", "not a number");
7620 refused("ftp://host/repo", "scheme ftp");
7621 refused("host/repo", "not an absolute");
7622 // A password that holds a `/` or a `?` ends the authority before the
7623 // `@`. So the rest of the userinfo reads as the path or the query.
7624 refused("https://user:443/pw-secret@host/repo", "userinfo");
7625 refused("https://user:1234?pw-secret@host/", "userinfo");
7626 refused("https://host/repo@v1", "userinfo");
7627 // A port is ASCII digits alone. Leading zeros are digits.
7628 refused("http://h:+80/", "not a number");
7629 refused("http://h:-80/", "not a number");
7630 check_base_url("http://h:080/").unwrap();
7631 assert_eq!(parse_mirror("http://h:080/r").unwrap().prefix, "http://h");
7632 assert_eq!(
7633 parse_mirror("http://h:0808/r").unwrap().prefix,
7634 "http://h:808"
7635 );
7636 }
7637
7638 /// No refusal of a mirror URL names the userinfo that a password holding
7639 /// a `?` hides in the query.
7640 #[test]
7641 fn a_mirror_refusal_names_no_userinfo() {
7642 let err = parse_mirror("https://user:1234?pw-secret@host/").unwrap_err();
7643 let text = err.to_string();
7644 assert!(text.contains("query string"), "{text}");
7645 assert!(!text.contains("secret"), "{text}");
7646 let err = parse_mirror("http://h:+80/x").unwrap_err();
7647 assert!(err.to_string().contains("not a number"), "{err}");
7648 }
7649
7650 #[test]
7651 fn options_are_validated_at_construction() {
7652 rt::block_on(async {
7653 let mut options = direct_options("http://example.com");
7654 options.headers = vec![("not a header".into(), "v".into())];
7655 let err = Fetcher::new(options).await.unwrap_err();
7656 assert!(err.to_string().contains("invalid header name"), "{err}");
7657
7658 // The host header comes from the url of the request, so a host
7659 // header from the caller collides with it.
7660 let mut options = direct_options("http://example.com");
7661 options.headers = vec![("host".into(), "elsewhere".into())];
7662 let err = Fetcher::new(options).await.unwrap_err();
7663 assert!(err.to_string().contains("host header"), "{err}");
7664
7665 // Credentials and an authorization header both set the same
7666 // header, and which of the two to send is not stated.
7667 let mut options = tls_options("https://example.com");
7668 options.headers = vec![("authorization".into(), "Basic aaa".into())];
7669 options.basic_auth = Some(BasicAuth {
7670 user: "u".into(),
7671 password: "p".into(),
7672 });
7673 let err = Fetcher::new(options).await.unwrap_err();
7674 assert!(err.to_string().contains("pass one of them"), "{err}");
7675
7676 // A low-speed rule with a zero measures nothing. The constructor
7677 // refuses it, and does not read it as no rule.
7678 for low_speed in [
7679 LowSpeed {
7680 limit: 0,
7681 time: Duration::from_secs(30),
7682 },
7683 LowSpeed {
7684 limit: 1000,
7685 time: Duration::ZERO,
7686 },
7687 ] {
7688 let mut options = direct_options("http://example.com");
7689 options.low_speed = Some(low_speed);
7690 let err = Fetcher::new(options).await.unwrap_err();
7691 assert!(err.to_string().contains("neither may be zero"), "{err}");
7692 }
7693 });
7694 }
7695
7696 /// A low-speed time is rounded up to whole seconds, and saturates at the
7697 /// maximum with no wrap.
7698 #[test]
7699 fn a_low_speed_time_rounds_up_to_whole_seconds() {
7700 let rule = |time| LowSpeed { limit: 1000, time };
7701 let secs = Duration::from_secs;
7702 assert_eq!(rule(secs(30)).whole_seconds(), secs(30));
7703 assert_eq!(rule(Duration::from_millis(200)).whole_seconds(), secs(1));
7704 assert_eq!(rule(Duration::from_millis(1500)).whole_seconds(), secs(2));
7705 assert_eq!(rule(Duration::MAX).whole_seconds(), secs(u64::MAX));
7706 }
7707
7708 /// The second at which the low-speed rule fails a body that delivers
7709 /// `bursts`. Each burst is a byte count at a whole second after the first
7710 /// read. `None` states that the rule does not fail the body within
7711 /// `seconds`.
7712 fn low_speed_failure(time: u64, bursts: &[(u64, u64)], seconds: u64) -> Option<u64> {
7713 let mut monitor = Monitor::new(LowSpeed {
7714 limit: 1000,
7715 time: Duration::from_secs(time),
7716 });
7717 (1..=seconds).find(|&second| {
7718 let arrived: u64 = bursts
7719 .iter()
7720 .filter(|(at, _)| *at == second - 1)
7721 .map(|(_, bytes)| bytes)
7722 .sum();
7723 monitor.counted += arrived;
7724 monitor.sample()
7725 })
7726 }
7727
7728 /// The low-speed rule fails a body at the second at which the `ostree`
7729 /// command fails the same transfer. The limit is 1000 bytes per second,
7730 /// and the time is 2 seconds.
7731 #[test]
7732 fn the_low_speed_rule_fails_where_the_tool_fails() {
7733 rt::block_on(async {
7734 // Nothing arrives: the rate is below the limit from the start.
7735 assert_eq!(low_speed_failure(2, &[], 20), Some(2));
7736 assert_eq!(low_speed_failure(3, &[], 20), Some(3));
7737 // One burst and then nothing. The rate falls below the limit when
7738 // the burst ages out of the five-second span. It also falls below
7739 // when the burst over the seconds so far is below the limit. A
7740 // sample of exactly the limit counts as below it.
7741 assert_eq!(low_speed_failure(2, &[(0, 1_000)], 20), Some(2));
7742 assert_eq!(low_speed_failure(2, &[(0, 3_000)], 20), Some(5));
7743 assert_eq!(low_speed_failure(2, &[(0, 5_000)], 20), Some(7));
7744 assert_eq!(low_speed_failure(2, &[(0, 20_000)], 20), Some(8));
7745 assert_eq!(low_speed_failure(2, &[(0, 8_000)], 20), Some(8));
7746 assert_eq!(low_speed_failure(2, &[(0, 3_500)], 20), Some(6));
7747 // A second burst that arrives before the rate stays below the
7748 // limit for 2 seconds starts the count again. The body ends with
7749 // the second burst.
7750 let second = |at| [(0, 6_000), (at, 6_000)];
7751 assert_eq!(low_speed_failure(2, &second(6), 7), None);
7752 assert_eq!(low_speed_failure(2, &second(7), 8), None);
7753 assert_eq!(low_speed_failure(2, &second(8), 9), Some(8));
7754 // Bursts whose average is above the limit pass, though some whole
7755 // seconds carry nothing.
7756 let bursts: Vec<(u64, u64)> = (0..20).step_by(2).map(|at| (at, 2_100)).collect();
7757 assert_eq!(low_speed_failure(1, &bursts, 20), None);
7758 });
7759 }
7760
7761 /// A fetcher with no mirror serves the URLs its requests name. A path
7762 /// target has nowhere to go there, and is refused before admission.
7763 #[test]
7764 fn a_path_target_needs_a_mirror() {
7765 rt::block_on(async {
7766 let fetcher = Fetcher::new(mirrorless_options()).await.unwrap();
7767 let err = fetcher.route(Target::Path("summary")).unwrap_err();
7768 assert!(err.to_string().contains("no mirror is configured"), "{err}");
7769 let route = fetcher
7770 .route(Target::Url("https://example.com/summary"))
7771 .unwrap();
7772 let Route::One(destination) = route else {
7773 panic!("a url target names one destination");
7774 };
7775 assert_eq!(destination.url(), "https://example.com/summary");
7776 });
7777 }
7778
7779 /// A request path is added to the base path as written. So a `?` or a `#`
7780 /// in it is a delimiter, and the target is not the target that the caller
7781 /// asked for.
7782 #[test]
7783 fn a_query_or_a_fragment_in_a_path_is_rejected() {
7784 for path in ["refs/heads/a?b=c", "refs/heads/a#frag"] {
7785 let Err(err) = check_path(path) else {
7786 panic!("{path} was accepted as a request path");
7787 };
7788 assert!(
7789 err.to_string().contains("no query and no fragment"),
7790 "{path}: {err}"
7791 );
7792 }
7793 check_path("refs/heads/a").unwrap();
7794 }
7795
7796 /// A path with a query goes to the mirrors. The path has the rules of a
7797 /// path target, and a `#` in the query is refused before admission.
7798 #[test]
7799 fn a_path_query_target_is_checked_and_goes_to_the_mirrors() {
7800 rt::block_on(async {
7801 let fetcher = Fetcher::new(direct_options("http://example.com/r"))
7802 .await
7803 .unwrap();
7804 let route = fetcher
7805 .route(Target::PathQuery {
7806 path: "_ostrya/refs/v1",
7807 query: "pattern=a",
7808 })
7809 .unwrap();
7810 let Route::Mirrors { path, query } = route else {
7811 panic!("a path query target goes to the mirrors");
7812 };
7813 assert_eq!((&*path, query), ("_ostrya/refs/v1", Some("pattern=a")));
7814
7815 let refused = [
7816 ("p?x", "q", "no query and no fragment"),
7817 ("p#x", "q", "no query and no fragment"),
7818 ("p", "q#x", "a query holds no fragment"),
7819 ];
7820 for (path, query, message) in refused {
7821 let err = fetcher
7822 .route(Target::PathQuery { path, query })
7823 .unwrap_err();
7824 assert!(matches!(err, Error::Fetch(_)), "{err:?}");
7825 assert!(err.to_string().contains(message), "{path}?{query}: {err}");
7826 }
7827
7828 let fetcher = Fetcher::new(mirrorless_options()).await.unwrap();
7829 let err = fetcher
7830 .route(Target::PathQuery {
7831 path: "p",
7832 query: "q",
7833 })
7834 .unwrap_err();
7835 assert!(
7836 err.to_string().contains("path p?q has nowhere to go"),
7837 "{err}"
7838 );
7839 });
7840 }
7841
7842 /// The request path is added to the base path of the mirror, and the
7843 /// target carries the origin form for HTTP/1.1.
7844 #[test]
7845 fn a_request_target_appends_the_path_to_the_base() {
7846 rt::block_on(async {
7847 let fetcher = Fetcher::new(direct_options("http://example.com/r"))
7848 .await
7849 .unwrap();
7850 let mirror = &fetcher.inner.mirrors[0];
7851 let destination = mirror.destination("refs/heads/a", None);
7852 let request = fetcher
7853 .build_request(
7854 &destination,
7855 &FetchRequest::path("refs/heads/a"),
7856 &fetcher.inner.headers,
7857 Protocol::Http11,
7858 Via::Direct,
7859 )
7860 .unwrap();
7861 assert_eq!(request.uri(), "/r/refs/heads/a");
7862 });
7863 }
7864
7865 /// A `Location` is resolved against the URL of the response that carried
7866 /// it. So it reads as an absolute URL, a relative URL, or a
7867 /// scheme-relative URL. A fragment names a part of a representation and
7868 /// reaches no request, so a redirect drops it.
7869 #[test]
7870 fn a_location_resolves_against_the_response_that_carried_it() {
7871 let resolved = |value: &str| {
7872 resolve_location(
7873 "https://example.com/repo/objects/summary?x=1",
7874 &HeaderValue::try_from(value).unwrap(),
7875 )
7876 };
7877 for (value, hop) in [
7878 // Absolute, at another origin and at another port.
7879 ("http://other.example/p", "http://other.example/p"),
7880 (
7881 "https://other.example:8443/p?q=2",
7882 "https://other.example:8443/p?q=2",
7883 ),
7884 // Relative: rooted at the origin, and a sibling of the path the
7885 // response was answered at.
7886 ("/other/path", "https://example.com/other/path"),
7887 ("sibling", "https://example.com/repo/objects/sibling"),
7888 // Scheme-relative, which takes the scheme of the response that
7889 // redirected.
7890 ("//host.example/path", "https://host.example/path"),
7891 // A fragment is dropped, and the resolution does not refuse it.
7892 ("/other/path#frag", "https://example.com/other/path"),
7893 ("http://other.example/p#frag", "http://other.example/p"),
7894 // A scheme under which the fetcher serves nothing resolves here.
7895 // The hop check refuses it.
7896 ("file:///srv/repo", "file:///srv/repo"),
7897 ] {
7898 assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
7899 }
7900
7901 // A value that the resolution cannot read holds no URL for a request.
7902 // An empty value holds none either, because it resolves to the URL of
7903 // the response itself.
7904 assert_eq!(resolved("http://"), None);
7905 assert_eq!(resolved(""), None);
7906
7907 // A fragment alone resolves to the URL of the response itself, which is
7908 // a hop of its own.
7909 assert_eq!(
7910 resolved("#frag").as_deref(),
7911 Some("https://example.com/repo/objects/summary?x=1")
7912 );
7913
7914 // The resolution normalizes its result. A dot segment is resolved
7915 // away, a backslash reads as a path separator, and a tab is removed. A
7916 // character that a query cannot carry is percent-encoded, and an IPv4
7917 // host is canonicalized.
7918 for (value, hop) in [
7919 ("/deep/../root", "https://example.com/root"),
7920 ("/./p", "https://example.com/p"),
7921 ("/a\\b", "https://example.com/a/b"),
7922 ("/pa\tth", "https://example.com/path"),
7923 ("/p?q='x'", "https://example.com/p?q=%27x%27"),
7924 ("http://2130706433/p", "http://127.0.0.1/p"),
7925 ] {
7926 assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
7927 }
7928 }
7929
7930 /// A hop is read as a URL target is. Two hops are refused with both URLs
7931 /// named: a scheme under which the fetcher serves nothing, and a hop from
7932 /// `https` to `http`. A hop from `http` to `https` is followed.
7933 #[test]
7934 fn a_redirect_hop_is_validated_against_the_url_that_redirected() {
7935 let secure = parse_url("https://example.com/repo/summary").unwrap();
7936 let cleartext = parse_url("http://example.com/repo/summary").unwrap();
7937
7938 // A hop at another origin, and one at the origin that redirected.
7939 let hop = redirect_destination(&secure, "https://other.example/p?q=1").unwrap();
7940 assert_eq!(hop.url(), "https://other.example/p?q=1");
7941 assert_eq!(hop.origin.host, "other.example");
7942 let hop = redirect_destination(&secure, "https://example.com/elsewhere").unwrap();
7943 assert_eq!(hop.origin, secure.origin);
7944 // A hop from cleartext to tls is followed, and so is one that stays
7945 // cleartext.
7946 let hop = redirect_destination(&cleartext, "https://example.com/elsewhere").unwrap();
7947 assert!(hop.origin.tls);
7948 redirect_destination(&cleartext, "http://other.example/p").unwrap();
7949
7950 // A hop from tls to cleartext is refused, and both URLs are named.
7951 let err = redirect_destination(&secure, "http://other.example/p").unwrap_err();
7952 let message = err.to_string();
7953 assert!(
7954 message.contains("https://example.com/repo/summary"),
7955 "{message}"
7956 );
7957 assert!(message.contains("http://other.example/p"), "{message}");
7958 assert!(message.contains("cleartext"), "{message}");
7959
7960 // A scheme under which the fetcher serves nothing, named in the same
7961 // way.
7962 let err = redirect_destination(&secure, "file:///srv/repo").unwrap_err();
7963 let message = err.to_string();
7964 assert!(
7965 message.contains("https://example.com/repo/summary"),
7966 "{message}"
7967 );
7968 assert!(message.contains("file:///srv/repo"), "{message}");
7969 assert!(
7970 message.contains("not an absolute http or https url"),
7971 "{message}"
7972 );
7973
7974 // Userinfo is refused, and the password reaches no message.
7975 let err =
7976 redirect_destination(&secure, "https://alice:sup3rs3cret@other.example/p").unwrap_err();
7977 let message = err.to_string();
7978 assert!(message.contains("userinfo"), "{message}");
7979 assert!(!message.contains("sup3rs3cret"), "{message}");
7980 }
7981
7982 /// The statuses that send a fetch to another URL. A fetch is a GET, so the
7983 /// statuses that differ on the method are one case.
7984 #[test]
7985 fn the_followed_statuses_are_the_five_redirects() {
7986 for status in [301u16, 302, 303, 307, 308] {
7987 assert!(
7988 is_redirect(StatusCode::from_u16(status).unwrap()),
7989 "{status}"
7990 );
7991 }
7992 for status in [200u16, 300, 304, 305, 306, 400, 404, 500] {
7993 assert!(
7994 !is_redirect(StatusCode::from_u16(status).unwrap()),
7995 "{status}"
7996 );
7997 }
7998 }
7999
8000 #[test]
8001 fn retryable_statuses_are_classified() {
8002 for status in [500u16, 502, 503, 408, 429] {
8003 let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
8004 assert!(matches!(failure, Failure::Retry(_)), "{status}");
8005 }
8006 for status in [400u16, 401, 403, 404, 410] {
8007 let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
8008 assert!(matches!(failure, Failure::Fatal(_)), "{status}");
8009 }
8010 }
8011
8012 #[test]
8013 fn backoff_doubles_and_stops_at_two_seconds() {
8014 assert_eq!(backoff(1), Duration::from_millis(250));
8015 assert_eq!(backoff(2), Duration::from_millis(500));
8016 assert_eq!(backoff(3), Duration::from_secs(1));
8017 assert_eq!(backoff(4), Duration::from_secs(2));
8018 assert_eq!(backoff(9), Duration::from_secs(2));
8019 }
8020
8021 #[test]
8022 fn basic_auth_and_extra_headers_reach_the_header_list() {
8023 let mut options = tls_options("https://example.com");
8024 options.basic_auth = Some(BasicAuth {
8025 user: "u".into(),
8026 password: "p".into(),
8027 });
8028 options.headers = vec![("x-trace".into(), "abc".into())];
8029 let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
8030 let headers = &fetcher.inner.headers;
8031 let value = |name: HeaderName| {
8032 headers
8033 .iter()
8034 .find(|(n, _)| *n == name)
8035 .map(|(_, v)| v.to_str().unwrap().to_string())
8036 };
8037 assert_eq!(
8038 value(hyper::header::USER_AGENT).as_deref(),
8039 Some(USER_AGENT)
8040 );
8041 assert_eq!(
8042 value(HeaderName::from_static("x-trace")).as_deref(),
8043 Some("abc")
8044 );
8045 // base64("u:p")
8046 assert_eq!(
8047 value(hyper::header::AUTHORIZATION).as_deref(),
8048 Some("Basic dTpw")
8049 );
8050 }
8051
8052 /// Options for a fetcher with no mirror, which serves the URLs its
8053 /// requests name. The anchors come from the fixture authority, so the
8054 /// constructor reads no host trust store, which an empty mirror list
8055 /// otherwise demands.
8056 fn mirrorless_options() -> FetcherOptions {
8057 FetcherOptions {
8058 mirrors: Vec::new(),
8059 ..tls_options("unused")
8060 }
8061 }
8062
8063 /// Options for a fetcher at `url` that reaches every origin directly.
8064 ///
8065 /// A test that is not about the proxy states this. So the proxy variables
8066 /// of the host that runs the suite have no effect. The default form reads
8067 /// them, and a fetcher built under one goes to a proxy that no test
8068 /// started.
8069 fn direct_options(url: impl Into<String>) -> FetcherOptions {
8070 FetcherOptions {
8071 proxy: Proxy::None,
8072 ..FetcherOptions::new(url)
8073 }
8074 }
8075
8076 /// Options for an `https` mirror whose anchors come from the fixture
8077 /// authority, so the constructor reads no host trust store.
8078 fn tls_options(url: &str) -> FetcherOptions {
8079 FetcherOptions {
8080 tls: TlsOptions {
8081 roots: TrustRoots::Pem(
8082 include_bytes!("../../../tests/fixtures/tls/ca.pem").to_vec(),
8083 ),
8084 ..TlsOptions::default()
8085 },
8086 ..direct_options(url)
8087 }
8088 }
8089
8090 /// A credential reaches every mirror, so one cleartext mirror is enough to
8091 /// refuse the configuration. Credentials named in `headers` are refused in
8092 /// the same way. Any other header is sent, whatever the scheme.
8093 #[test]
8094 fn credentials_alongside_a_cleartext_mirror_are_refused() {
8095 let auth = || {
8096 Some(BasicAuth {
8097 user: "u".into(),
8098 password: "p".into(),
8099 })
8100 };
8101
8102 // The message names the cleartext mirror, also if it is one entry among
8103 // https entries.
8104 for mirrors in [
8105 vec!["http://cleartext.example/repo".to_owned()],
8106 vec![
8107 "https://secure.example/repo".to_owned(),
8108 "http://cleartext.example/repo".to_owned(),
8109 ],
8110 ] {
8111 let options = FetcherOptions {
8112 mirrors,
8113 basic_auth: auth(),
8114 ..tls_options("unused")
8115 };
8116 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
8117 let message = err.to_string();
8118 assert!(message.contains("basic-auth credentials"), "{message}");
8119 assert!(
8120 message.contains("http://cleartext.example/repo"),
8121 "{message}"
8122 );
8123 }
8124
8125 // Each header name that carries a credential, refused in the same way.
8126 for name in ["authorization", "proxy-authorization", "cookie"] {
8127 let options = FetcherOptions {
8128 headers: vec![(name.to_owned(), "secret".to_owned())],
8129 ..direct_options("http://cleartext.example/repo")
8130 };
8131 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
8132 let message = err.to_string();
8133 assert!(message.contains(name), "{message}");
8134 assert!(message.contains("carries credentials"), "{message}");
8135 }
8136
8137 // A header that is not a credential reaches a cleartext mirror.
8138 let options = FetcherOptions {
8139 headers: vec![("x-trace".to_owned(), "abc".to_owned())],
8140 ..direct_options("http://cleartext.example/repo")
8141 };
8142 rt::block_on(Fetcher::new(options)).unwrap();
8143
8144 // With every mirror on https, both kinds are accepted.
8145 let options = FetcherOptions {
8146 mirrors: vec![
8147 "https://one.example/repo".to_owned(),
8148 "https://two.example/repo".to_owned(),
8149 ],
8150 basic_auth: auth(),
8151 headers: vec![("cookie".to_owned(), "session=1".to_owned())],
8152 ..tls_options("unused")
8153 };
8154 rt::block_on(Fetcher::new(options)).unwrap();
8155 }
8156
8157 /// A request URL is served as it is written. The query string is part of
8158 /// the name of the request, and reaches the wire. Userinfo and a fragment
8159 /// are never sent, so the parse refuses them. The absolute URL, the
8160 /// origin-form target, the authority, and the origin all come from the one
8161 /// string of the destination.
8162 #[test]
8163 fn url_targets_are_parsed_and_validated() {
8164 // Every row states the URL, then the absolute URL, the origin-form
8165 // target, the authority, and the origin the parse produces.
8166 let rows = [
8167 (
8168 "https://example.com/repo/summary?sig=a%2Fb&x=1",
8169 "https://example.com/repo/summary?sig=a%2Fb&x=1",
8170 "/repo/summary?sig=a%2Fb&x=1",
8171 "example.com",
8172 "https://example.com",
8173 ),
8174 // A URL with no path of its own asks for the root, with or without
8175 // the trailing slash.
8176 ("http://h", "http://h/", "/", "h", "http://h"),
8177 ("http://h/", "http://h/", "/", "h", "http://h"),
8178 // An empty query is part of what the request names.
8179 ("http://h/p?", "http://h/p?", "/p?", "h", "http://h"),
8180 (
8181 "http://h/p?a=%2F&b=1",
8182 "http://h/p?a=%2F&b=1",
8183 "/p?a=%2F&b=1",
8184 "h",
8185 "http://h",
8186 ),
8187 // The default port of the scheme is left out of the authority, also
8188 // if the URL wrote it. The scheme is held in lower case.
8189 ("https://h:443/p", "https://h/p", "/p", "h", "https://h"),
8190 ("HTTP://h/p", "http://h/p", "/p", "h", "http://h"),
8191 // An IPv6 literal keeps its brackets in the authority, and a
8192 // non-default port stays with it.
8193 (
8194 "http://[2001:db8::1]:8080/r/config",
8195 "http://[2001:db8::1]:8080/r/config",
8196 "/r/config",
8197 "[2001:db8::1]:8080",
8198 "http://[2001:db8::1]:8080",
8199 ),
8200 ];
8201 for (url, absolute, target, authority, origin) in rows {
8202 let dest = parse_url(url).unwrap();
8203 assert_eq!(dest.url(), absolute, "{url}");
8204 assert_eq!(dest.target(), target, "{url}");
8205 assert_eq!(dest.authority, authority, "{url}");
8206 assert_eq!(dest.origin_url(), origin, "{url}");
8207 }
8208
8209 let dest = parse_url("https://example.com/repo/summary?sig=a%2Fb&x=1").unwrap();
8210 assert_eq!(dest.origin.port, 443);
8211 assert!(dest.origin.tls);
8212 let root = parse_url("http://example.com").unwrap();
8213 assert_eq!(root.origin.port, 80);
8214 assert!(!root.origin.tls);
8215 // The address is held without the brackets of the authority.
8216 let ported = parse_url("http://[::1]:8080/r/config").unwrap();
8217 assert_eq!(ported.origin.host, "::1");
8218 assert_eq!(ported.origin.port, 8080);
8219
8220 // The refusal names the scheme and the host, and leaves the password
8221 // out of a message a caller logs.
8222 let err = parse_url("https://alice:sup3rs3cret@example.com/p").unwrap_err();
8223 let message = err.to_string();
8224 assert!(message.contains("userinfo"), "{message}");
8225 assert!(message.contains("https url for example.com"), "{message}");
8226 assert!(message.contains("FetchRequest::basic_auth"), "{message}");
8227 assert!(!message.contains("sup3rs3cret"), "{message}");
8228
8229 let err = parse_url("https://example.com/p#frag").unwrap_err();
8230 assert!(err.to_string().contains("fragment"), "{err}");
8231 let err = parse_url("file:///srv/repo").unwrap_err();
8232 assert!(matches!(err, Error::Unsupported(_)), "{err}");
8233 let err = parse_url("/srv/repo").unwrap_err();
8234 assert!(err.to_string().contains("not an absolute"), "{err}");
8235 }
8236
8237 /// Each message about a URL whose authority the parse did not read yet
8238 /// leaves out the userinfo.
8239 #[test]
8240 fn a_password_reaches_no_message() {
8241 for url in [
8242 "https://alice:sup3rs3cret@example.com/p",
8243 "https://alice:sup3rs3cret@example.com/p#frag",
8244 "http://alice:sup3rs3cret@example.com/ p",
8245 "http://alice:sup3rs3cret@",
8246 "alice:sup3rs3cret@example.com/p",
8247 ] {
8248 let err = parse_url(url).unwrap_err();
8249 let message = err.to_string();
8250 assert!(!message.contains("sup3rs3cret"), "{url}: {message}");
8251 }
8252
8253 // A password with a `/`, a `?`, or a `#` ends the authority before the
8254 // `@`. The userinfo is left out also in this case.
8255 for password in ["pa#ss", "pa?ss", "p/ss"] {
8256 let url = format!("https://alice:{password}@example.com/p");
8257 let message = parse_url(&url).unwrap_err().to_string();
8258 assert!(!message.contains(password), "{password}: {message}");
8259 }
8260 }
8261
8262 /// `Uri` accepts an authority whose port it cannot read, and reports no
8263 /// port for it. So the parse refuses a URL that names such a port, and does
8264 /// not serve it from the default of the scheme.
8265 #[test]
8266 fn a_port_the_url_parser_cannot_read_is_refused() {
8267 for (url, text) in [
8268 ("http://h:99999/x", "99999"),
8269 ("http://h:65536/x", "65536"),
8270 ("http://h:abc/x", "abc"),
8271 ("http://h:/x", ""),
8272 // The integer parse of `std` takes a leading `+`, and a port is
8273 // ASCII digits alone.
8274 ("http://h:+80/x", "+80"),
8275 ] {
8276 let err = parse_url(url).unwrap_err();
8277 let message = err.to_string();
8278 assert!(message.contains(url), "{url}: {message}");
8279 assert!(message.contains(text), "{url}: {message}");
8280 assert!(message.contains("not a number"), "{url}: {message}");
8281 // A mirror URL is read by the same parse.
8282 assert!(parse_mirror(url).is_err(), "{url}");
8283 }
8284
8285 // A URL with no port at all takes the scheme default, and a port the
8286 // parser reads is kept.
8287 let default = parse_url("http://h/x").unwrap();
8288 assert_eq!(default.origin.port, 80);
8289 assert_eq!(default.url(), "http://h/x");
8290 let ported = parse_url("http://h:8080/x").unwrap();
8291 assert_eq!(ported.origin.port, 8080);
8292 assert_eq!(ported.url(), "http://h:8080/x");
8293 // Leading zeros are digits: the port is the number they give.
8294 let zeros = parse_url("http://h:0080/x").unwrap();
8295 assert_eq!(zeros.origin.port, 80);
8296 assert_eq!(zeros.url(), "http://h/x");
8297 }
8298
8299 /// A host is one origin in each case of its letters, so two spellings of
8300 /// one origin are one pool key.
8301 #[test]
8302 fn a_host_in_another_case_is_one_origin() {
8303 let upper = parse_url("http://LOCALHOST:8080/x").unwrap();
8304 let lower = parse_url("http://localhost:8080/x").unwrap();
8305 assert_eq!(upper.origin, lower.origin);
8306 assert_eq!(upper.origin.host, "localhost");
8307 // The authority reaches the wire as the caller wrote it.
8308 assert_eq!(upper.authority, "LOCALHOST:8080");
8309 assert_eq!(upper.url(), "http://LOCALHOST:8080/x");
8310 }
8311
8312 /// The rendering of a struct with credentials leaves out the password.
8313 #[test]
8314 fn basic_auth_debug_holds_no_password() {
8315 let auth = BasicAuth {
8316 user: "alice".into(),
8317 password: "sup3rs3cret".into(),
8318 };
8319 let rendered = format!("{auth:?}");
8320 assert!(rendered.contains("alice"), "{rendered}");
8321 assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
8322
8323 let request = FetchRequest {
8324 basic_auth: Some(&auth),
8325 ..FetchRequest::path("summary")
8326 };
8327 let rendered = format!("{request:?}");
8328 assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
8329
8330 let options = FetcherOptions {
8331 basic_auth: Some(auth),
8332 ..direct_options("https://example.com")
8333 };
8334 let rendered = format!("{options:?}");
8335 assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
8336 }
8337
8338 /// The origin of one absolute URL, which is what a proxy decision reads.
8339 fn origin_of(url: &str) -> Origin {
8340 parse_url(url).unwrap().origin
8341 }
8342
8343 /// How a hop at `url` is reached: the proxy that it names, and the way,
8344 /// which is the absolute form, a tunnel, or a SOCKS5 connection.
8345 fn via_of(proxies: &Proxies, url: &str) -> Option<(String, &'static str)> {
8346 match proxies.via(&origin_of(url)) {
8347 Via::Direct => None,
8348 Via::Absolute(proxy) => Some((proxy.named.clone(), "absolute")),
8349 Via::Tunnel(proxy) => Some((proxy.named.clone(), "tunnel")),
8350 Via::Socks(proxy, _) => Some((proxy.named.clone(), "socks")),
8351 }
8352 }
8353
8354 /// The variable list one test states, as the options carry it.
8355 fn variables(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
8356 pairs
8357 .iter()
8358 .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
8359 .collect()
8360 }
8361
8362 /// A proxy URL names an endpoint and nothing else. A path, a query, a
8363 /// fragment, or a scheme other than `http` states a value that a proxy
8364 /// connection has no place for. The constructor refuses each of them.
8365 #[test]
8366 fn a_proxy_url_names_an_http_endpoint() {
8367 // Every row states the URL, then the endpoint host, the port, and how a
8368 // diagnostic names the proxy.
8369 for (url, host, port, named) in [
8370 (
8371 "http://proxy.example",
8372 "proxy.example",
8373 80,
8374 "http://proxy.example",
8375 ),
8376 (
8377 "http://proxy.example:3128",
8378 "proxy.example",
8379 3128,
8380 "http://proxy.example:3128",
8381 ),
8382 // A path of `/` alone is the root, which is no path at all.
8383 (
8384 "http://proxy.example/",
8385 "proxy.example",
8386 80,
8387 "http://proxy.example",
8388 ),
8389 (
8390 "HTTP://Proxy.Example:3128",
8391 "proxy.example",
8392 3128,
8393 "http://Proxy.Example:3128",
8394 ),
8395 // An environment variable can carry space around its value. The
8396 // endpoint is read without it.
8397 (
8398 " http://proxy.example:3128 ",
8399 "proxy.example",
8400 3128,
8401 "http://proxy.example:3128",
8402 ),
8403 // An IPv6 literal keeps its brackets in the authority, and is held
8404 // without them. The connect resolves the bracketed form to nothing.
8405 ("http://[::1]:3128", "::1", 3128, "http://[::1]:3128"),
8406 (
8407 "http://alice:s3cret@proxy.example:3128",
8408 "proxy.example",
8409 3128,
8410 "http://proxy.example:3128",
8411 ),
8412 ] {
8413 let proxy = parse_proxy(url).unwrap_or_else(|e| panic!("{url}: {e}"));
8414 assert_eq!(proxy.endpoint.host, host, "{url}");
8415 assert_eq!(proxy.endpoint.port, port, "{url}");
8416 assert!(!proxy.endpoint.tls, "{url}");
8417 assert_eq!(proxy.named, named, "{url}");
8418 }
8419
8420 // Userinfo is the credential of the proxy, after the percent-decode:
8421 // base64("alice:s3cret") and base64("al:ce:p@ss").
8422 let credential = |url: &str| {
8423 let ProxyKind::Http { credential } = parse_proxy(url).unwrap().kind else {
8424 panic!("{url} names an http proxy");
8425 };
8426 credential.map(|value| value.to_str().unwrap().to_owned())
8427 };
8428 assert_eq!(credential("http://proxy.example"), None);
8429 assert_eq!(
8430 credential("http://alice:s3cret@proxy.example").as_deref(),
8431 Some("Basic YWxpY2U6czNjcmV0")
8432 );
8433 assert_eq!(
8434 credential("http://al%3Ace:p%40ss@proxy.example").as_deref(),
8435 Some("Basic YWw6Y2U6cEBzcw==")
8436 );
8437 // A user with no password is userinfo too, and it is sent with the
8438 // empty password an `Authorization` value holds: base64("alice:").
8439 assert_eq!(
8440 credential("http://alice@proxy.example").as_deref(),
8441 Some("Basic YWxpY2U6")
8442 );
8443
8444 // Every row states a URL the fetcher cannot connect through and a word
8445 // its refusal carries.
8446 for (url, says) in [
8447 ("socks4://proxy.example:1080", "socks5h://host[:port] alone"),
8448 (
8449 "socks4a://proxy.example:1080",
8450 "socks5h://host[:port] alone",
8451 ),
8452 ("https://proxy.example:3128", "socks5h://host[:port] alone"),
8453 ("proxy.example:3128", "socks5h://host[:port] alone"),
8454 ("http://proxy.example/squid", "carries no path"),
8455 ("http://proxy.example/?upstream=1", "carries no query"),
8456 ("http://proxy.example/#frag", "carries no fragment"),
8457 ("http://", "invalid url"),
8458 ("http://proxy.example:99999", "not a number"),
8459 ("http://proxy.example:abc", "not a number"),
8460 ("http://alice:p%zz@proxy.example", "percent-encoded"),
8461 ("http://alice:p%4@proxy.example", "percent-encoded"),
8462 ] {
8463 let err = parse_proxy(url).unwrap_err();
8464 assert!(matches!(err, Error::Unsupported(_)), "{url}: {err}");
8465 let message = err.to_string();
8466 assert!(message.contains(says), "{url}: {message}");
8467 }
8468 }
8469
8470 /// A `socks5h` URL names a SOCKS5 endpoint, with the port 1080 by default.
8471 /// It takes the checks of an `http` URL, and its userinfo is the user name
8472 /// and the password of RFC 1929, each 1 to 255 bytes after the decode.
8473 #[test]
8474 fn a_socks5h_proxy_url_names_its_endpoint() {
8475 for (url, host, port, named) in [
8476 (
8477 "socks5h://proxy.example",
8478 "proxy.example",
8479 1080,
8480 "socks5h://proxy.example",
8481 ),
8482 (
8483 "socks5h://proxy.example:1080",
8484 "proxy.example",
8485 1080,
8486 "socks5h://proxy.example",
8487 ),
8488 (
8489 "SOCKS5H://Proxy.Example:9050",
8490 "proxy.example",
8491 9050,
8492 "socks5h://Proxy.Example:9050",
8493 ),
8494 ("socks5h://[::1]", "::1", 1080, "socks5h://[::1]"),
8495 (
8496 "socks5h://proxy.example/",
8497 "proxy.example",
8498 1080,
8499 "socks5h://proxy.example",
8500 ),
8501 (
8502 "socks5h://alice:s3cret@proxy.example",
8503 "proxy.example",
8504 1080,
8505 "socks5h://proxy.example",
8506 ),
8507 ] {
8508 let proxy = parse_proxy(url).unwrap_or_else(|e| panic!("{url}: {e}"));
8509 assert_eq!(proxy.endpoint.host, host, "{url}");
8510 assert_eq!(proxy.endpoint.port, port, "{url}");
8511 assert!(!proxy.endpoint.tls, "{url}");
8512 assert_eq!(proxy.named, named, "{url}");
8513 assert!(matches!(proxy.kind, ProxyKind::Socks(_)), "{url}");
8514 }
8515 let credential = |url: &str| match parse_proxy(url).unwrap().kind {
8516 ProxyKind::Socks(socks) => socks.credential.is_some(),
8517 ProxyKind::Http { .. } => panic!("{url} names a SOCKS5 proxy"),
8518 };
8519 assert!(!credential("socks5h://proxy.example"));
8520 assert!(credential("socks5h://alice:s3cret@proxy.example"));
8521
8522 // Every row states a URL that the fetcher refuses and a word of the
8523 // refusal. The message names the URL without its userinfo.
8524 let long = "a".repeat(256);
8525 for (url, says) in [
8526 ("socks5h://proxy.example/x".to_owned(), "carries no path"),
8527 (
8528 "socks5h://proxy.example/?a=1".to_owned(),
8529 "carries no query",
8530 ),
8531 (
8532 "socks5h://proxy.example/#f".to_owned(),
8533 "carries no fragment",
8534 ),
8535 ("socks5h://proxy.example:99999".to_owned(), "not a number"),
8536 (
8537 "socks5h://s3cret@proxy.example".to_owned(),
8538 "password is empty",
8539 ),
8540 (
8541 "socks5h://s3cret:@proxy.example".to_owned(),
8542 "password is empty",
8543 ),
8544 (
8545 "socks5h://:s3cret@proxy.example".to_owned(),
8546 "user name is empty",
8547 ),
8548 ("socks5h://@proxy.example".to_owned(), "user name is empty"),
8549 (
8550 format!("socks5h://{long}:s3cret@proxy.example"),
8551 "user name is longer",
8552 ),
8553 (
8554 format!("socks5h://alice:{long}s3cret@proxy.example"),
8555 "password is longer",
8556 ),
8557 (
8558 "socks5h://alice:s3cret%zz@proxy.example".to_owned(),
8559 "percent-encoded",
8560 ),
8561 (
8562 "socks5h://alice:s3cret%ff@proxy.example".to_owned(),
8563 "percent-encoded",
8564 ),
8565 ] {
8566 let err = parse_proxy(&url).unwrap_err();
8567 assert!(matches!(err, Error::Unsupported(_)), "{url}: {err}");
8568 let message = err.to_string();
8569 assert!(message.contains(says), "{url}: {message}");
8570 assert!(
8571 message.contains("socks5h://proxy.example"),
8572 "{url}: {message}"
8573 );
8574 assert!(!message.contains("s3cret"), "{url}: {message}");
8575 }
8576 }
8577
8578 /// A `socks5` URL names a SOCKS5 endpoint whose client resolves the origin
8579 /// host, with the port 1080 by default. A `socks5h` URL names one whose
8580 /// proxy resolves it. The URL rules and the userinfo rules are the rules
8581 /// of a `socks5h` URL.
8582 #[test]
8583 fn a_socks5_proxy_url_names_its_endpoint() {
8584 let resolve = |url: &str| match parse_proxy(url).unwrap().kind {
8585 ProxyKind::Socks(socks) => (socks.resolve, socks.credential.is_some()),
8586 ProxyKind::Http { .. } => panic!("{url} names a SOCKS5 proxy"),
8587 };
8588 for (url, host, port, named) in [
8589 (
8590 "socks5://proxy.example",
8591 "proxy.example",
8592 1080,
8593 "socks5://proxy.example",
8594 ),
8595 (
8596 "socks5://proxy.example:1080",
8597 "proxy.example",
8598 1080,
8599 "socks5://proxy.example",
8600 ),
8601 (
8602 "SOCKS5://Proxy.Example:9050",
8603 "proxy.example",
8604 9050,
8605 "socks5://Proxy.Example:9050",
8606 ),
8607 ("socks5://[::1]", "::1", 1080, "socks5://[::1]"),
8608 (
8609 "socks5://alice:s3cret@proxy.example",
8610 "proxy.example",
8611 1080,
8612 "socks5://proxy.example",
8613 ),
8614 ] {
8615 let proxy = parse_proxy(url).unwrap_or_else(|e| panic!("{url}: {e}"));
8616 assert_eq!(proxy.endpoint.host, host, "{url}");
8617 assert_eq!(proxy.endpoint.port, port, "{url}");
8618 assert!(!proxy.endpoint.tls, "{url}");
8619 assert_eq!(proxy.named, named, "{url}");
8620 assert_eq!(resolve(url).0, ResolveSide::Client, "{url}");
8621 }
8622 assert_eq!(
8623 resolve("socks5h://proxy.example"),
8624 (ResolveSide::Proxy, false)
8625 );
8626 assert_eq!(
8627 resolve("socks5://alice:s3cret@proxy.example"),
8628 (ResolveSide::Client, true)
8629 );
8630 assert_eq!(
8631 resolve("socks5://proxy.example"),
8632 (ResolveSide::Client, false)
8633 );
8634
8635 let err = parse_proxy("socks5://s3cret@proxy.example").unwrap_err();
8636 assert!(matches!(err, Error::Unsupported(_)), "{err}");
8637 let message = err.to_string();
8638 assert!(message.contains("password is empty"), "{message}");
8639 assert!(message.contains("socks5://proxy.example"), "{message}");
8640 assert!(!message.contains("s3cret"), "{message}");
8641 }
8642
8643 /// The marker that [`socks_peer`] writes after a reply of success. It
8644 /// stands for the first bytes of the origin.
8645 const SOCKS_MARKER: &[u8] = b"origin bytes";
8646
8647 /// The answers of a [`socks_peer`].
8648 struct SocksScript {
8649 /// The method that the peer selects.
8650 method: u8,
8651 /// The status of the RFC 1929 reply, if the peer selects `02`.
8652 auth_status: u8,
8653 /// The `REP` of each connection in turn. A connection after the end of
8654 /// the list gets `00`.
8655 replies: Vec<u8>,
8656 }
8657
8658 /// What a [`socks_peer`] saw.
8659 #[derive(Debug, Default)]
8660 struct SocksSeen {
8661 /// The number of connections that the peer accepted.
8662 connections: usize,
8663 /// The `ATYP`, the address bytes, and the port of each request.
8664 requests: Vec<(u8, Vec<u8>, u16)>,
8665 }
8666
8667 /// Starts a scripted SOCKS5 peer on a loopback port, and gives the port
8668 /// and what the peer sees.
8669 ///
8670 /// The peer serves one connection at a time. It answers the greeting with
8671 /// the method of `script`, the RFC 1929 exchange with its status, and the
8672 /// request of each connection with the next `REP`. After a `REP` of `00`,
8673 /// it writes [`SOCKS_MARKER`].
8674 async fn socks_peer(script: SocksScript) -> (u16, Arc<Mutex<SocksSeen>>) {
8675 use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
8676
8677 let peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
8678 .await
8679 .unwrap();
8680 let port = peer.local_addr().unwrap().port();
8681 let seen = Arc::new(Mutex::new(SocksSeen::default()));
8682 let record = seen.clone();
8683 drop(rt::spawn(async move {
8684 while let Ok((mut stream, _peer)) = peer.accept().await {
8685 let index = {
8686 let mut seen = record.lock().unwrap();
8687 seen.connections += 1;
8688 seen.connections - 1
8689 };
8690 let reply = script.replies.get(index).copied().unwrap_or(0);
8691 let record = record.clone();
8692 let script = &script;
8693 let served = async move {
8694 let mut head = [0u8; 2];
8695 stream.read_exact(&mut head).await?;
8696 let mut methods = vec![0u8; usize::from(head[1])];
8697 stream.read_exact(&mut methods).await?;
8698 stream.write_all(&[0x05, script.method]).await?;
8699 stream.flush().await?;
8700 if script.method == 0x02 {
8701 let mut len = [0u8; 2];
8702 stream.read_exact(&mut len).await?;
8703 let mut user = vec![0u8; usize::from(len[1])];
8704 stream.read_exact(&mut user).await?;
8705 stream.read_exact(&mut len[..1]).await?;
8706 let mut password = vec![0u8; usize::from(len[0])];
8707 stream.read_exact(&mut password).await?;
8708 stream.write_all(&[0x01, script.auth_status]).await?;
8709 stream.flush().await?;
8710 if script.auth_status != 0x00 {
8711 return std::io::Result::Ok(());
8712 }
8713 } else if script.method != 0x00 {
8714 return Ok(());
8715 }
8716 let mut request = [0u8; 4];
8717 stream.read_exact(&mut request).await?;
8718 let mut addr = match request[3] {
8719 0x01 => vec![0u8; 4],
8720 0x04 => vec![0u8; 16],
8721 _ => {
8722 let mut len = [0u8; 1];
8723 stream.read_exact(&mut len).await?;
8724 vec![0u8; usize::from(len[0])]
8725 }
8726 };
8727 stream.read_exact(&mut addr).await?;
8728 let mut port = [0u8; 2];
8729 stream.read_exact(&mut port).await?;
8730 record.lock().unwrap().requests.push((
8731 request[3],
8732 addr,
8733 u16::from_be_bytes(port),
8734 ));
8735 stream
8736 .write_all(&[0x05, reply, 0x00, 0x01, 0, 0, 0, 0, 0, 0])
8737 .await?;
8738 if reply == 0x00 {
8739 stream.write_all(SOCKS_MARKER).await?;
8740 }
8741 stream.flush().await
8742 };
8743 let _ = served.await;
8744 }
8745 }));
8746 (port, seen)
8747 }
8748
8749 /// The endpoint of a SOCKS5 proxy URL.
8750 fn socks_endpoint(url: &str) -> ProxyEndpoint {
8751 let proxy = parse_proxy(url).unwrap();
8752 assert!(matches!(proxy.kind, ProxyKind::Socks(_)), "{url}");
8753 proxy
8754 }
8755
8756 /// The SOCKS5 settings of an endpoint that [`socks_endpoint`] gives.
8757 fn socks_of(proxy: &ProxyEndpoint) -> &SocksProxy {
8758 let ProxyKind::Socks(socks) = &proxy.kind else {
8759 panic!("{} names a SOCKS5 proxy", proxy.named);
8760 };
8761 socks
8762 }
8763
8764 /// The TLS origin of the address loop tests.
8765 fn loop_origin() -> Origin {
8766 Origin {
8767 tls: true,
8768 host: "origin.example".to_owned(),
8769 port: 443,
8770 }
8771 }
8772
8773 /// The address list of the address loop tests: an IPv4 address, then an
8774 /// IPv6 address.
8775 fn two_addresses() -> [SocketAddr; 2] {
8776 [
8777 "192.0.2.1:443".parse().unwrap(),
8778 "[2001:db8::1]:443".parse().unwrap(),
8779 ]
8780 }
8781
8782 /// A refusal of the first address moves the loop to the second address
8783 /// over a new connection to the proxy. Each request names the address,
8784 /// and the stream of the second connection carries the bytes after the
8785 /// reply.
8786 #[test]
8787 fn the_address_loop_moves_past_a_refused_address() {
8788 use futures_lite::io::AsyncReadExt;
8789
8790 rt::block_on(async {
8791 let (port, seen) = socks_peer(SocksScript {
8792 method: 0x00,
8793 auth_status: 0x00,
8794 replies: vec![0x05, 0x00],
8795 })
8796 .await;
8797 let proxy = socks_endpoint(&format!("socks5://127.0.0.1:{port}"));
8798 let addrs = two_addresses();
8799 let connected = within(
8800 Duration::from_secs(5),
8801 socks_each(&proxy, socks_of(&proxy), &loop_origin(), &addrs),
8802 )
8803 .await
8804 .expect("the loop ends within the limit");
8805 let Ok(mut stream) = connected else {
8806 panic!("the second address connects");
8807 };
8808 let mut marker = vec![0u8; SOCKS_MARKER.len()];
8809 stream.read_exact(&mut marker).await.unwrap();
8810 assert_eq!(marker, SOCKS_MARKER);
8811
8812 let seen = seen.lock().unwrap();
8813 assert_eq!(seen.connections, 2);
8814 let v6 = "2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap();
8815 assert_eq!(
8816 seen.requests,
8817 vec![
8818 (0x01, vec![192, 0, 2, 1], 443),
8819 (0x04, v6.octets().to_vec(), 443),
8820 ]
8821 );
8822 });
8823 }
8824
8825 /// A refused user name and password is definitive, so the loop stops at
8826 /// the first address. The message names the proxy and the origin, and
8827 /// holds no part of the credential.
8828 #[test]
8829 fn an_auth_refusal_stops_the_address_loop() {
8830 rt::block_on(async {
8831 let (port, seen) = socks_peer(SocksScript {
8832 method: 0x02,
8833 auth_status: 0x01,
8834 replies: Vec::new(),
8835 })
8836 .await;
8837 let proxy = socks_endpoint(&format!("socks5://alice:s3cret@127.0.0.1:{port}"));
8838 let addrs = two_addresses();
8839 let failure = within(
8840 Duration::from_secs(5),
8841 socks_each(&proxy, socks_of(&proxy), &loop_origin(), &addrs),
8842 )
8843 .await
8844 .expect("the loop ends within the limit");
8845 let Err(Failure::Fatal(err)) = failure else {
8846 panic!("an auth refusal is definitive");
8847 };
8848 let message = err.to_string();
8849 assert!(
8850 message.contains(&format!("socks5://127.0.0.1:{port}")),
8851 "{message}"
8852 );
8853 assert!(message.contains("origin.example:443"), "{message}");
8854 assert!(!message.contains("s3cret"), "{message}");
8855 assert!(!message.contains("alice"), "{message}");
8856 assert_eq!(seen.lock().unwrap().connections, 1);
8857 });
8858 }
8859
8860 /// With each address refused, the retryable failure names the last
8861 /// address, the number of addresses, and the last reason.
8862 #[test]
8863 fn every_refused_address_gives_the_last_failure() {
8864 rt::block_on(async {
8865 let (port, seen) = socks_peer(SocksScript {
8866 method: 0x00,
8867 auth_status: 0x00,
8868 replies: vec![0x05, 0x04],
8869 })
8870 .await;
8871 let proxy = socks_endpoint(&format!("socks5://127.0.0.1:{port}"));
8872 let addrs = two_addresses();
8873 let failure = within(
8874 Duration::from_secs(5),
8875 socks_each(&proxy, socks_of(&proxy), &loop_origin(), &addrs),
8876 )
8877 .await
8878 .expect("the loop ends within the limit");
8879 let Err(Failure::Retry(err)) = failure else {
8880 panic!("a refused connect is retryable");
8881 };
8882 assert_eq!(
8883 err.to_string(),
8884 format!(
8885 "fetch: connect to origin.example:443 through the proxy \
8886 socks5://127.0.0.1:{port} failed at [2001:db8::1]:443, the last of 2 addresses: the proxy refused \
8887 the connect with the code 04 (host unreachable)"
8888 )
8889 );
8890 assert_eq!(seen.lock().unwrap().connections, 2);
8891 });
8892 }
8893
8894 /// Under `socks5://`, a host name that the resolver refuses is retryable.
8895 /// The message names the origin host, and the fetcher opens no connection
8896 /// to the proxy. A name with a NUL byte passes the SOCKS5 checks of the
8897 /// name, and `std` refuses it before it calls the resolver of the system.
8898 /// So the test sends no DNS query.
8899 #[test]
8900 fn a_failed_resolve_names_the_origin_host() {
8901 rt::block_on(async {
8902 let (port, seen) = socks_peer(SocksScript {
8903 method: 0x00,
8904 auth_status: 0x00,
8905 replies: Vec::new(),
8906 })
8907 .await;
8908 let proxy = socks_endpoint(&format!("socks5://127.0.0.1:{port}"));
8909 let origin = Origin {
8910 tls: true,
8911 host: "origin\0example".to_owned(),
8912 port: 443,
8913 };
8914 let failure = within(
8915 Duration::from_secs(5),
8916 socks_connect(&proxy, socks_of(&proxy), &origin),
8917 )
8918 .await
8919 .expect("the resolve ends within the limit");
8920 let Err(Failure::Retry(err)) = failure else {
8921 panic!("a failed resolve is retryable");
8922 };
8923 let message = err.to_string();
8924 assert!(
8925 message.starts_with(&format!(
8926 "fetch: connect to origin\0example:443 through the proxy \
8927 socks5://127.0.0.1:{port} failed: cannot resolve origin\0example: "
8928 )),
8929 "{message}"
8930 );
8931 assert_eq!(seen.lock().unwrap().connections, 0);
8932 });
8933 }
8934
8935 /// A failed connect to the proxy ends the loop at the first address. The
8936 /// failure is the retryable failure of a proxy connect, with no count of
8937 /// addresses.
8938 #[test]
8939 fn an_unreachable_proxy_ends_the_address_loop() {
8940 rt::block_on(async {
8941 // An open connection holds its local port, and nothing listens on
8942 // that port. So a connect to the port is refused, and no other
8943 // test can bind the port before the end of this test.
8944 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
8945 let held = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap();
8946 let port = held.local_addr().unwrap().port();
8947 let proxy = socks_endpoint(&format!("socks5://127.0.0.1:{port}"));
8948 let addrs = two_addresses();
8949 let failure = within(
8950 Duration::from_secs(5),
8951 socks_each(&proxy, socks_of(&proxy), &loop_origin(), &addrs),
8952 )
8953 .await
8954 .expect("the loop ends within the limit");
8955 let Err(Failure::Retry(err)) = failure else {
8956 panic!("a failed proxy connect is retryable");
8957 };
8958 let message = err.to_string();
8959 assert!(
8960 message.starts_with(&format!(
8961 "fetch: connect to the proxy socks5://127.0.0.1:{port} failed: "
8962 )),
8963 "{message}"
8964 );
8965 assert!(!message.contains("the last of"), "{message}");
8966 drop((held, listener));
8967 });
8968 }
8969
8970 /// `http_proxy` serves cleartext origins, and `https_proxy` serves TLS
8971 /// origins. `all_proxy` serves both schemes if the scheme-specific variable
8972 /// is unset. Lower case wins over upper case, and an empty value counts as
8973 /// unset. Nothing reads `HTTP_PROXY`.
8974 #[test]
8975 fn the_proxy_variables_are_read_per_scheme() {
8976 let cleartext = "http://origin.example/summary";
8977 let tls = "https://origin.example/summary";
8978 let absolute = |named: &str| Some((named.to_owned(), "absolute"));
8979 let tunnel = |named: &str| Some((named.to_owned(), "tunnel"));
8980 let socks = |named: &str| Some((named.to_owned(), "socks"));
8981
8982 // Each scheme is served by its own variable, and the request form
8983 // follows the origin. Cleartext uses the absolute form over a proxy
8984 // connection, and TLS uses a tunnel.
8985 let proxies = resolve_variables(&variables(&[
8986 ("http_proxy", "http://plain.example:3128"),
8987 ("https_proxy", "http://secure.example:3128"),
8988 ]))
8989 .unwrap();
8990 assert_eq!(
8991 via_of(&proxies, cleartext),
8992 absolute("http://plain.example:3128")
8993 );
8994 assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
8995
8996 // One variable serves its own scheme alone.
8997 let proxies =
8998 resolve_variables(&variables(&[("http_proxy", "http://plain.example:3128")])).unwrap();
8999 assert_eq!(
9000 via_of(&proxies, cleartext),
9001 absolute("http://plain.example:3128")
9002 );
9003 assert_eq!(via_of(&proxies, tls), None);
9004 let proxies =
9005 resolve_variables(&variables(&[("https_proxy", "http://secure.example:3128")]))
9006 .unwrap();
9007 assert_eq!(via_of(&proxies, cleartext), None);
9008 assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
9009
9010 // `all_proxy` serves either scheme, and the scheme-specific variable
9011 // takes the scheme it names.
9012 let proxies =
9013 resolve_variables(&variables(&[("all_proxy", "http://any.example:3128")])).unwrap();
9014 assert_eq!(
9015 via_of(&proxies, cleartext),
9016 absolute("http://any.example:3128")
9017 );
9018 assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
9019 let proxies = resolve_variables(&variables(&[
9020 ("all_proxy", "http://any.example:3128"),
9021 ("https_proxy", "http://secure.example:3128"),
9022 ]))
9023 .unwrap();
9024 assert_eq!(
9025 via_of(&proxies, cleartext),
9026 absolute("http://any.example:3128")
9027 );
9028 assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
9029
9030 // The upper-case name is read for each variable except `http_proxy`. A
9031 // CGI gateway gives a request header called `Proxy` to its program
9032 // under that name.
9033 let proxies = resolve_variables(&variables(&[
9034 ("HTTP_PROXY", "http://cgi.example:3128"),
9035 ("HTTPS_PROXY", "http://secure.example:3128"),
9036 ]))
9037 .unwrap();
9038 assert_eq!(via_of(&proxies, cleartext), None);
9039 assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
9040 let proxies =
9041 resolve_variables(&variables(&[("ALL_PROXY", "http://any.example:3128")])).unwrap();
9042 assert_eq!(
9043 via_of(&proxies, cleartext),
9044 absolute("http://any.example:3128")
9045 );
9046
9047 // Lower case wins over upper case, and an empty value counts as unset.
9048 // So the upper-case name is the one that is read.
9049 let proxies = resolve_variables(&variables(&[
9050 ("https_proxy", "http://lower.example:3128"),
9051 ("HTTPS_PROXY", "http://upper.example:3128"),
9052 ]))
9053 .unwrap();
9054 assert_eq!(via_of(&proxies, tls), tunnel("http://lower.example:3128"));
9055 let proxies = resolve_variables(&variables(&[
9056 ("https_proxy", ""),
9057 ("HTTPS_PROXY", "http://upper.example:3128"),
9058 ]))
9059 .unwrap();
9060 assert_eq!(via_of(&proxies, tls), tunnel("http://upper.example:3128"));
9061 let proxies = resolve_variables(&variables(&[("http_proxy", "")])).unwrap();
9062 assert_eq!(via_of(&proxies, cleartext), None);
9063
9064 // A value the fetcher cannot connect through fails the resolution
9065 // whichever variable held it.
9066 for name in ["http_proxy", "https_proxy", "all_proxy"] {
9067 let err = resolve_variables(&variables(&[(name, "socks4://proxy.example:1080")]))
9068 .unwrap_err();
9069 assert!(matches!(err, Error::Unsupported(_)), "{name}: {err}");
9070 }
9071 // A variable that the selection passes over is parsed too. An
9072 // `all_proxy` beside both scheme-specific variables is read by no
9073 // fetch. If it holds a value that the fetcher cannot connect through,
9074 // the resolution fails.
9075 let err = resolve_variables(&variables(&[
9076 ("all_proxy", "socks4://proxy.example:1080"),
9077 ("http_proxy", "http://plain.example:3128"),
9078 ("https_proxy", "http://secure.example:3128"),
9079 ]))
9080 .unwrap_err();
9081 assert!(matches!(err, Error::Unsupported(_)), "{err}");
9082
9083 // No variable at all, and the explicit forms of the option.
9084 let proxies = resolve_variables(&[]).unwrap();
9085 assert_eq!(via_of(&proxies, cleartext), None);
9086 assert_eq!(via_of(&proxies, tls), None);
9087 let proxies = resolve_proxy(&Proxy::None).unwrap();
9088 assert_eq!(via_of(&proxies, cleartext), None);
9089 // One URL serves every origin, and it reads no exemption.
9090 let proxies = resolve_proxy(&Proxy::Url("http://any.example:3128".into())).unwrap();
9091 assert_eq!(
9092 via_of(&proxies, cleartext),
9093 absolute("http://any.example:3128")
9094 );
9095 assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
9096
9097 // A SOCKS5 proxy in `https_proxy` serves TLS origins alone, and the
9098 // way is the same for each scheme that a SOCKS5 proxy serves.
9099 let proxies = resolve_variables(&variables(&[(
9100 "https_proxy",
9101 "socks5h://socks.example:9050",
9102 )]))
9103 .unwrap();
9104 assert_eq!(via_of(&proxies, tls), socks("socks5h://socks.example:9050"));
9105 assert_eq!(via_of(&proxies, cleartext), None);
9106 let proxies = resolve_proxy(&Proxy::Url("socks5h://socks.example".into())).unwrap();
9107 assert_eq!(via_of(&proxies, tls), socks("socks5h://socks.example"));
9108 assert_eq!(
9109 via_of(&proxies, cleartext),
9110 socks("socks5h://socks.example")
9111 );
9112 }
9113
9114 /// A proxy variable with white space at the start or the end of its value
9115 /// fails the resolution, also a value of white space alone. The message
9116 /// names the variable, and holds nothing of the value. Each variable that
9117 /// the selection reads is checked, also if no fetch uses it. A variable
9118 /// that the selection does not read is not checked.
9119 #[test]
9120 fn a_proxy_variable_with_white_space_around_it_is_refused() {
9121 let url = "http://alice:s3cret@proxy.example:3128";
9122 let refused = |pairs: &[(&str, &str)], name: &str| {
9123 let err = resolve_variables(&variables(pairs)).unwrap_err();
9124 assert!(matches!(err, Error::Unsupported(_)), "{pairs:?}: {err}");
9125 let message = err.to_string();
9126 assert!(message.contains(name), "{pairs:?}: {message}");
9127 assert!(!message.contains("s3cret"), "{pairs:?}: {message}");
9128 assert!(!message.contains("proxy.example"), "{pairs:?}: {message}");
9129 };
9130
9131 for name in [
9132 "http_proxy",
9133 "https_proxy",
9134 "HTTPS_PROXY",
9135 "all_proxy",
9136 "ALL_PROXY",
9137 ] {
9138 for value in [
9139 format!(" {url}"),
9140 format!("{url} "),
9141 format!("{url}\t"),
9142 format!("{url}\n"),
9143 format!("{url}\u{a0}"),
9144 " ".to_owned(),
9145 ] {
9146 refused(&[(name, &value)], name);
9147 }
9148 }
9149 // If the lower-case value is empty, the upper-case name is read, and
9150 // the refusal names it.
9151 refused(
9152 &[("all_proxy", ""), ("ALL_PROXY", "http://p:1 ")],
9153 "ALL_PROXY",
9154 );
9155 // The check comes before the parse, so a value the parse refuses as
9156 // well gets the white-space refusal.
9157 refused(
9158 &[("all_proxy", "socks4://alice:s3cret@proxy.example:1080 ")],
9159 "all_proxy",
9160 );
9161 // The refusal occurs when the fetcher is built. So an exemption of
9162 // every origin does not prevent it.
9163 refused(
9164 &[("http_proxy", &format!("{url} ")), ("no_proxy", "*")],
9165 "http_proxy",
9166 );
9167 // `all_proxy` beside both scheme-specific variables is read by no
9168 // fetch, and the check still reads its value.
9169 refused(
9170 &[
9171 ("all_proxy", &format!("{url} ")),
9172 ("http_proxy", "http://plain.example:3128"),
9173 ("https_proxy", "http://secure.example:3128"),
9174 ],
9175 "all_proxy",
9176 );
9177
9178 // An upper-case name shadowed by its lower-case one is not read, and
9179 // `HTTP_PROXY` is read by nothing.
9180 resolve_variables(&variables(&[
9181 ("https_proxy", "http://secure.example:3128"),
9182 ("HTTPS_PROXY", "http://upper.example:3128 "),
9183 ]))
9184 .unwrap();
9185 resolve_variables(&variables(&[("HTTP_PROXY", "http://cgi.example:3128 ")])).unwrap();
9186 // A URL the caller states in the options keeps its trim.
9187 resolve_proxy(&Proxy::Url("http://p:3128 ".into())).unwrap();
9188 }
9189
9190 /// `check_options` takes the options that the constructor takes up to
9191 /// its TLS setup, and refuses each other value with the error of the
9192 /// constructor, in the order of the constructor.
9193 #[test]
9194 fn check_options_gives_the_refusals_of_the_constructor_that_read_no_file() {
9195 let base = || direct_options("http://origin.example/repo");
9196 let proxy = |proxy: Proxy| FetcherOptions { proxy, ..base() };
9197 let headers = |pairs: &[(&str, &str)]| FetcherOptions {
9198 headers: pairs
9199 .iter()
9200 .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
9201 .collect(),
9202 ..base()
9203 };
9204 let bearer = |token: &str| {
9205 Some(BearerToken {
9206 token: token.to_owned(),
9207 })
9208 };
9209 for options in [
9210 base(),
9211 proxy(Proxy::Url("http://proxy.example:3128".into())),
9212 proxy(Proxy::Url("socks5h://socks.example".into())),
9213 proxy(Proxy::Variables(vec![
9214 ("https_proxy".into(), "http://proxy.example:3128".into()),
9215 ("no_proxy".into(), ".internal.example".into()),
9216 ])),
9217 headers(&[("X-Trace", "1")]),
9218 ] {
9219 check_options(&options).unwrap();
9220 }
9221 let refused = [
9222 FetcherOptions {
9223 low_speed: Some(LowSpeed {
9224 limit: 0,
9225 time: Duration::from_secs(30),
9226 }),
9227 ..base()
9228 },
9229 FetcherOptions {
9230 mirrors: vec!["http://origin.example/repo?x=1".into()],
9231 ..base()
9232 },
9233 FetcherOptions {
9234 mirrors: vec!["ftp://origin.example/repo".into()],
9235 ..base()
9236 },
9237 headers(&[("Host", "other.example")]),
9238 headers(&[("bad name", "1")]),
9239 headers(&[("Connection", "close")]),
9240 headers(&[("X-Trace", "a\nb")]),
9241 headers(&[("Cookie", "id=1")]),
9242 FetcherOptions {
9243 bearer_token: bearer("tok"),
9244 ..base()
9245 },
9246 FetcherOptions {
9247 bearer_token: bearer("tok"),
9248 allow_cleartext_credentials: true,
9249 ..headers(&[("Authorization", "Bearer other")])
9250 },
9251 FetcherOptions {
9252 bearer_token: bearer("not token68"),
9253 allow_cleartext_credentials: true,
9254 ..base()
9255 },
9256 proxy(Proxy::Url("ftp://proxy.example:3128".into())),
9257 proxy(Proxy::Url("http://proxy.example:3128/squid".into())),
9258 proxy(Proxy::Variables(vec![(
9259 "http_proxy".into(),
9260 "ftp://x".into(),
9261 )])),
9262 proxy(Proxy::Variables(vec![(
9263 "all_proxy".into(),
9264 "socks4://x".into(),
9265 )])),
9266 proxy(Proxy::Variables(vec![(
9267 "https_proxy".into(),
9268 "http://p:1 ".into(),
9269 )])),
9270 // A bad header comes before a bad proxy.
9271 FetcherOptions {
9272 proxy: Proxy::Url("ftp://proxy.example:3128".into()),
9273 ..headers(&[("Host", "other.example")])
9274 },
9275 ];
9276 for options in refused {
9277 let checked = check_options(&options).unwrap_err();
9278 let built = rt::block_on(Fetcher::new(options.clone())).err().unwrap();
9279 assert_eq!(checked.to_string(), built.to_string(), "{options:?}");
9280 }
9281 let both = FetcherOptions {
9282 proxy: Proxy::Url("ftp://proxy.example:3128".into()),
9283 ..headers(&[("Host", "other.example")])
9284 };
9285 assert!(matches!(check_options(&both), Err(Error::Fetch(_))));
9286 }
9287
9288 /// What `no_proxy` exempts: an exact host, a host under a listed domain, a
9289 /// port-qualified entry, and every host under `*`. The match is made
9290 /// against the host text and never against the address it resolves to.
9291 #[test]
9292 fn no_proxy_exempts_by_host_text_and_port() {
9293 let proxied = |no_proxy: &str, url: &str| {
9294 let proxies = resolve_variables(&variables(&[
9295 ("all_proxy", "http://any.example:3128"),
9296 ("no_proxy", no_proxy),
9297 ]))
9298 .unwrap();
9299 via_of(&proxies, url).is_some()
9300 };
9301
9302 // An exact host, and a host of another name at the same domain.
9303 assert!(!proxied("origin.example", "http://origin.example/p"));
9304 assert!(proxied("origin.example", "http://other.example/p"));
9305 // A host under a listed domain, in each of the two spellings of the
9306 // entry. A name that only ends with the same letters is not exempted.
9307 for entry in ["example.com", ".example.com"] {
9308 assert!(!proxied(entry, "http://a.example.com/p"));
9309 assert!(!proxied(entry, "http://deep.a.example.com/p"));
9310 assert!(!proxied(entry, "http://example.com/p"));
9311 assert!(proxied(entry, "http://notexample.com/p"));
9312 }
9313 // The list is comma-separated, space around an entry is ignored, and an
9314 // empty entry names nothing.
9315 assert!(!proxied(" a.example , b.example ", "http://b.example/p"));
9316 assert!(!proxied("a.example,,b.example", "http://a.example/p"));
9317 assert!(proxied(",", "http://a.example/p"));
9318 assert!(proxied("", "http://a.example/p"));
9319 // ASCII case is ignored on both sides.
9320 assert!(!proxied("ORIGIN.example", "http://origin.EXAMPLE/p"));
9321 // A port-qualified entry matches that port alone.
9322 assert!(!proxied(
9323 "origin.example:8080",
9324 "http://origin.example:8080/p"
9325 ));
9326 assert!(proxied(
9327 "origin.example:8080",
9328 "http://origin.example:8081/p"
9329 ));
9330 assert!(proxied("origin.example:8080", "http://origin.example/p"));
9331 assert!(!proxied("origin.example:443", "https://origin.example/p"));
9332 // An entry with no port matches whatever port the origin names.
9333 assert!(!proxied("origin.example", "http://origin.example:8080/p"));
9334 // `*` exempts every host, whatever else the list holds.
9335 for url in ["http://a.example/p", "https://b.example:8443/p"] {
9336 assert!(!proxied("*", url));
9337 assert!(!proxied("a.example,*", url));
9338 }
9339 // An IP literal matches that text and nothing else. So the address of a
9340 // name does not exempt the name, and a name does not exempt an address.
9341 assert!(!proxied("127.0.0.1", "http://127.0.0.1:8080/p"));
9342 assert!(proxied("localhost", "http://127.0.0.1:8080/p"));
9343 assert!(proxied("127.0.0.1", "http://localhost:8080/p"));
9344 // An IPv6 literal is exempted by the address alone, written with or
9345 // without the brackets the authority carries.
9346 for entry in ["::1", "[::1]", "[::1]:8080"] {
9347 assert!(!proxied(entry, "http://[::1]:8080/p"), "{entry}");
9348 }
9349 assert!(proxied("[::1]:8081", "http://[::1]:8080/p"));
9350 // A network in CIDR notation names no network here: it is read as a
9351 // host text, which no origin holds.
9352 assert!(proxied("127.0.0.0/8", "http://127.0.0.1:8080/p"));
9353 // A port text that is no port leaves the entry as one host text, which
9354 // no origin host holds.
9355 assert!(proxied("origin.example:abc", "http://origin.example/p"));
9356 // An entry that names no host exempts nothing, also for a host written
9357 // with a trailing `.`.
9358 for entry in [".", ":8080", ".:8080"] {
9359 assert!(proxied(entry, "http://a.example./p"), "{entry}");
9360 assert!(proxied(entry, "http://a.example:8080/p"), "{entry}");
9361 }
9362 // One leading `.` is stripped, so a second belongs to the host text the
9363 // entry names.
9364 assert!(proxied("..example.com", "http://a.example.com/p"));
9365 // `*` as a whole entry is the one wildcard of the list. Each other form
9366 // with a `*` is a host text.
9367 assert!(proxied("*.example.com", "http://a.example.com/p"));
9368 assert!(proxied("*.example.com", "http://example.com/p"));
9369 }
9370
9371 /// The userinfo of a proxy URL holds a password. So it reaches neither a
9372 /// rendering of the options nor a refusal of the constructor.
9373 #[test]
9374 fn a_proxy_password_reaches_no_message() {
9375 let url = |tail: &str| format!("http://alice:sup3rs3cret@proxy.example:3128{tail}");
9376
9377 // The rendering of every form that carries a URL.
9378 for proxy in [
9379 Proxy::Url(url("")),
9380 Proxy::Variables(vec![("https_proxy".to_owned(), url(""))]),
9381 ] {
9382 let rendered = format!("{proxy:?}");
9383 assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
9384 assert!(rendered.contains("proxy.example:3128"), "{rendered}");
9385
9386 let options = FetcherOptions {
9387 proxy,
9388 ..direct_options("https://example.com")
9389 };
9390 let rendered = format!("{options:?}");
9391 assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
9392 }
9393
9394 // Each refusal, whichever part of the URL the parse read.
9395 for tail in ["/squid", "/?upstream=1", "/#frag", ":99999"] {
9396 let err = parse_proxy(&url(tail)).unwrap_err();
9397 let message = err.to_string();
9398 assert!(!message.contains("sup3rs3cret"), "{tail}: {message}");
9399 }
9400 let err = parse_proxy("socks4://alice:sup3rs3cret@proxy.example:1080").unwrap_err();
9401 assert!(!err.to_string().contains("sup3rs3cret"), "{err}");
9402 let err = parse_proxy("socks5h://alice:sup3rs3cret@proxy.example/x").unwrap_err();
9403 assert!(!err.to_string().contains("sup3rs3cret"), "{err}");
9404
9405 // A password with a `/`, a `?`, or a `#` ends the authority before the
9406 // `@`. The userinfo is left out also in this case.
9407 for password in ["pa#ss", "pa?ss", "p/ss"] {
9408 let url = format!("http://alice:{password}@proxy.example:3128/squid");
9409 let rendered = format!("{:?}", Proxy::Url(url.clone()));
9410 assert!(!rendered.contains(password), "{password}: {rendered}");
9411 assert!(
9412 rendered.contains("proxy.example:3128"),
9413 "{password}: {rendered}"
9414 );
9415 let message = parse_proxy(&url).unwrap_err().to_string();
9416 assert!(!message.contains(password), "{password}: {message}");
9417 assert!(
9418 message.contains("proxy.example:3128"),
9419 "{password}: {message}"
9420 );
9421 }
9422
9423 // A `/` or a `?` in the userinfo moves the text after it into the path
9424 // or the query. The refusal of that path or query shows no part of it.
9425 for userinfo in ["u/pw-QXZ", "tok?pw-QXZ", "u:x/pw-QXZ", "u:x?pw-QXZ"] {
9426 let url = format!("http://{userinfo}@proxy.invalid:3128");
9427 let message = parse_proxy(&url).unwrap_err().to_string();
9428 assert!(!message.contains("pw-QXZ"), "{userinfo}: {message}");
9429 }
9430
9431 // The refusal the constructor writes is the one a caller logs.
9432 rt::block_on(async {
9433 let err = Fetcher::new(FetcherOptions {
9434 proxy: Proxy::Url(url("/squid")),
9435 ..direct_options("http://origin.example/repo")
9436 })
9437 .await
9438 .unwrap_err();
9439 assert!(matches!(err, Error::Unsupported(_)), "{err}");
9440 let message = err.to_string();
9441 assert!(!message.contains("sup3rs3cret"), "{message}");
9442 assert!(message.contains("proxy.example:3128"), "{message}");
9443 });
9444 }
9445
9446 /// The `Debug` of a proxy writes each URL as `RedactedUrl` writes it. The
9447 /// form of each variant is the form of `derive(Debug)`.
9448 #[test]
9449 fn proxy_debug_redacts_each_url() {
9450 let url = "http://alice:pw-QXZ@proxy.example:3128/?t=QXZ#QXZ";
9451 assert_eq!(
9452 format!("{:?}", Proxy::Url(url.to_owned())),
9453 r#"Url("http://proxy.example:3128/?<redacted>#<redacted>")"#
9454 );
9455 let variables = Proxy::Variables(vec![
9456 ("https_proxy".to_owned(), url.to_owned()),
9457 ("no_proxy".to_owned(), ".internal.example.com".to_owned()),
9458 ]);
9459 assert_eq!(
9460 format!("{variables:?}"),
9461 concat!(
9462 r#"Variables([("https_proxy", "http://proxy.example:3128/?<redacted>#<redacted>"), "#,
9463 r#"("no_proxy", ".internal.example.com")])"#
9464 )
9465 );
9466 assert_eq!(format!("{:?}", Proxy::None), "None");
9467 assert_eq!(format!("{:?}", Proxy::Environment), "Environment");
9468 }
9469
9470 /// The text before `://` is a scheme only when it is a valid scheme. Else
9471 /// the userinfo starts at the start of the text.
9472 #[test]
9473 fn without_userinfo_reads_only_a_valid_scheme() {
9474 assert_eq!(without_userinfo("u:a://b@h/p"), "h/p");
9475 assert_eq!(without_userinfo("svn+ssh://u@h/p"), "svn+ssh://h/p");
9476 assert_eq!(without_userinfo("https://h/p"), "https://h/p");
9477 assert_eq!(scheme_len("1http://h"), 0);
9478 assert_eq!(scheme_len("://h"), 0);
9479 assert_eq!(scheme_len("h/p"), 0);
9480 }
9481
9482 /// A `CONNECT` names its target by host and port, and always writes the
9483 /// port. The proxy opens a TCP connection, which reads no scheme.
9484 #[test]
9485 fn a_connect_names_the_target_with_its_port() {
9486 for (url, authority) in [
9487 ("https://origin.example/p", "origin.example:443"),
9488 ("https://origin.example:8443/p", "origin.example:8443"),
9489 ("http://origin.example/p", "origin.example:80"),
9490 ("https://[2001:db8::1]/p", "[2001:db8::1]:443"),
9491 ("https://[::1]:8443/p", "[::1]:8443"),
9492 ] {
9493 assert_eq!(connect_authority(&origin_of(url)), authority, "{url}");
9494 }
9495 }
9496
9497 /// A proxied cleartext request carries the absolute-form target and the
9498 /// `Host` header of the origin. It also carries the credential of the
9499 /// proxy, if the merged headers hold no header of that name. A direct
9500 /// request and the request over a tunnel carry the origin form and nothing
9501 /// of the proxy.
9502 #[test]
9503 fn a_proxied_cleartext_request_carries_the_absolute_form() {
9504 rt::block_on(async {
9505 let fetcher = Fetcher::new(FetcherOptions {
9506 proxy: Proxy::Url("http://alice:s3cret@proxy.example:3128".into()),
9507 ..tls_options("http://origin.example/r")
9508 })
9509 .await
9510 .unwrap();
9511 let destination = fetcher.inner.mirrors[0].destination("refs/heads/a", None);
9512 let request = FetchRequest::path("refs/heads/a");
9513 let built = |via: Via<'_>, headers: &[(HeaderName, HeaderValue)]| {
9514 fetcher
9515 .build_request(&destination, &request, headers, Protocol::Http11, via)
9516 .unwrap()
9517 };
9518 let proxy_credential = |request: &Request<RequestBody>| {
9519 request
9520 .headers()
9521 .get(hyper::header::PROXY_AUTHORIZATION)
9522 .map(|value| value.to_str().unwrap().to_owned())
9523 };
9524 let Via::Absolute(proxy) = fetcher.inner.proxies.via(&destination.origin) else {
9525 panic!("a cleartext origin behind a proxy travels in absolute form");
9526 };
9527 let via = Via::Absolute(proxy);
9528
9529 let absolute = built(via, &fetcher.inner.headers);
9530 assert_eq!(absolute.uri(), "http://origin.example/r/refs/heads/a");
9531 assert_eq!(
9532 absolute.headers().get(hyper::header::HOST).unwrap(),
9533 "origin.example"
9534 );
9535 // base64("alice:s3cret")
9536 assert_eq!(
9537 proxy_credential(&absolute).as_deref(),
9538 Some("Basic YWxpY2U6czNjcmV0")
9539 );
9540
9541 // A `Proxy-Authorization` header that the caller set states the
9542 // value for the proxy. So the credential of the fetcher is left
9543 // out, and is not added to it.
9544 let mut headers = fetcher.inner.headers.clone();
9545 headers.push((
9546 hyper::header::PROXY_AUTHORIZATION,
9547 HeaderValue::from_static("Basic Y2FsbGVy"),
9548 ));
9549 let caller = built(via, &headers);
9550 assert_eq!(
9551 caller
9552 .headers()
9553 .get_all(hyper::header::PROXY_AUTHORIZATION)
9554 .iter()
9555 .count(),
9556 1
9557 );
9558 assert_eq!(proxy_credential(&caller).as_deref(), Some("Basic Y2FsbGVy"));
9559
9560 // A direct hop, the request over a tunnel, and the request over a
9561 // SOCKS5 connection carry the origin form and nothing of the proxy.
9562 let socks_proxy = parse_proxy("socks5h://bob:pw@socks.example").unwrap();
9563 let ProxyKind::Socks(socks) = &socks_proxy.kind else {
9564 panic!("a socks5h url names a SOCKS5 proxy");
9565 };
9566 for via in [
9567 Via::Direct,
9568 Via::Tunnel(proxy),
9569 Via::Socks(&socks_proxy, socks),
9570 ] {
9571 let direct = built(via, &fetcher.inner.headers);
9572 assert_eq!(direct.uri(), "/r/refs/heads/a");
9573 assert_eq!(proxy_credential(&direct), None);
9574 }
9575 });
9576 }
9577
9578 /// The connection layer frames a request and holds its connection. So a
9579 /// header of one of those names is refused. The constructor refuses a
9580 /// fetcher header, and a request header fails before admission.
9581 #[test]
9582 fn a_connection_header_is_refused_at_both_layers() {
9583 let fetcher_headers = vec![(
9584 HeaderName::from_static("x-trace"),
9585 HeaderValue::from_static("abc"),
9586 )];
9587 for name in CONNECTION_HEADERS {
9588 let options = FetcherOptions {
9589 headers: vec![(name.to_owned(), "10".to_owned())],
9590 ..direct_options("http://example.com")
9591 };
9592 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
9593 let message = err.to_string();
9594 assert!(message.contains(name), "{name}: {message}");
9595 assert!(message.contains("connection layer"), "{name}: {message}");
9596
9597 let request = vec![(name.to_owned(), "10".to_owned())];
9598 let err = merge_headers(&fetcher_headers, &request, None, None).unwrap_err();
9599 let message = err.to_string();
9600 assert!(message.contains(name), "{name}: {message}");
9601 assert!(message.contains("connection layer"), "{name}: {message}");
9602 }
9603
9604 // A name written in another case is the same header name.
9605 let request = vec![("Content-Length".to_owned(), "10".to_owned())];
9606 let err = merge_headers(&fetcher_headers, &request, None, None).unwrap_err();
9607 assert!(err.to_string().contains("content-length"), "{err}");
9608 }
9609
9610 /// A request that adds no header and no credentials sends the list of the
9611 /// fetcher by reference. A request header replaces the fetcher header of
9612 /// the same name. The credentials of the request replace the
9613 /// `Authorization` of the fetcher.
9614 #[test]
9615 fn request_headers_merge_over_the_fetchers() {
9616 let header = |name: &'static str, value: &'static str| {
9617 (
9618 HeaderName::from_static(name),
9619 HeaderValue::from_static(value),
9620 )
9621 };
9622 let fetcher = vec![
9623 header("x-trace", "fetcher"),
9624 header("x-only", "yes"),
9625 header("authorization", "Basic ZmV0Y2hlcg=="),
9626 ];
9627 let sent = |headers: &[(HeaderName, HeaderValue)]| {
9628 headers
9629 .iter()
9630 .map(|(name, value)| (name.as_str().to_owned(), value.to_str().unwrap().to_owned()))
9631 .collect::<Vec<_>>()
9632 };
9633
9634 let borrowed = merge_headers(&fetcher, &[], None, None).unwrap();
9635 assert!(matches!(borrowed, Cow::Borrowed(_)));
9636 assert_eq!(sent(&borrowed), sent(&fetcher));
9637
9638 // The replacement compares names as header names, so the case that the
9639 // request wrote has no effect. It leaves each other fetcher header in
9640 // place. Two request headers of one name both reach the wire.
9641 let extra = vec![
9642 ("X-Trace".to_owned(), "request".to_owned()),
9643 ("x-trace".to_owned(), "second".to_owned()),
9644 ];
9645 let merged = merge_headers(&fetcher, &extra, None, None).unwrap();
9646 assert_eq!(
9647 sent(&merged),
9648 [
9649 ("x-only".to_owned(), "yes".to_owned()),
9650 ("authorization".to_owned(), "Basic ZmV0Y2hlcg==".to_owned()),
9651 ("x-trace".to_owned(), "request".to_owned()),
9652 ("x-trace".to_owned(), "second".to_owned()),
9653 ]
9654 );
9655
9656 // base64("u:p")
9657 let auth = BasicAuth {
9658 user: "u".into(),
9659 password: "p".into(),
9660 };
9661 let merged = merge_headers(&fetcher, &[], Some(&auth), None).unwrap();
9662 assert_eq!(
9663 sent(&merged),
9664 [
9665 ("x-trace".to_owned(), "fetcher".to_owned()),
9666 ("x-only".to_owned(), "yes".to_owned()),
9667 ("authorization".to_owned(), "Basic dTpw".to_owned()),
9668 ]
9669 );
9670
9671 let both = vec![("authorization".to_owned(), "Basic aaa".to_owned())];
9672 let err = merge_headers(&fetcher, &both, Some(&auth), None).unwrap_err();
9673 assert!(err.to_string().contains("pass one of them"), "{err}");
9674 let host = vec![("host".to_owned(), "elsewhere".to_owned())];
9675 let err = merge_headers(&fetcher, &host, None, None).unwrap_err();
9676 assert!(err.to_string().contains("host header"), "{err}");
9677 let invalid = vec![("not a header".to_owned(), "v".to_owned())];
9678 let err = merge_headers(&fetcher, &invalid, None, None).unwrap_err();
9679 assert!(err.to_string().contains("invalid header name"), "{err}");
9680 }
9681
9682 /// A fetch delivers the bytes that the remote stores. So a response is
9683 /// served only if it declares no coding, or declares `identity`. A value is
9684 /// a comma-separated list, and several headers state one list together. A
9685 /// token compares with no case and with no space around it.
9686 #[test]
9687 fn a_declared_content_coding_is_read_off_the_response() {
9688 let map = |values: &[&str]| {
9689 let mut headers = hyper::HeaderMap::new();
9690 for value in values {
9691 headers.append(
9692 hyper::header::CONTENT_ENCODING,
9693 HeaderValue::try_from(*value).unwrap(),
9694 );
9695 }
9696 headers
9697 };
9698
9699 // Nothing to undo: no header at all, an empty value, a value of
9700 // separators alone, and every spelling of the one coding that is served.
9701 for values in [
9702 vec![],
9703 vec![""],
9704 vec![","],
9705 vec!["identity"],
9706 vec!["IDENTITY"],
9707 vec![" identity "],
9708 vec!["identity", "identity"],
9709 ] {
9710 assert_eq!(declared_coding(&map(&values)), None, "{values:?}");
9711 }
9712
9713 // A coding that the body needs a decode from, named as the response
9714 // wrote it. A list with one coding refuses the whole response, at each
9715 // position of the coding. Several headers are read together, in the
9716 // order of arrival. A value whose tokens are all empty names nothing,
9717 // so it adds no separator to the message.
9718 for (values, named) in [
9719 (vec!["gzip"], "gzip"),
9720 (vec!["GZip"], "GZip"),
9721 (vec!["identity, gzip"], "identity, gzip"),
9722 (vec!["gzip, identity"], "gzip, identity"),
9723 (vec!["identity", "gzip"], "identity, gzip"),
9724 (vec!["gzip", "br"], "gzip, br"),
9725 (vec!["", "gzip"], "gzip"),
9726 (vec!["gzip", ""], "gzip"),
9727 (vec!["gzip", "", "br"], "gzip, br"),
9728 (vec!["gzip", ",", "br"], "gzip, br"),
9729 ] {
9730 assert_eq!(
9731 declared_coding(&map(&values)).as_deref(),
9732 Some(named),
9733 "{values:?}"
9734 );
9735 }
9736 }
9737
9738 /// Each request asks for no content coding. A configured header with a
9739 /// name that the fetcher sets replaces that entry, and does not join it on
9740 /// the wire.
9741 #[test]
9742 fn a_fetcher_header_replaces_the_entry_the_fetcher_sets() {
9743 let sent = |fetcher: &Fetcher, name: HeaderName| {
9744 fetcher
9745 .inner
9746 .headers
9747 .iter()
9748 .filter(|(held, _)| *held == name)
9749 .map(|(_, value)| value.to_str().unwrap().to_owned())
9750 .collect::<Vec<_>>()
9751 };
9752
9753 let fetcher = rt::block_on(Fetcher::new(direct_options("http://example.com"))).unwrap();
9754 assert_eq!(
9755 sent(&fetcher, hyper::header::ACCEPT_ENCODING),
9756 [IDENTITY.to_owned()]
9757 );
9758
9759 for name in ["accept-encoding", "user-agent"] {
9760 let options = FetcherOptions {
9761 headers: vec![(name.to_owned(), "caller".to_owned())],
9762 ..direct_options("http://example.com")
9763 };
9764 let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
9765 let header = HeaderName::from_static(name);
9766 assert_eq!(sent(&fetcher, header), ["caller".to_owned()], "{name}");
9767 }
9768
9769 // Two entries of one name both reach the wire. The first of them
9770 // replaces the entry that the fetcher sets.
9771 let options = FetcherOptions {
9772 headers: vec![
9773 ("accept-encoding".to_owned(), "one".to_owned()),
9774 ("Accept-Encoding".to_owned(), "two".to_owned()),
9775 ],
9776 ..direct_options("http://example.com")
9777 };
9778 let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
9779 assert_eq!(
9780 sent(&fetcher, hyper::header::ACCEPT_ENCODING),
9781 ["one".to_owned(), "two".to_owned()]
9782 );
9783 // A name under which the fetcher sets nothing also keeps both entries.
9784 let options = FetcherOptions {
9785 headers: vec![
9786 ("x-trace".to_owned(), "one".to_owned()),
9787 ("x-trace".to_owned(), "two".to_owned()),
9788 ],
9789 ..direct_options("http://example.com")
9790 };
9791 let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
9792 assert_eq!(
9793 sent(&fetcher, HeaderName::from_static("x-trace")),
9794 ["one".to_owned(), "two".to_owned()]
9795 );
9796 }
9797
9798 /// A credential is withheld from no destination. So one cleartext
9799 /// destination that a fetch can reach refuses it, and the message names
9800 /// the origin. A header that is not a credential reaches a cleartext
9801 /// destination.
9802 #[test]
9803 fn a_credential_refuses_a_cleartext_destination() {
9804 let credential = vec![(hyper::header::COOKIE, HeaderValue::from_static("session=1"))];
9805 let plain = vec![(
9806 HeaderName::from_static("x-trace"),
9807 HeaderValue::from_static("abc"),
9808 )];
9809 // A fetcher whose mirror list holds one cleartext entry among https
9810 // entries. The credential belongs to the request, so the construction
9811 // check of the list does not refuse it.
9812 let options = FetcherOptions {
9813 mirrors: vec![
9814 "https://secure.example/repo".to_owned(),
9815 "http://cleartext.example/repo".to_owned(),
9816 ],
9817 ..tls_options("unused")
9818 };
9819 let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
9820
9821 let mirrors = fetcher.route(Target::Path("summary")).unwrap();
9822 let err = fetcher.check_cleartext(&mirrors, &credential).unwrap_err();
9823 assert!(
9824 err.to_string().contains("http://cleartext.example"),
9825 "{err}"
9826 );
9827 fetcher.check_cleartext(&mirrors, &plain).unwrap();
9828
9829 let cleartext = fetcher
9830 .route(Target::Url("http://cleartext.example/p"))
9831 .unwrap();
9832 let err = fetcher
9833 .check_cleartext(&cleartext, &credential)
9834 .unwrap_err();
9835 assert!(
9836 err.to_string().contains("http://cleartext.example"),
9837 "{err}"
9838 );
9839 fetcher.check_cleartext(&cleartext, &plain).unwrap();
9840
9841 let secure = fetcher
9842 .route(Target::Url("https://secure.example/p"))
9843 .unwrap();
9844 fetcher.check_cleartext(&secure, &credential).unwrap();
9845 }
9846
9847 /// A handshake verifies the server certificate against a trust anchor. So
9848 /// if the fetcher holds none, a fetch of a TLS origin is refused before
9849 /// admission, and the message names the origin.
9850 ///
9851 /// A clear flag stands for a fetcher built on a host whose trust store
9852 /// holds nothing. The test sets the flag by hand, because this host has a
9853 /// CA bundle. `TrustRoots::Pem` fails the constructor over a blob that
9854 /// holds no certificate.
9855 #[test]
9856 fn a_tls_destination_needs_a_trust_anchor() {
9857 rt::block_on(async {
9858 let mut fetcher = Fetcher::new(direct_options("http://cleartext.example/repo"))
9859 .await
9860 .unwrap();
9861 Arc::get_mut(&mut fetcher.inner)
9862 .expect("the one handle on this fetcher")
9863 .has_trust_anchors = false;
9864
9865 // Nothing listens on port 1 of the loopback. So an attempt fails
9866 // its connect, and the fetcher tries again through each round and
9867 // each backoff. The refusal is definitive and takes no attempt, so
9868 // it resolves at once.
9869 let refused = within(
9870 Duration::from_secs(1),
9871 fetcher.fetch(FetchRequest::url("https://127.0.0.1:1/summary")),
9872 )
9873 .await;
9874 let err = refused
9875 .expect("the refusal takes no attempt")
9876 .expect_err("a tls url is refused without anchors");
9877 let message = err.to_string();
9878 assert!(message.contains("https://127.0.0.1:1"), "{message}");
9879 assert!(message.contains("no trust anchors"), "{message}");
9880
9881 // A cleartext destination opens no handshake, so it is served by
9882 // the same fetcher.
9883 let cleartext = fetcher
9884 .route(Target::Url("http://cleartext.example/summary"))
9885 .unwrap();
9886 fetcher.check_trust_anchors(&cleartext).unwrap();
9887 let mirrors = fetcher.route(Target::Path("summary")).unwrap();
9888 fetcher.check_trust_anchors(&mirrors).unwrap();
9889 });
9890 }
9891
9892 /// The constructor reads the host trust store only if a fetch can open a
9893 /// handshake. A fetcher whose mirrors are all `http`, and that follows no
9894 /// redirect, reads no store and holds no anchor. It refuses a URL target
9895 /// that names an `https` origin. An `https` mirror, an empty mirror list, and
9896 /// a redirect limit above zero each read the store.
9897 #[test]
9898 fn a_cleartext_fetcher_with_no_redirect_reads_no_trust_store() {
9899 let reads = || tls::SYSTEM_STORE_READS.with(std::cell::Cell::get);
9900 rt::block_on(async {
9901 let before = reads();
9902 let fetcher = Fetcher::new(FetcherOptions {
9903 max_redirects: 0,
9904 ..direct_options("http://cleartext.example/repo")
9905 })
9906 .await
9907 .unwrap();
9908 assert_eq!(reads(), before, "the store was read");
9909 assert!(!fetcher.inner.has_trust_anchors);
9910 let refused = within(
9911 Duration::from_secs(1),
9912 fetcher.fetch(FetchRequest::url("https://127.0.0.1:1/summary")),
9913 )
9914 .await
9915 .expect("the refusal takes no attempt")
9916 .expect_err("a tls url is refused without anchors");
9917 assert!(
9918 refused.to_string().contains("no trust anchors"),
9919 "{refused}"
9920 );
9921
9922 let cases = [
9923 direct_options("http://cleartext.example/repo"),
9924 FetcherOptions {
9925 max_redirects: 0,
9926 ..direct_options("https://tls.example/repo")
9927 },
9928 FetcherOptions {
9929 max_redirects: 0,
9930 proxy: Proxy::None,
9931 ..FetcherOptions::default()
9932 },
9933 ];
9934 for options in cases {
9935 let before = reads();
9936 let what = format!("{:?} {}", options.mirrors, options.max_redirects);
9937 // A host with no CA bundle fails the `https` cases, after the
9938 // read.
9939 let _ = Fetcher::new(options).await;
9940 assert_eq!(reads(), before + 1, "{what}");
9941 }
9942 });
9943 }
9944
9945 /// The server chooses the origin of a redirect. So a hop to a TLS origin
9946 /// gets the refusal that a route to a TLS origin gets. The fetcher holds
9947 /// nothing to verify the certificate against. With no refusal, the
9948 /// handshake fails retryably with a message about the peer, and spends
9949 /// each round and each backoff.
9950 ///
9951 /// The test sets the flag by hand, for the reason that
9952 /// `a_tls_destination_needs_a_trust_anchor` states.
9953 ///
9954 /// The two peers are raw sockets: one answers a redirect to the other, and
9955 /// the other reports how many connections reached it.
9956 #[test]
9957 fn a_redirect_to_a_tls_origin_needs_a_trust_anchor() {
9958 use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
9959 use std::sync::atomic::{AtomicUsize, Ordering};
9960
9961 rt::block_on(async {
9962 // The origin that the redirect names. Nothing connects to it, and
9963 // the count reports this.
9964 let tls_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
9965 .await
9966 .unwrap();
9967 let tls_port = tls_peer.local_addr().unwrap().port();
9968 let connections = Arc::new(AtomicUsize::new(0));
9969 let counted = connections.clone();
9970 drop(rt::spawn(async move {
9971 while let Ok((stream, _peer)) = tls_peer.accept().await {
9972 counted.fetch_add(1, Ordering::SeqCst);
9973 drop(stream);
9974 }
9975 }));
9976
9977 let cleartext_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
9978 .await
9979 .unwrap();
9980 let cleartext_port = cleartext_peer.local_addr().unwrap().port();
9981 let requests = Arc::new(AtomicUsize::new(0));
9982 let counted = requests.clone();
9983 drop(rt::spawn(async move {
9984 while let Ok((mut stream, _peer)) = cleartext_peer.accept().await {
9985 let mut request = [0u8; 1024];
9986 let _ = stream.read(&mut request).await;
9987 counted.fetch_add(1, Ordering::SeqCst);
9988 let answer = format!(
9989 "HTTP/1.1 302 Found\r\nLocation: https://127.0.0.1:{tls_port}/hopped\r\n\
9990 Content-Length: 0\r\n\r\n"
9991 );
9992 let _ = stream.write_all(answer.as_bytes()).await;
9993 let _ = stream.flush().await;
9994 }
9995 }));
9996
9997 let mut fetcher =
9998 Fetcher::new(direct_options(format!("http://127.0.0.1:{cleartext_port}")))
9999 .await
10000 .unwrap();
10001 Arc::get_mut(&mut fetcher.inner)
10002 .expect("the one handle on this fetcher")
10003 .has_trust_anchors = false;
10004
10005 // Six rounds of a retryable handshake failure and their backoffs
10006 // run for more than five seconds. So only a refusal that ends the
10007 // attempt resolves inside this window.
10008 let refused = within(
10009 Duration::from_secs(2),
10010 fetcher.fetch(FetchRequest::path("summary")),
10011 )
10012 .await;
10013 let err = refused
10014 .expect("the refusal ends the attempt")
10015 .expect_err("a tls hop is refused without anchors");
10016 let message = err.to_string();
10017 assert!(
10018 message.contains(&format!("https://127.0.0.1:{tls_port}")),
10019 "{message}"
10020 );
10021 assert!(message.contains("no trust anchors"), "{message}");
10022 assert_eq!(requests.load(Ordering::SeqCst), 1);
10023 assert_eq!(connections.load(Ordering::SeqCst), 0);
10024 });
10025 }
10026
10027 /// The reading end of a channel body, taken out of the body as an upload
10028 /// takes it.
10029 fn channel() -> (BodyEnd, UploadWriter) {
10030 let (body, writer) = UploadBody::channel();
10031 let UploadForm::Channel(end) = body.form else {
10032 panic!("a channel body holds its reading end");
10033 };
10034 (end, writer)
10035 }
10036
10037 /// The next frame of `end`, as the bytes it carries.
10038 async fn next_frame(end: &mut BodyEnd) -> Option<std::io::Result<Bytes>> {
10039 let frame = std::future::poll_fn(|cx| end.poll_frame(cx)).await?;
10040 Some(frame.map(|frame| frame.into_data().expect("an upload body yields data")))
10041 }
10042
10043 /// The writer hands the body over in frames of 64 KiB, a close hands over
10044 /// what is left, and the end follows the last frame. The close completes
10045 /// when the reading end gives the end.
10046 #[test]
10047 fn a_writer_hands_over_frames_of_64_kib() {
10048 rt::block_on(async {
10049 let (mut end, mut writer) = channel();
10050 let data = (0..150_000u32).map(|i| i as u8).collect::<Vec<_>>();
10051 let written = async {
10052 futures_lite::io::AsyncWriteExt::write_all(&mut writer, &data).await?;
10053 futures_lite::io::AsyncWriteExt::close(&mut writer).await
10054 };
10055 let read = async {
10056 let mut frames = Vec::new();
10057 while let Some(frame) = next_frame(&mut end).await {
10058 frames.push(frame.unwrap());
10059 }
10060 frames
10061 };
10062 let (written, frames) = futures_lite::future::zip(written, read).await;
10063 written.unwrap();
10064 assert_eq!(
10065 frames.iter().map(Bytes::len).collect::<Vec<_>>(),
10066 [UPLOAD_FRAME, UPLOAD_FRAME, 150_000 - 2 * UPLOAD_FRAME]
10067 );
10068 assert_eq!(frames.concat(), data);
10069 assert!(end.is_end_stream());
10070 assert!(end.exchange.lock().ended);
10071 assert_eq!(end.exchange.exact, None);
10072 });
10073 }
10074
10075 /// A flush hands over a part-filled frame, and completes when hyper takes
10076 /// it.
10077 #[test]
10078 fn a_flush_hands_over_a_part_filled_frame() {
10079 rt::block_on(async {
10080 let (mut end, mut writer) = channel();
10081 let flushed = async {
10082 futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"hello").await?;
10083 futures_lite::io::AsyncWriteExt::flush(&mut writer).await
10084 };
10085 let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
10086 flushed.unwrap();
10087 assert_eq!(frame.unwrap().unwrap(), &b"hello"[..]);
10088 assert!(!end.is_end_stream());
10089 });
10090 }
10091
10092 /// A writer reports the hand-over of its request, and a request given
10093 /// back unwritten is no longer handed over.
10094 #[test]
10095 fn a_writer_reports_the_hand_over() {
10096 let (end, writer) = channel();
10097 assert!(!writer.is_handed_over());
10098 end.exchange.hand_over(Duration::from_secs(1)).unwrap();
10099 assert!(writer.is_handed_over());
10100 end.exchange.withdraw();
10101 assert!(!writer.is_handed_over());
10102 }
10103
10104 /// A writer holds no buffer until its first write. A flush of less than
10105 /// 4 KiB hands over a copy and keeps the frame buffer. A larger flush
10106 /// hands the buffer over, and the next one is allocated at the next
10107 /// write.
10108 #[test]
10109 fn a_small_flush_hands_over_a_copy_and_keeps_the_buffer() {
10110 rt::block_on(async {
10111 let (mut end, mut writer) = channel();
10112 assert_eq!(writer.buffer.capacity(), 0);
10113 futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"small")
10114 .await
10115 .unwrap();
10116 assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
10117 let kept = writer.buffer.as_ptr();
10118 let flushed = futures_lite::io::AsyncWriteExt::flush(&mut writer);
10119 let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
10120 flushed.unwrap();
10121 assert_eq!(frame.unwrap().unwrap(), &b"small"[..]);
10122 assert!(writer.buffer.is_empty());
10123 assert_eq!(writer.buffer.as_ptr(), kept);
10124 assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
10125
10126 let large = vec![7u8; SMALL_FRAME];
10127 let flushed = async {
10128 futures_lite::io::AsyncWriteExt::write_all(&mut writer, &large).await?;
10129 futures_lite::io::AsyncWriteExt::flush(&mut writer).await
10130 };
10131 let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
10132 flushed.unwrap();
10133 assert_eq!(frame.unwrap().unwrap(), large);
10134 assert_eq!(writer.buffer.capacity(), 0);
10135 futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
10136 .await
10137 .unwrap();
10138 assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
10139 });
10140 }
10141
10142 /// A writer dropped before close fails the body, so hyper never reads a
10143 /// clean end for a body cut short.
10144 #[test]
10145 fn a_writer_dropped_unclosed_fails_the_body() {
10146 rt::block_on(async {
10147 let (mut end, mut writer) = channel();
10148 futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"part")
10149 .await
10150 .unwrap();
10151 drop(writer);
10152 let err = next_frame(&mut end).await.unwrap().unwrap_err();
10153 assert!(err.to_string().contains("dropped"), "{err}");
10154 assert!(!end.is_end_stream());
10155 assert!(!end.exchange.lock().ended);
10156 // The failure stands for every later poll.
10157 assert!(next_frame(&mut end).await.unwrap().is_err());
10158 });
10159 }
10160
10161 /// Once the reading end is gone, a write, a flush, and a close fail with
10162 /// a broken pipe.
10163 #[test]
10164 fn a_write_after_the_reading_end_is_gone_is_a_broken_pipe() {
10165 rt::block_on(async {
10166 let (end, mut writer) = channel();
10167 drop(end);
10168 let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"late")
10169 .await
10170 .unwrap_err();
10171 assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
10172 let err = futures_lite::io::AsyncWriteExt::flush(&mut writer)
10173 .await
10174 .unwrap_err();
10175 assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
10176 });
10177 }
10178
10179 /// A write after close is a broken pipe.
10180 #[test]
10181 fn a_write_after_close_is_a_broken_pipe() {
10182 rt::block_on(async {
10183 let (mut end, mut writer) = channel();
10184 let closed = futures_lite::io::AsyncWriteExt::close(&mut writer);
10185 let (closed, frame) = futures_lite::future::zip(closed, next_frame(&mut end)).await;
10186 closed.unwrap();
10187 assert!(frame.is_none());
10188 let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
10189 .await
10190 .unwrap_err();
10191 assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
10192 });
10193 }
10194
10195 /// A frame that waits in the slot past the stall window fails the write
10196 /// with a timeout, and fails the body. The failure is latched. Before
10197 /// an upload starts the window, a full slot is no stall.
10198 #[test]
10199 fn a_frame_not_taken_within_the_window_fails_the_write() {
10200 rt::block_on(async {
10201 let (mut end, mut writer) = channel();
10202 let frame = vec![0u8; UPLOAD_FRAME];
10203 // The first frame fills the buffer, the second hands it to the
10204 // slot, and the third waits for the slot.
10205 for _ in 0..2 {
10206 futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame)
10207 .await
10208 .unwrap();
10209 }
10210 let unbounded = within(
10211 Duration::from_millis(100),
10212 futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame),
10213 )
10214 .await;
10215 assert!(unbounded.is_none(), "a wait before the upload has no bound");
10216
10217 end.exchange.hand_over(Duration::from_millis(50)).unwrap();
10218 let started = Instant::now();
10219 let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame)
10220 .await
10221 .unwrap_err();
10222 assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
10223 assert!(started.elapsed() >= Duration::from_millis(50));
10224 let again = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
10225 .await
10226 .unwrap_err();
10227 assert_eq!(again.kind(), std::io::ErrorKind::TimedOut);
10228 let failed = next_frame(&mut end).await.unwrap().unwrap_err();
10229 assert!(failed.to_string().contains("not taken"), "{failed}");
10230 });
10231 }
10232
10233 /// A body given whole declares its length and travels in frames of 64 KiB
10234 /// cut from its bytes with no copy. It reaches its end with the last
10235 /// frame. An empty body is at its end at the hand-over. The hand-over
10236 /// reports this, so the request can declare a length of zero.
10237 #[test]
10238 fn a_whole_body_travels_in_frames_of_a_declared_length() {
10239 rt::block_on(async {
10240 let bytes = Bytes::from((0..150_000u32).map(|i| i as u8).collect::<Vec<_>>());
10241 let mut end = BodyEnd::whole(&bytes);
10242 assert_eq!(end.exchange.exact, Some(150_000));
10243 assert_eq!(end.exchange.hand_over(Duration::from_secs(60)), Ok(false));
10244 assert!(!end.is_end_stream());
10245 let mut at = 0;
10246 for len in [UPLOAD_FRAME, UPLOAD_FRAME, 150_000 - 2 * UPLOAD_FRAME] {
10247 assert!(!end.exchange.lock().ended);
10248 let frame = next_frame(&mut end).await.unwrap().unwrap();
10249 assert_eq!(frame.len(), len);
10250 assert_eq!(frame.as_ptr(), bytes[at..].as_ptr());
10251 at += len;
10252 }
10253 assert!(end.exchange.lock().ended);
10254 assert!(end.is_end_stream());
10255 assert!(next_frame(&mut end).await.is_none());
10256
10257 let empty = BodyEnd::whole(&Bytes::new());
10258 assert_eq!(empty.exchange.exact, Some(0));
10259 assert!(!empty.is_end_stream());
10260 assert_eq!(empty.exchange.hand_over(Duration::from_secs(60)), Ok(true));
10261 assert!(empty.is_end_stream());
10262 assert!(empty.exchange.lock().ended);
10263 });
10264 }
10265
10266 /// A channel body that reaches its end after the hand-over is framed as a
10267 /// stream: hyper learns of the end from its first poll.
10268 #[test]
10269 fn a_body_closed_after_the_hand_over_ends_at_the_first_poll() {
10270 rt::block_on(async {
10271 let (mut end, mut writer) = channel();
10272 assert_eq!(end.exchange.hand_over(Duration::from_secs(60)), Ok(false));
10273 end.exchange.lock().closed = true;
10274 assert!(!end.is_end_stream());
10275 assert!(next_frame(&mut end).await.is_none());
10276 assert!(end.is_end_stream());
10277 futures_lite::io::AsyncWriteExt::close(&mut writer)
10278 .await
10279 .unwrap();
10280 });
10281 }
10282
10283 /// The timer of a window whose end moves later is armed once, fires at
10284 /// the first end, and is armed again for the rest alone.
10285 #[test]
10286 fn a_lazy_timer_fires_at_the_end_it_was_moved_to() {
10287 rt::block_on(async {
10288 let mut timer = None;
10289 let started = Instant::now();
10290 let mut end = started + Duration::from_millis(50);
10291 std::future::poll_fn(|cx| {
10292 if poll_until(&mut timer, cx, end).is_pending() {
10293 end = started + Duration::from_millis(120);
10294 return Poll::Pending;
10295 }
10296 Poll::Ready(())
10297 })
10298 .await;
10299 assert!(started.elapsed() >= Duration::from_millis(120));
10300 assert!(timer.is_none());
10301 });
10302 }
10303
10304 /// A bearer token holds the token68 syntax, and a refusal names no part
10305 /// of it. The bearer and the Basic values are marked sensitive, and so is
10306 /// a credential header the caller sets.
10307 #[test]
10308 fn a_bearer_token_is_token68_and_sensitive() {
10309 let token = |token: &str| BearerToken {
10310 token: token.to_owned(),
10311 };
10312 for good in ["abc", "a-b.c_d~e+f/g", "dGVzdA==", "x="] {
10313 assert!(is_token68(good), "{good}");
10314 }
10315 for bad in ["", "=", "a b", "a=b", "tök", "a\n", "a,b"] {
10316 assert!(!is_token68(bad), "{bad:?}");
10317 let err = merge_headers(&[], &[], None, Some(&token(bad))).unwrap_err();
10318 let message = err.to_string();
10319 assert!(message.contains("token68"), "{message}");
10320 assert!(!message.contains(" "), "{message}");
10321 if !bad.is_empty() && bad != "=" {
10322 assert!(!message.contains(bad), "{message}");
10323 }
10324 }
10325
10326 let authorization = |headers: &[(HeaderName, HeaderValue)]| {
10327 headers
10328 .iter()
10329 .find(|(name, _)| *name == hyper::header::AUTHORIZATION)
10330 .map(|(_, value)| value.clone())
10331 .unwrap()
10332 };
10333 let merged = merge_headers(&[], &[], None, Some(&token("t0k3n"))).unwrap();
10334 let value = authorization(&merged);
10335 assert_eq!(value, "Bearer t0k3n");
10336 assert!(value.is_sensitive());
10337
10338 let auth = BasicAuth {
10339 user: "u".into(),
10340 password: "p".into(),
10341 };
10342 let merged = merge_headers(&[], &[], Some(&auth), None).unwrap();
10343 assert!(authorization(&merged).is_sensitive());
10344 let header = vec![("authorization".to_owned(), "Custom x".to_owned())];
10345 let merged = merge_headers(&[], &header, None, None).unwrap();
10346 assert!(authorization(&merged).is_sensitive());
10347
10348 let err = merge_headers(&[], &[], Some(&auth), Some(&token("t"))).unwrap_err();
10349 assert!(err.to_string().contains("pass one of them"), "{err}");
10350 assert!(err.to_string().contains("bearer token"), "{err}");
10351 let err = merge_headers(&[], &header, None, Some(&token("t"))).unwrap_err();
10352 assert!(err.to_string().contains("pass one of them"), "{err}");
10353 assert!(err.to_string().contains("bearer token"), "{err}");
10354 }
10355
10356 #[test]
10357 fn bearer_token_debug_holds_no_token() {
10358 let token = BearerToken {
10359 token: "s3cret".into(),
10360 };
10361 let rendered = format!("{token:?}");
10362 assert!(!rendered.contains("s3cret"), "{rendered}");
10363 assert!(rendered.contains("redacted"), "{rendered}");
10364 }
10365
10366 /// The bearer token of the fetcher is one sensitive `Authorization` entry
10367 /// in the header list. A request without a credential sends it. Each of
10368 /// these replaces it for one request: the `basic_auth` of the request, the
10369 /// `bearer_token` of the request, or an `Authorization` header of the
10370 /// request.
10371 #[test]
10372 fn a_fetcher_bearer_token_joins_the_header_list() {
10373 let options = FetcherOptions {
10374 bearer_token: Some(BearerToken {
10375 token: "t0k3n".into(),
10376 }),
10377 ..tls_options("https://example.com")
10378 };
10379 let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
10380 let authorization = |headers: &[(HeaderName, HeaderValue)]| {
10381 headers
10382 .iter()
10383 .filter(|(name, _)| *name == hyper::header::AUTHORIZATION)
10384 .map(|(_, value)| value.clone())
10385 .collect::<Vec<_>>()
10386 };
10387 let held = authorization(&fetcher.inner.headers);
10388 assert_eq!(held, ["Bearer t0k3n"]);
10389 assert!(held[0].is_sensitive());
10390
10391 let extra = vec![("x-trace".to_owned(), "abc".to_owned())];
10392 let merged = merge_headers(&fetcher.inner.headers, &extra, None, None).unwrap();
10393 assert_eq!(authorization(&merged), ["Bearer t0k3n"]);
10394
10395 // base64("u:p")
10396 let auth = BasicAuth {
10397 user: "u".into(),
10398 password: "p".into(),
10399 };
10400 let merged = merge_headers(&fetcher.inner.headers, &[], Some(&auth), None).unwrap();
10401 assert_eq!(authorization(&merged), ["Basic dTpw"]);
10402 let token = BearerToken {
10403 token: "other".into(),
10404 };
10405 let merged = merge_headers(&fetcher.inner.headers, &[], None, Some(&token)).unwrap();
10406 assert_eq!(authorization(&merged), ["Bearer other"]);
10407 let header = vec![("authorization".to_owned(), "Custom x".to_owned())];
10408 let merged = merge_headers(&fetcher.inner.headers, &header, None, None).unwrap();
10409 assert_eq!(authorization(&merged), ["Custom x"]);
10410 }
10411
10412 /// The constructor refuses the bearer token of the fetcher beside another
10413 /// value for `Authorization`, and a token outside the token68 syntax. A
10414 /// refusal names no part of the token.
10415 #[test]
10416 fn a_fetcher_bearer_token_is_refused_beside_another_credential_or_out_of_syntax() {
10417 let token = |token: &str| {
10418 Some(BearerToken {
10419 token: token.to_owned(),
10420 })
10421 };
10422 let beside_basic = FetcherOptions {
10423 bearer_token: token("t0k3n"),
10424 basic_auth: Some(BasicAuth {
10425 user: "u".into(),
10426 password: "p".into(),
10427 }),
10428 ..tls_options("https://example.com")
10429 };
10430 let beside_header = FetcherOptions {
10431 bearer_token: token("t0k3n"),
10432 headers: vec![("authorization".into(), "Basic aaa".into())],
10433 ..tls_options("https://example.com")
10434 };
10435 for options in [beside_basic, beside_header] {
10436 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
10437 let message = err.to_string();
10438 assert!(message.contains("bearer token"), "{message}");
10439 assert!(message.contains("pass one of them"), "{message}");
10440 }
10441
10442 let options = FetcherOptions {
10443 bearer_token: token("not a token"),
10444 ..tls_options("https://example.com")
10445 };
10446 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
10447 assert!(matches!(err, Error::Fetch(_)), "{err}");
10448 let message = err.to_string();
10449 assert!(message.contains("token68"), "{message}");
10450 assert!(!message.contains("not a token"), "{message}");
10451 }
10452
10453 /// A credential of the fetcher fails the constructor beside a cleartext
10454 /// mirror. The cleartext permission of the fetcher admits each kind of
10455 /// credential.
10456 #[test]
10457 fn the_fetcher_cleartext_permission_admits_a_cleartext_mirror() {
10458 let cleartext = "http://cleartext.example/repo";
10459 let token = || {
10460 Some(BearerToken {
10461 token: "t0k3n".into(),
10462 })
10463 };
10464 let options = FetcherOptions {
10465 bearer_token: token(),
10466 ..tls_options(cleartext)
10467 };
10468 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
10469 let message = err.to_string();
10470 assert!(message.contains("bearer token"), "{message}");
10471 assert!(message.contains(cleartext), "{message}");
10472 assert!(
10473 message.contains("FetcherOptions::allow_cleartext_credentials"),
10474 "{message}"
10475 );
10476 assert!(!message.contains("t0k3n"), "{message}");
10477
10478 let options = FetcherOptions {
10479 bearer_token: token(),
10480 allow_cleartext_credentials: true,
10481 ..tls_options(cleartext)
10482 };
10483 let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
10484 assert!(
10485 fetcher.inner.headers.iter().any(
10486 |(name, value)| name == hyper::header::AUTHORIZATION && value == "Bearer t0k3n"
10487 )
10488 );
10489
10490 let options = FetcherOptions {
10491 basic_auth: Some(BasicAuth {
10492 user: "u".into(),
10493 password: "p".into(),
10494 }),
10495 allow_cleartext_credentials: true,
10496 ..tls_options(cleartext)
10497 };
10498 rt::block_on(Fetcher::new(options)).unwrap();
10499 let options = FetcherOptions {
10500 headers: vec![("cookie".into(), "session=1".into())],
10501 allow_cleartext_credentials: true,
10502 ..tls_options(cleartext)
10503 };
10504 rt::block_on(Fetcher::new(options)).unwrap();
10505 }
10506
10507 /// A signer that returns one fixed header, or fails if it holds no header.
10508 #[derive(Debug)]
10509 struct FixedSigner {
10510 header: Option<(String, String)>,
10511 }
10512
10513 impl RequestSigner for FixedSigner {
10514 fn sign(&self, _request: &SignRequest<'_>) -> Result<Vec<(String, String)>> {
10515 match &self.header {
10516 Some(header) => Ok(vec![header.clone()]),
10517 None => Err(Error::Fetch("the signer has no key".into())),
10518 }
10519 }
10520 }
10521
10522 fn fixed_signer() -> Option<Arc<dyn RequestSigner>> {
10523 Some(Arc::new(FixedSigner {
10524 header: Some(("authorization".into(), "Fixed x".into())),
10525 }))
10526 }
10527
10528 /// The constructor refuses a signer beside another value for
10529 /// `Authorization`. A signer is a credential, so a cleartext mirror fails
10530 /// the constructor unless the fetcher permits it.
10531 #[test]
10532 fn a_signer_is_refused_beside_basic_auth_a_bearer_token_or_an_authorization_header() {
10533 let beside_basic = FetcherOptions {
10534 signer: fixed_signer(),
10535 basic_auth: Some(BasicAuth {
10536 user: "u".into(),
10537 password: "p".into(),
10538 }),
10539 ..tls_options("https://example.com")
10540 };
10541 let beside_bearer = FetcherOptions {
10542 signer: fixed_signer(),
10543 bearer_token: Some(BearerToken {
10544 token: "t0k3n".into(),
10545 }),
10546 ..tls_options("https://example.com")
10547 };
10548 let beside_header = FetcherOptions {
10549 signer: fixed_signer(),
10550 headers: vec![("Authorization".into(), "Basic aaa".into())],
10551 ..tls_options("https://example.com")
10552 };
10553 for (options, other) in [
10554 (beside_basic, "basic-auth credentials"),
10555 (beside_bearer, "a bearer token"),
10556 (beside_header, "an authorization header"),
10557 ] {
10558 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
10559 assert!(matches!(err, Error::Fetch(_)), "{err}");
10560 let message = err.to_string();
10561 assert!(message.contains("request signer"), "{message}");
10562 assert!(message.contains(other), "{message}");
10563 assert!(message.contains("pass one of them"), "{message}");
10564 }
10565
10566 // Another header goes beside the signer.
10567 let options = FetcherOptions {
10568 signer: fixed_signer(),
10569 headers: vec![("x-trace".into(), "abc".into())],
10570 ..tls_options("https://example.com")
10571 };
10572 rt::block_on(Fetcher::new(options)).unwrap();
10573
10574 let cleartext = "http://cleartext.example/repo";
10575 let options = FetcherOptions {
10576 signer: fixed_signer(),
10577 ..tls_options(cleartext)
10578 };
10579 let err = rt::block_on(Fetcher::new(options)).unwrap_err();
10580 let message = err.to_string();
10581 assert!(message.contains("request signer"), "{message}");
10582 assert!(message.contains(cleartext), "{message}");
10583 assert!(
10584 message.contains("FetcherOptions::allow_cleartext_credentials"),
10585 "{message}"
10586 );
10587 let options = FetcherOptions {
10588 signer: fixed_signer(),
10589 allow_cleartext_credentials: true,
10590 ..tls_options(cleartext)
10591 };
10592 rt::block_on(Fetcher::new(options)).unwrap();
10593 }
10594
10595 /// The request that a signer gets names the method, the authority of the
10596 /// `Host` header, and the path and the query of the request target.
10597 #[test]
10598 fn a_sign_request_carries_the_wire_authority_path_and_query() {
10599 let get = Method::GET;
10600 let put = Method::PUT;
10601
10602 // A mirror with a base path and the default port of its scheme.
10603 let mirror = parse_mirror("https://Example.com:443/base/repo/").unwrap();
10604 let hop = mirror.destination("objects/ab/cd.file", None);
10605 let request = sign_request(&get, &hop, SignPayload::Empty);
10606 assert_eq!(request.method, "GET");
10607 assert_eq!(request.authority, "Example.com");
10608 assert_eq!(request.authority, hop.authority.to_str().unwrap());
10609 assert_eq!(request.path, "/base/repo/objects/ab/cd.file");
10610 assert_eq!(request.query, None);
10611 assert_eq!(request.payload, SignPayload::Empty);
10612
10613 // A port other than the default, and a query.
10614 let mirror = parse_mirror("http://example.com:8080").unwrap();
10615 let hop = mirror.destination("summary", Some("x-id=1&b=%2F"));
10616 let request = sign_request(&get, &hop, SignPayload::Empty);
10617 assert_eq!(request.authority, "example.com:8080");
10618 assert_eq!(request.path, "/summary");
10619 assert_eq!(request.query, Some("x-id=1&b=%2F"));
10620
10621 // An IPv6 literal keeps its brackets. An empty query is not `None`.
10622 let body = b"abc";
10623 let hop = parse_url("https://[::1]:8443/a/b?").unwrap();
10624 let request = sign_request(&put, &hop, SignPayload::Bytes(body));
10625 assert_eq!(request.method, "PUT");
10626 assert_eq!(request.authority, "[::1]:8443");
10627 assert_eq!(request.path, "/a/b");
10628 assert_eq!(request.query, Some(""));
10629 assert_eq!(request.payload, SignPayload::Bytes(b"abc"));
10630 assert_eq!(format!("{:?}", request.payload), "Bytes(3)");
10631
10632 let hop = parse_url("https://[::1]/").unwrap();
10633 let request = sign_request(&put, &hop, SignPayload::Streamed);
10634 assert_eq!(request.authority, "[::1]");
10635 assert_eq!(request.path, "/");
10636 assert_eq!(request.query, None);
10637 }
10638
10639 /// A signer that gives each `+` of a request path as `%2B`, as a signer of
10640 /// a canonical path does.
10641 #[derive(Debug)]
10642 struct PlusSigner;
10643
10644 impl RequestSigner for PlusSigner {
10645 fn sign(&self, _request: &SignRequest<'_>) -> Result<Vec<(String, String)>> {
10646 Ok(Vec::new())
10647 }
10648
10649 fn request_path<'a>(&self, path: &'a str) -> Result<Cow<'a, str>> {
10650 Ok(Cow::Owned(path.replace('+', "%2B")))
10651 }
10652 }
10653
10654 /// The path of a path target goes through the signer, and the request
10655 /// target carries the form that the signer gives. The query does not.
10656 /// With no signer, or with a signer that keeps the default method, the
10657 /// path goes as written. A URL target goes as written with each signer.
10658 #[test]
10659 fn a_signer_gives_the_form_of_a_request_path() {
10660 rt::block_on(async {
10661 let cases: [(Option<Arc<dyn RequestSigner>>, &str); 3] = [
10662 (None, "/r/deltas/a+/b"),
10663 (fixed_signer(), "/r/deltas/a+/b"),
10664 (Some(Arc::new(PlusSigner)), "/r/deltas/a%2B/b"),
10665 ];
10666 for (signer, want) in cases {
10667 let fetcher = Fetcher::new(FetcherOptions {
10668 signer,
10669 allow_cleartext_credentials: true,
10670 ..direct_options("http://example.com/r")
10671 })
10672 .await
10673 .unwrap();
10674 let targets = [
10675 (Target::Path("deltas/a+/b"), want.to_owned()),
10676 (
10677 Target::PathQuery {
10678 path: "deltas/a+/b",
10679 query: "x=a+",
10680 },
10681 format!("{want}?x=a+"),
10682 ),
10683 ];
10684 for (target, wire) in targets {
10685 let Route::Mirrors { path, query } = fetcher.route(target).unwrap() else {
10686 panic!("a path target goes to the mirrors");
10687 };
10688 let destination = fetcher.inner.mirrors[0].destination(&path, query);
10689 let request = fetcher
10690 .build_request(
10691 &destination,
10692 &FetchRequest::for_target(target),
10693 &fetcher.inner.headers,
10694 Protocol::Http11,
10695 Via::Direct,
10696 )
10697 .unwrap();
10698 assert_eq!(request.uri(), wire.as_str(), "{target:?}");
10699 }
10700 let Route::One(destination) = fetcher
10701 .route(Target::Url("http://example.com/r/deltas/a+/b"))
10702 .unwrap()
10703 else {
10704 panic!("a url target names one destination");
10705 };
10706 assert_eq!(destination.target(), "/r/deltas/a+/b");
10707 }
10708 });
10709 }
10710
10711 /// The headers of a signer replace the headers of the same name, and each
10712 /// of their values is marked sensitive, whatever its name is. A refused
10713 /// header and an error of the signer end the request.
10714 #[test]
10715 fn signed_headers_replace_their_names_and_failures_are_final() {
10716 let fetcher = rt::block_on(Fetcher::new(FetcherOptions {
10717 headers: vec![("x-amz-date".into(), "old".into())],
10718 ..tls_options("https://example.com")
10719 }))
10720 .unwrap();
10721 let hop = parse_url("https://example.com/x").unwrap();
10722 let signer = FixedSigner {
10723 header: Some(("x-amz-date".into(), "new".into())),
10724 };
10725 let merged = signed(
10726 &signer,
10727 &Method::GET,
10728 &hop,
10729 SignPayload::Empty,
10730 &fetcher.inner.headers,
10731 )
10732 .ok()
10733 .unwrap();
10734 let dates = merged
10735 .iter()
10736 .filter(|(name, _)| name == "x-amz-date")
10737 .map(|(_, value)| value.to_str().unwrap())
10738 .collect::<Vec<_>>();
10739 assert_eq!(dates, ["new"]);
10740 for (name, value) in merged.iter() {
10741 assert_eq!(value.is_sensitive(), name == "x-amz-date", "{name}");
10742 }
10743
10744 // A header that is not a credential by its name is sensitive too, so
10745 // an HTTP/2 connection never indexes a session token.
10746 let signer = FixedSigner {
10747 header: Some(("X-Amz-Security-Token".into(), "session".into())),
10748 };
10749 let merged = signed(&signer, &Method::GET, &hop, SignPayload::Empty, &[])
10750 .ok()
10751 .unwrap();
10752 assert_eq!(merged.len(), 1);
10753 assert!(merged[0].1.is_sensitive());
10754
10755 let signer = FixedSigner {
10756 header: Some(("authorization".into(), "Fixed x".into())),
10757 };
10758 let merged = signed(&signer, &Method::GET, &hop, SignPayload::Empty, &[])
10759 .ok()
10760 .unwrap();
10761 assert!(merged[0].1.is_sensitive());
10762
10763 for signer in [
10764 FixedSigner { header: None },
10765 FixedSigner {
10766 header: Some(("host".into(), "elsewhere".into())),
10767 },
10768 ] {
10769 let failure = signed(&signer, &Method::GET, &hop, SignPayload::Empty, &[]);
10770 assert!(matches!(failure, Err(Failure::Final(Error::Fetch(_)))));
10771 }
10772 }
10773
10774 #[test]
10775 fn fetcher_options_debug_holds_no_bearer_token() {
10776 let options = FetcherOptions {
10777 bearer_token: Some(BearerToken {
10778 token: "s3cret".into(),
10779 }),
10780 ..FetcherOptions::default()
10781 };
10782 let rendered = format!("{options:?}");
10783 assert!(!rendered.contains("s3cret"), "{rendered}");
10784 assert!(rendered.contains("redacted"), "{rendered}");
10785 }
10786
10787 /// Headers whose values hold the marker `QXZ`, which no `Debug` output
10788 /// shows.
10789 fn secret_headers() -> Vec<(String, String)> {
10790 vec![
10791 ("Authorization".into(), "Basic val-QXZ-1".into()),
10792 ("proxy-authorization".into(), "Basic val-QXZ-2".into()),
10793 ("cookie".into(), "id=val-QXZ-3".into()),
10794 ("X-Trace".into(), "val-QXZ-4".into()),
10795 ]
10796 }
10797
10798 /// The `Debug` output of the headers of [`secret_headers`].
10799 const SECRET_HEADERS_SHOWN: &str = r#"[("Authorization", "<redacted>"), ("proxy-authorization", "<redacted>"), ("cookie", "<redacted>"), ("X-Trace", "<redacted>")]"#;
10800
10801 /// Checks that `rendered` shows each header of [`secret_headers`] with
10802 /// `<redacted>`, and no header value.
10803 fn assert_no_header_value(rendered: &str) {
10804 assert!(!rendered.contains("QXZ"), "{rendered}");
10805 for (name, _) in secret_headers() {
10806 let entry = format!(r#"("{name}", "<redacted>")"#);
10807 assert!(rendered.contains(&entry), "{rendered}");
10808 }
10809 }
10810
10811 /// The `Debug` output of the options shows each header name and no header
10812 /// value. Each other field shows as its own `Debug` shows it, in the order
10813 /// of declaration.
10814 #[test]
10815 fn fetcher_options_debug_holds_no_header_value() {
10816 let options = FetcherOptions {
10817 headers: secret_headers(),
10818 ..FetcherOptions::new("https://example.com/")
10819 };
10820 let rendered = format!("{options:?}");
10821 assert_no_header_value(&rendered);
10822 assert_eq!(
10823 rendered,
10824 format!(
10825 "FetcherOptions {{ mirrors: [\"https://example.com/\"], \
10826 headers: {SECRET_HEADERS_SHOWN}, basic_auth: None, bearer_token: None, \
10827 signer: None, allow_cleartext_credentials: false, \
10828 tls: TlsOptions {{ roots: System, client_identity: None }}, \
10829 proxy: Environment, http2: true, max_retries: 5, max_redirects: 10, \
10830 max_outstanding: 8, connect_timeout: 30s, progress_timeout: 60s, \
10831 low_speed: None, fetch_timeout: Some(300s) }}"
10832 )
10833 );
10834 }
10835
10836 /// The `Debug` output of a fetch request shows each header name and no
10837 /// header value. Each other field shows as its own `Debug` shows it.
10838 #[test]
10839 fn fetch_request_debug_holds_no_header_value() {
10840 let headers = secret_headers();
10841 let request = FetchRequest {
10842 headers: &headers,
10843 max_error_body: Some(4096),
10844 ..FetchRequest::path("summary")
10845 };
10846 let rendered = format!("{request:?}");
10847 assert_no_header_value(&rendered);
10848 assert_eq!(
10849 rendered,
10850 format!(
10851 "FetchRequest {{ target: Path(\"summary\"), priority: Normal, \
10852 validators: None, max_size: None, headers: {SECRET_HEADERS_SHOWN}, \
10853 basic_auth: None, allow_cleartext_credentials: false, \
10854 max_error_body: Some(4096) }}"
10855 )
10856 );
10857 }
10858
10859 /// The `Debug` output of a kept error response shows the name of each
10860 /// header and the length of the body. It shows no header value and no
10861 /// byte of the body, in the response and in the error that carries it.
10862 #[test]
10863 fn an_error_response_debug_holds_no_header_value_and_no_body() {
10864 let mut headers = hyper::HeaderMap::new();
10865 headers.insert(
10866 hyper::header::SET_COOKIE,
10867 HeaderValue::from_static("session=QXZ"),
10868 );
10869 let response = ErrorResponse::new(headers, Some(b"SECRETBODY".to_vec()));
10870 assert_eq!(
10871 format!("{response:?}"),
10872 "ErrorResponse { headers: [(\"set-cookie\", \"<redacted>\")], body: Some(10) }"
10873 );
10874 let error = Error::HttpStatus {
10875 status: 403,
10876 url: "https://h/x".into(),
10877 response: Some(Box::new(response)),
10878 };
10879 let rendered = format!("{error:?}");
10880 assert!(!rendered.contains("QXZ"), "{rendered}");
10881 assert!(!rendered.contains("SECRETBODY"), "{rendered}");
10882 assert_eq!(error.to_string(), "http status 403 for https://h/x");
10883 }
10884
10885 /// An error response gives back the headers and the body that it was
10886 /// built from.
10887 #[test]
10888 fn an_error_response_keeps_its_parts() {
10889 let mut headers = hyper::HeaderMap::new();
10890 headers.insert("x-amz-bucket-region", HeaderValue::from_static("eu-west-1"));
10891 let response = ErrorResponse::new(headers.clone(), Some(b"<Error/>".to_vec()));
10892 assert_eq!(response.headers(), &headers);
10893 assert_eq!(response.body(), Some(&b"<Error/>"[..]));
10894 let headless = ErrorResponse::new(hyper::HeaderMap::new(), None);
10895 assert!(headless.headers().is_empty());
10896 assert_eq!(headless.body(), None);
10897 }
10898
10899 /// A body of bytes has a copy that shares its buffer. A streamed body has
10900 /// no copy.
10901 #[test]
10902 fn a_bytes_body_clones_and_a_channel_body_does_not() {
10903 let body = UploadBody::bytes(b"part".to_vec());
10904 let copy = body.try_clone().expect("a bytes body has a copy");
10905 let (UploadForm::Bytes { bytes: first, .. }, UploadForm::Bytes { bytes: second, .. }) =
10906 (&body.form, ©.form)
10907 else {
10908 panic!("the copy of a bytes body is a bytes body");
10909 };
10910 assert_eq!(first, second);
10911 assert_eq!(first.as_ptr(), second.as_ptr());
10912 let (channel, _writer) = UploadBody::channel();
10913 assert!(channel.try_clone().is_none());
10914 }
10915
10916 /// A body of bytes gives its buffer back when no copy shares it. A
10917 /// shared body and a streamed body come back unchanged.
10918 #[test]
10919 fn a_bytes_body_gives_its_buffer_back_when_it_is_not_shared() {
10920 // A vector with spare capacity, and a vector with none.
10921 for mut bytes in [Vec::with_capacity(16), Vec::with_capacity(4)] {
10922 bytes.extend_from_slice(b"part");
10923 let (address, capacity) = (bytes.as_ptr(), bytes.capacity());
10924 let body = UploadBody::bytes(bytes);
10925 let copy = body.try_clone().expect("a bytes body has a copy");
10926 let Err(body) = body.into_vec() else {
10927 panic!("a shared body is not given back");
10928 };
10929 assert_eq!(body.as_bytes(), Some(&b"part"[..]));
10930 drop(copy);
10931 let Ok(bytes) = body.into_vec() else {
10932 panic!("a body with no copy gives its buffer back");
10933 };
10934 assert_eq!(bytes, b"part");
10935 assert_eq!(bytes.as_ptr(), address);
10936 assert_eq!(bytes.capacity(), capacity);
10937 }
10938 let (channel, _writer) = UploadBody::channel();
10939 let Err(channel) = channel.into_vec() else {
10940 panic!("a streamed body has no buffer");
10941 };
10942 assert!(channel.as_bytes().is_none());
10943 }
10944
10945 /// A body with a digest keeps the digest in a copy and in a body that
10946 /// is not given back. The buffer that comes back holds no digest. The
10947 /// `Debug` output of its payload shows the length of the body.
10948 #[test]
10949 fn a_body_with_a_digest_keeps_it_in_a_copy_and_gives_the_buffer_back() {
10950 let digest = [7u8; 32];
10951 let mut bytes = Vec::with_capacity(16);
10952 bytes.extend_from_slice(b"part");
10953 let (address, capacity) = (bytes.as_ptr(), bytes.capacity());
10954 let body = UploadBody::bytes_with_sha256(bytes, digest);
10955 assert_eq!(body.sha256(), Some(digest));
10956 assert_eq!(body.as_bytes(), Some(&b"part"[..]));
10957 assert_eq!(format!("{body:?}"), "Bytes(4)");
10958 let copy = body.try_clone().expect("a bytes body has a copy");
10959 assert_eq!(copy.sha256(), Some(digest));
10960 assert_eq!(copy.as_bytes(), Some(&b"part"[..]));
10961 let Err(body) = body.into_vec() else {
10962 panic!("a shared body is not given back");
10963 };
10964 assert_eq!(body.sha256(), Some(digest));
10965 drop(copy);
10966 let Ok(bytes) = body.into_vec() else {
10967 panic!("a body with no copy gives its buffer back");
10968 };
10969 assert_eq!(bytes, b"part");
10970 assert_eq!(bytes.as_ptr(), address);
10971 assert_eq!(bytes.capacity(), capacity);
10972 assert_eq!(UploadBody::bytes(bytes).sha256(), None);
10973 let (channel, _writer) = UploadBody::channel();
10974 assert_eq!(channel.sha256(), None);
10975
10976 let payload = SignPayload::Sha256 {
10977 bytes: b"abc",
10978 sha256: digest,
10979 };
10980 assert_eq!(format!("{payload:?}"), "Sha256(3)");
10981 assert_ne!(payload, SignPayload::Bytes(b"abc"));
10982 }
10983
10984 /// The `Debug` output of an upload request shows each header name and no
10985 /// header value. Each other field shows as its own `Debug` shows it.
10986 #[test]
10987 fn upload_request_debug_holds_no_header_value() {
10988 let headers = secret_headers();
10989 let request = UploadRequest {
10990 headers: &headers,
10991 ..UploadRequest::path("objects", UploadBody::bytes(Vec::new()))
10992 };
10993 let rendered = format!("{request:?}");
10994 assert_no_header_value(&rendered);
10995 assert_eq!(
10996 rendered,
10997 format!(
10998 "UploadRequest {{ target: Path(\"objects\"), method: Post, body: Bytes(0), \
10999 priority: Normal, max_response: 2097152, headers: {SECRET_HEADERS_SHOWN}, \
11000 basic_auth: None, bearer_token: None, allow_cleartext_credentials: false, \
11001 response_timeout: None }}"
11002 )
11003 );
11004 }
11005
11006 /// Starts a raw socket peer that answers each request with fixed headers,
11007 /// and gives a fetcher with the peer as its mirror, and the port of the
11008 /// peer.
11009 ///
11010 /// Each header value holds the marker `QXZ`.
11011 async fn fixed_header_peer() -> (Fetcher, u16) {
11012 use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
11013
11014 let peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
11015 .await
11016 .unwrap();
11017 let port = peer.local_addr().unwrap().port();
11018 drop(rt::spawn(async move {
11019 while let Ok((mut stream, _peer)) = peer.accept().await {
11020 let mut request = [0u8; 1024];
11021 let _ = stream.read(&mut request).await;
11022 let answer = "HTTP/1.1 200 OK\r\nSet-Cookie: a=val-QXZ-5\r\n\
11023 Set-Cookie: b=val-QXZ-6\r\nContent-Type: text/val-QXZ-7\r\n\
11024 Content-Length: 0\r\n\r\n";
11025 let _ = stream.write_all(answer.as_bytes()).await;
11026 let _ = stream.flush().await;
11027 }
11028 }));
11029
11030 // With no redirect and a cleartext mirror, the fetcher reads no system
11031 // trust store.
11032 let fetcher = Fetcher::new(FetcherOptions {
11033 max_redirects: 0,
11034 ..direct_options(format!("http://127.0.0.1:{port}"))
11035 })
11036 .await
11037 .unwrap();
11038 (fetcher, port)
11039 }
11040
11041 /// The `Debug` output of an upload answer shows the name of each response
11042 /// header, once for each value, and no header value.
11043 #[test]
11044 fn uploaded_debug_holds_no_header_value() {
11045 rt::block_on(async {
11046 let (fetcher, port) = fixed_header_peer().await;
11047 let uploaded = within(
11048 Duration::from_secs(5),
11049 fetcher.upload(UploadRequest::path(
11050 "objects",
11051 UploadBody::bytes(Vec::new()),
11052 )),
11053 )
11054 .await
11055 .expect("the upload ends within the limit")
11056 .unwrap();
11057 let rendered = format!("{uploaded:?}");
11058 assert!(!rendered.contains("QXZ"), "{rendered}");
11059 let headers = r#"[("set-cookie", "<redacted>"), ("set-cookie", "<redacted>"), ("content-type", "<redacted>"), ("content-length", "<redacted>")]"#;
11060 assert_eq!(
11061 rendered,
11062 format!(
11063 "Uploaded {{ status: 200, headers: {headers}, \
11064 url: \"http://127.0.0.1:{port}/objects\", body: Body {{ \
11065 protocol: Http11, content_length: Some(0), received: 0, .. }} }}"
11066 )
11067 );
11068 });
11069 }
11070
11071 /// The `Debug` output of an upload answer shows the host and the path of
11072 /// its URL, and `<redacted>` in place of the query.
11073 #[test]
11074 fn uploaded_debug_holds_no_url_query() {
11075 rt::block_on(async {
11076 let (fetcher, port) = fixed_header_peer().await;
11077 let url = format!("http://127.0.0.1:{port}/objects?X-Amz-Signature=sig-QXZ");
11078 let uploaded = within(
11079 Duration::from_secs(5),
11080 fetcher.upload(UploadRequest::url(&url, UploadBody::bytes(Vec::new()))),
11081 )
11082 .await
11083 .expect("the upload ends within the limit")
11084 .unwrap();
11085 assert_eq!(uploaded.url(), url);
11086 let rendered = format!("{uploaded:?}");
11087 assert!(!rendered.contains("QXZ"), "{rendered}");
11088 assert!(
11089 rendered.contains(&format!(
11090 "url: \"http://127.0.0.1:{port}/objects?<redacted>\""
11091 )),
11092 "{rendered}"
11093 );
11094 });
11095 }
11096
11097 /// For a text with no `@`, `?`, and `#`, the `Debug` output of a URL and
11098 /// of a path is the `Debug` output of the `str`.
11099 #[test]
11100 fn redacted_url_debug_quotes_as_str_debug() {
11101 let texts = [
11102 "https://example.com/it's",
11103 "a\"b\\c",
11104 "line\nnext\ttab\u{7f}",
11105 "caf\u{e9}",
11106 "\u{301}start",
11107 "mid\u{301}dle",
11108 "zero\u{200b}width",
11109 "emoji \u{1f980}",
11110 "",
11111 ];
11112 for text in texts {
11113 let expected = format!("{text:?}");
11114 assert_eq!(format!("{:?}", RedactedUrl::url(text)), expected);
11115 assert_eq!(format!("{:?}", RedactedUrl::path(text)), expected);
11116 }
11117 }
11118
11119 /// The `Debug` output of a URL removes the text up to the last `@` after
11120 /// the scheme, and shows `<redacted>` in place of a query and a fragment.
11121 /// A path keeps each `@`.
11122 #[test]
11123 fn redacted_url_debug_removes_userinfo_query_and_fragment() {
11124 let urls = [
11125 ("https://example.com/repo", "https://example.com/repo"),
11126 (
11127 "https://user:pw@example.com/repo",
11128 "https://example.com/repo",
11129 ),
11130 (
11131 "https://u:pa#ss@example.com/repo",
11132 "https://example.com/repo",
11133 ),
11134 (
11135 "https://u:pa?ss@example.com/repo",
11136 "https://example.com/repo",
11137 ),
11138 (
11139 "https://u:p/ss@example.com/repo",
11140 "https://example.com/repo",
11141 ),
11142 ("https://example.com/a@b/c", "https://b/c"),
11143 (
11144 "https://example.com/s?a=1",
11145 "https://example.com/s?<redacted>",
11146 ),
11147 (
11148 "https://example.com/s#f",
11149 "https://example.com/s#<redacted>",
11150 ),
11151 (
11152 "https://u:p@example.com/s?a=1#f",
11153 "https://example.com/s?<redacted>#<redacted>",
11154 ),
11155 ("https://example.com/s?", "https://example.com/s?<redacted>"),
11156 ("https://example.com/s#", "https://example.com/s#<redacted>"),
11157 (
11158 "https://example.com/s?#",
11159 "https://example.com/s?<redacted>#<redacted>",
11160 ),
11161 ("https://example.com/s?a=x@y&b=1", "https://y&b=1"),
11162 ("example.com/s?a=1", "example.com/s?<redacted>"),
11163 ("u:p@example.com/s", "example.com/s"),
11164 ("u:a://b@h/p", "h/p"),
11165 ("https://[::1]:8/p?q", "https://[::1]:8/p?<redacted>"),
11166 ("https://h/p#a?b", "https://h/p#<redacted>"),
11167 ("é@é?é#é", "é?<redacted>#<redacted>"),
11168 ];
11169 for (url, shown) in urls {
11170 assert_eq!(
11171 format!("{:?}", RedactedUrl::url(url)),
11172 format!("\"{shown}\"")
11173 );
11174 }
11175 let paths = [
11176 ("objects/ab", "objects/ab"),
11177 ("a@b/c", "a@b/c"),
11178 ("summary?sig=1", "summary?<redacted>"),
11179 ("summary#f", "summary#<redacted>"),
11180 ("summary?sig=1#f", "summary?<redacted>#<redacted>"),
11181 ];
11182 for (path, shown) in paths {
11183 assert_eq!(
11184 format!("{:?}", RedactedUrl::path(path)),
11185 format!("\"{shown}\"")
11186 );
11187 }
11188 }
11189
11190 /// The `Debug` output of a target alone shows the layout of a tuple
11191 /// variant, with the URL rule.
11192 #[test]
11193 fn target_debug_redacts_url_and_path() {
11194 let url = Target::Url("https://u:pw-QXZ@h/p?t=QXZ#QXZ");
11195 let path = Target::Path("summary?sig=QXZ#QXZ");
11196 assert_eq!(
11197 format!("{url:?}"),
11198 r#"Url("https://h/p?<redacted>#<redacted>")"#
11199 );
11200 assert_eq!(
11201 format!("{path:?}"),
11202 r#"Path("summary?<redacted>#<redacted>")"#
11203 );
11204 assert_eq!(
11205 format!("{url:#?}"),
11206 "Url(\n \"https://h/p?<redacted>#<redacted>\",\n)"
11207 );
11208 assert_eq!(
11209 format!("{path:#?}"),
11210 "Path(\n \"summary?<redacted>#<redacted>\",\n)"
11211 );
11212 let path_query = Target::PathQuery {
11213 path: "p?QXZ",
11214 query: "pattern=QXZ",
11215 };
11216 assert_eq!(
11217 format!("{path_query:?}"),
11218 r#"PathQuery { path: "p?<redacted>", query: "<redacted>" }"#
11219 );
11220 let rendered = format!("{:?}", FetchRequest::path_query("refs/v1", "pattern=QXZ"));
11221 assert!(!rendered.contains("QXZ"), "{rendered}");
11222 assert!(
11223 rendered.contains(r#"target: PathQuery { path: "refs/v1", query: "<redacted>" }"#),
11224 "{rendered}"
11225 );
11226 }
11227
11228 /// A URL that holds the marker `QXZ` in its userinfo, query, and fragment.
11229 const SECRET_URL: &str =
11230 "https://user-QXZ:pw-QXZ@example.com/repo?X-Amz-Signature=sig-QXZ#frag-QXZ";
11231
11232 /// The `Debug` output of the options shows the host and the path of each
11233 /// mirror, and no userinfo, query, or fragment.
11234 #[test]
11235 fn fetcher_options_debug_holds_no_mirror_secret() {
11236 let options = FetcherOptions {
11237 mirrors: vec![SECRET_URL.into(), "https://mirror.example.com/os".into()],
11238 ..FetcherOptions::default()
11239 };
11240 let rendered = format!("{options:?}");
11241 assert!(!rendered.contains("QXZ"), "{rendered}");
11242 assert!(
11243 rendered.contains(
11244 r#"mirrors: ["https://example.com/repo?<redacted>#<redacted>", "https://mirror.example.com/os"]"#
11245 ),
11246 "{rendered}"
11247 );
11248 }
11249
11250 /// The `Debug` output of a fetch request shows the host and the path of
11251 /// its target, and no userinfo, query, or fragment.
11252 #[test]
11253 fn fetch_request_debug_holds_no_target_secret() {
11254 let rendered = format!("{:?}", FetchRequest::url(SECRET_URL));
11255 assert!(!rendered.contains("QXZ"), "{rendered}");
11256 assert!(
11257 rendered.contains(r#"target: Url("https://example.com/repo?<redacted>#<redacted>")"#),
11258 "{rendered}"
11259 );
11260 let rendered = format!("{:?}", FetchRequest::path("summary?sig=QXZ#f"));
11261 assert!(!rendered.contains("QXZ"), "{rendered}");
11262 assert!(
11263 rendered.contains(r#"target: Path("summary?<redacted>#<redacted>")"#),
11264 "{rendered}"
11265 );
11266 }
11267
11268 /// The `Debug` output of an upload request shows the host and the path of
11269 /// its target, and no userinfo, query, or fragment.
11270 #[test]
11271 fn upload_request_debug_holds_no_target_secret() {
11272 let request = UploadRequest::url(SECRET_URL, UploadBody::bytes(Vec::new()));
11273 let rendered = format!("{request:?}");
11274 assert!(!rendered.contains("QXZ"), "{rendered}");
11275 assert!(
11276 rendered.contains(r#"target: Url("https://example.com/repo?<redacted>#<redacted>")"#),
11277 "{rendered}"
11278 );
11279 }
11280
11281 /// A kept error body with no declared length grows as its frames arrive,
11282 /// and its capacity never passes the cap. The first frame of 10,000 bytes
11283 /// and the frames of 16 KiB after it do not fall on the cap.
11284 #[test]
11285 fn a_kept_error_body_holds_no_capacity_past_the_cap() {
11286 use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
11287
11288 const CAP: usize = 100_000;
11289 rt::block_on(async {
11290 let peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
11291 .await
11292 .unwrap();
11293 let port = peer.local_addr().unwrap().port();
11294 drop(rt::spawn(async move {
11295 while let Ok((mut stream, _peer)) = peer.accept().await {
11296 let mut request = [0u8; 1024];
11297 let _ = stream.read(&mut request).await;
11298 let mut answer =
11299 b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec();
11300 let mut left = CAP - 1;
11301 let mut size = 10_000;
11302 while left > 0 {
11303 let n = size.min(left);
11304 answer.extend_from_slice(format!("{n:x}\r\n").as_bytes());
11305 answer.resize(answer.len() + n, b'e');
11306 answer.extend_from_slice(b"\r\n");
11307 left -= n;
11308 size = 16 * 1024;
11309 }
11310 answer.extend_from_slice(b"0\r\n\r\n");
11311 for piece in answer.chunks(size) {
11312 if stream.write_all(piece).await.is_err() || stream.flush().await.is_err() {
11313 break;
11314 }
11315 }
11316 }
11317 }));
11318 let fetcher = Fetcher::new(direct_options(format!("http://127.0.0.1:{port}")))
11319 .await
11320 .unwrap();
11321 let request = FetchRequest {
11322 max_error_body: Some(CAP as u64),
11323 ..FetchRequest::path("config")
11324 };
11325 let err = within(Duration::from_secs(10), fetcher.fetch(request))
11326 .await
11327 .expect("the fetch ends within the limit")
11328 .unwrap_err();
11329 let Error::HttpStatus {
11330 status: 404,
11331 response: Some(response),
11332 ..
11333 } = err
11334 else {
11335 panic!("{err}");
11336 };
11337 let body = response.body.as_ref().expect("the body is kept");
11338 assert_eq!(body.len(), CAP - 1);
11339 assert!(body.capacity() <= CAP, "capacity {}", body.capacity());
11340 });
11341 }
11342}