Skip to main content

day_part_http/
client.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The portable client (docs/http.md "Client").
5//!
6//! A [`Client`] owns the policy that must behave the same on every backend: following redirects,
7//! answering 401 and 407 challenges, the cookie jar, public-key pins, multipart bodies, total-time
8//! limits, and backpressure on response bodies. Beneath it a [`Transport`] performs one exchange
9//! at a time through the platform's own stack, which keeps TLS, trust stores, proxies, HTTP/2 and
10//! 3, and NTLM with the OS.
11//!
12//! Every asynchronous operation has a callback form (`*_async`) and a future form (`*_future`),
13//! per docs/async.md rule 3. Callbacks run on the thread the platform reports on; dropping a
14//! future, a [`Body`] or a [`WebSocket`] cancels what it stands for.
15
16use std::collections::VecDeque;
17use std::future::Future;
18use std::io::{Cursor, Read};
19use std::path::PathBuf;
20use std::pin::Pin;
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::{Arc, Mutex, MutexGuard, Weak};
23use std::task::{Context, Poll, Waker};
24use std::time::{Duration, SystemTime, UNIX_EPOCH};
25
26use day_async::TimerId;
27use sha2::{Digest, Sha256};
28
29use crate::{HttpError, Method, Request, Response};
30
31// ---------------------------------------------------------------------------
32// Client
33// ---------------------------------------------------------------------------
34
35/// Body chunks (or WebSocket messages) a reader keeps in hand, queued plus granted, before it
36/// stops asking the transport for more. A slow reader therefore slows the socket.
37const WINDOW: u32 = 4;
38/// The idle bound when neither the request nor the client sets one.
39pub(crate) const DEFAULT_IDLE: Duration = Duration::from_secs(30);
40const DEFAULT_QUESTION_TIMEOUT: Duration = Duration::from_secs(120);
41/// Credentials offered to one request before its 401 is delivered as the response.
42const MAX_AUTH_ATTEMPTS: u32 = 3;
43
44/// Lock, riding out poisoning: every state here is plain data whose invariants a panicking
45/// holder cannot break halfway.
46fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
47    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
48}
49
50/// A request body, as the builder recorded it.
51#[derive(Clone, Debug, Default)]
52pub(crate) enum Payload {
53    #[default]
54    Empty,
55    Bytes(Arc<Vec<u8>>),
56    File(PathBuf),
57    Stream(SharedReader, Option<u64>),
58    Form(Form),
59}
60
61/// An upload progress observer: `(bytes sent, total)`.
62#[derive(Clone)]
63pub(crate) struct ProgressFn(pub(crate) Arc<dyn Fn(u64, Option<u64>) + Send + Sync>);
64
65impl std::fmt::Debug for ProgressFn {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        f.write_str("ProgressFn")
68    }
69}
70
71/// Whether a client follows redirects.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum Redirects {
74    /// Follow at most this many, then fail with [`HttpError::TooManyRedirects`].
75    Follow(u32),
76    /// Deliver each redirect response as the response.
77    Never,
78}
79
80impl Default for Redirects {
81    fn default() -> Self {
82        Redirects::Follow(10)
83    }
84}
85
86/// A redirect the client is about to follow, as [`ClientBuilder::on_redirect`] sees it.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct Hop {
89    pub status: u16,
90    pub from: String,
91    pub to: String,
92    /// The method the next request uses: a 303 turns anything but HEAD into GET, and a 301 or
93    /// 302 turns a POST into a GET.
94    pub method: String,
95    /// Redirects already followed on the way here.
96    pub followed: u32,
97}
98
99/// An HTTP authentication challenge, as [`ClientBuilder::on_challenge`] sees it.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct Challenge {
102    pub url: String,
103    pub host: String,
104    pub port: u16,
105    pub realm: Option<String>,
106    pub scheme: Scheme,
107    /// A proxy asked (407), not the origin server.
108    pub proxy: bool,
109    /// Credentials this request already offered that the server refused.
110    pub previous_failures: u32,
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
114enum Resolution {
115    Default,
116    Follow,
117    Stop,
118    Credential { user: String, password: String },
119    Bearer(String),
120    Cancel,
121    Accept,
122    Reject,
123}
124
125/// The half of a question a handler answers. Dropping it unanswered takes the default.
126struct ReplyGrip {
127    flight: Weak<Flight>,
128    ask: u64,
129    answered: bool,
130}
131
132impl ReplyGrip {
133    fn answer(mut self, resolution: Resolution) {
134        self.answered = true;
135        if let Some(flight) = self.flight.upgrade() {
136            flight.resolve(self.ask, resolution);
137        }
138    }
139}
140
141impl Drop for ReplyGrip {
142    fn drop(&mut self) {
143        if let (false, Some(flight)) = (self.answered, self.flight.upgrade()) {
144            flight.resolve(self.ask, Resolution::Default);
145        }
146    }
147}
148
149/// Answers a redirect question. Dropping it unanswered follows the redirect. It is `Send`, so a
150/// handler may keep it and answer later from any thread; the exchange waits meanwhile, up to the
151/// client's question timeout.
152pub struct RedirectReply(ReplyGrip);
153
154impl RedirectReply {
155    /// Follow the redirect.
156    pub fn follow(self) {
157        self.0.answer(Resolution::Follow);
158    }
159
160    /// Do not follow: the redirect response is the response.
161    pub fn stop(self) {
162        self.0.answer(Resolution::Stop);
163    }
164
165    /// Abandon the request; it fails with [`HttpError::Cancelled`].
166    pub fn cancel(self) {
167        self.0.answer(Resolution::Cancel);
168    }
169}
170
171impl std::fmt::Debug for RedirectReply {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.write_str("RedirectReply")
174    }
175}
176
177/// Answers a challenge. Dropping it unanswered delivers the 401 (or 407) as the response.
178pub struct ChallengeReply(ReplyGrip);
179
180impl ChallengeReply {
181    /// Answer with a user name and password. The client writes Basic or Digest to match the
182    /// challenge; a platform stack answering NTLM or Negotiate itself takes them as they are.
183    pub fn credential(self, user: impl Into<String>, password: impl Into<String>) {
184        self.0.answer(Resolution::Credential {
185            user: user.into(),
186            password: password.into(),
187        });
188    }
189
190    /// Answer with a bearer token.
191    pub fn bearer(self, token: impl Into<String>) {
192        self.0.answer(Resolution::Bearer(token.into()));
193    }
194
195    /// Offer nothing: the challenge response is the response.
196    pub fn default_handling(self) {
197        self.0.answer(Resolution::Default);
198    }
199
200    /// Abandon the request; it fails with [`HttpError::Cancelled`].
201    pub fn cancel(self) {
202        self.0.answer(Resolution::Cancel);
203    }
204}
205
206impl std::fmt::Debug for ChallengeReply {
207    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208        f.write_str("ChallengeReply")
209    }
210}
211
212/// Answers a server trust question. Dropping it unanswered keeps the platform's verdict.
213pub struct TrustReply(ReplyGrip);
214
215impl TrustReply {
216    /// Trust the server, whatever the platform concluded.
217    pub fn accept(self) {
218        self.0.answer(Resolution::Accept);
219    }
220
221    /// Refuse the server; the request fails with [`HttpError::Tls`].
222    pub fn reject(self) {
223        self.0.answer(Resolution::Reject);
224    }
225
226    /// Keep the platform's verdict.
227    pub fn default_handling(self) {
228        self.0.answer(Resolution::Default);
229    }
230}
231
232impl std::fmt::Debug for TrustReply {
233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        f.write_str("TrustReply")
235    }
236}
237
238type RedirectHandler = dyn Fn(&Hop, RedirectReply) + Send + Sync;
239type ChallengeHandler = dyn Fn(&Challenge, ChallengeReply) + Send + Sync;
240type TrustHandler = dyn Fn(&ServerTrust, TrustReply) + Send + Sync;
241
242/// Which servers a client trusts beyond the platform's own evaluation.
243#[derive(Clone, Debug, Default, PartialEq, Eq)]
244pub struct Trust {
245    pins: Vec<(String, Option<[u8; 32]>)>,
246}
247
248impl Trust {
249    /// The platform's evaluation alone.
250    pub fn system() -> Trust {
251        Trust::default()
252    }
253
254    /// Require `host`'s certificate chain to hold a key whose SHA-256 is `pin`, written
255    /// `sha256/<base64>` as [`ServerTrust::pins`] prints it. `*.example.com` covers every
256    /// subdomain. Several pins for one host accept any of them, which is how a key rotation
257    /// ships. A malformed pin matches nothing, so its host fails closed.
258    #[must_use]
259    pub fn pin(mut self, host: impl Into<String>, pin: &str) -> Trust {
260        self.pins
261            .push((host.into().to_ascii_lowercase(), parse_pin(pin)));
262        self
263    }
264
265    /// Whether any pin is configured.
266    #[must_use]
267    pub fn is_empty(&self) -> bool {
268        self.pins.is_empty()
269    }
270
271    fn pins_for(&self, host: &str) -> Option<Vec<Option<[u8; 32]>>> {
272        let host = host.to_ascii_lowercase();
273        let pins: Vec<_> = self
274            .pins
275            .iter()
276            .filter(|(pattern, _)| host_matches(pattern, &host))
277            .map(|(_, pin)| *pin)
278            .collect();
279        (!pins.is_empty()).then_some(pins)
280    }
281}
282
283fn host_matches(pattern: &str, host: &str) -> bool {
284    match pattern.strip_prefix("*.") {
285        Some(base) => {
286            host.len() > base.len() + 1
287                && host.ends_with(base)
288                && host.as_bytes()[host.len() - base.len() - 1] == b'.'
289        }
290        None => pattern == host,
291    }
292}
293
294/// A client certificate identity, presented when a server asks for one.
295#[derive(Clone)]
296pub struct Identity {
297    pub(crate) pkcs12: Arc<Vec<u8>>,
298    pub(crate) password: String,
299}
300
301impl Identity {
302    /// A PKCS#12 archive (`.p12`, `.pfx`) holding the certificate and its private key.
303    pub fn pkcs12(der: Vec<u8>, password: impl Into<String>) -> Identity {
304        Identity {
305            pkcs12: Arc::new(der),
306            password: password.into(),
307        }
308    }
309}
310
311impl std::fmt::Debug for Identity {
312    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313        f.debug_struct("Identity")
314            .field("pkcs12_bytes", &self.pkcs12.len())
315            .finish_non_exhaustive()
316    }
317}
318
319/// Where a client keeps cookies.
320#[derive(Clone, Debug)]
321pub enum Cookies {
322    /// The platform's store: `HTTPCookieStorage` on Apple, the browser's jar on the web. Where
323    /// the platform offers none to share ([`Capabilities::platform_cookies`]), an in-memory
324    /// [`CookieJar`].
325    Platform,
326    /// This jar, which the client reads and writes itself.
327    Jar(Arc<CookieJar>),
328    /// Send none and keep none.
329    Off,
330}
331
332impl Cookies {
333    /// A fresh in-memory jar.
334    #[must_use]
335    pub fn jar() -> Cookies {
336        Cookies::Jar(Arc::new(CookieJar::new()))
337    }
338
339    /// A jar persisted to `file`: cookies with an expiry survive a relaunch.
340    pub fn jar_at(file: impl Into<PathBuf>) -> Cookies {
341        Cookies::Jar(Arc::new(CookieJar::open(file)))
342    }
343}
344
345impl Default for Cookies {
346    /// The platform store on Apple and the web, an in-memory jar elsewhere.
347    fn default() -> Self {
348        if cfg!(any(
349            target_os = "macos",
350            target_os = "ios",
351            target_arch = "wasm32"
352        )) {
353            Cookies::Platform
354        } else {
355            Cookies::jar()
356        }
357    }
358}
359
360/// Whether a client keeps an HTTP cache.
361#[derive(Clone, Copy, Debug, PartialEq, Eq)]
362pub enum Cache {
363    /// The platform's cache with these capacities in bytes, where it has one
364    /// ([`Capabilities::platform_cache`]).
365    Platform { memory: u64, disk: u64 },
366    /// No cache.
367    Off,
368}
369
370impl Cache {
371    /// The platform cache at 8 MiB in memory and 64 MiB on disk.
372    #[must_use]
373    pub fn platform() -> Cache {
374        Cache::Platform {
375            memory: 8 << 20,
376            disk: 64 << 20,
377        }
378    }
379}
380
381impl Default for Cache {
382    fn default() -> Self {
383        Cache::platform()
384    }
385}
386
387/// Configures a [`Client`].
388#[must_use]
389pub struct ClientBuilder {
390    timeout_idle: Duration,
391    timeout_total: Option<Duration>,
392    redirects: Redirects,
393    on_redirect: Option<Arc<RedirectHandler>>,
394    on_challenge: Option<Arc<ChallengeHandler>>,
395    on_server_trust: Option<Arc<TrustHandler>>,
396    trust: Trust,
397    identity: Option<Identity>,
398    cookies: Cookies,
399    cache: Cache,
400    headers: Vec<(String, String)>,
401    max_per_host: Option<u32>,
402    wait_for_connectivity: bool,
403    question_timeout: Duration,
404    transport: Option<Arc<dyn Transport>>,
405    session: Option<crate::Session>,
406}
407
408impl Default for ClientBuilder {
409    fn default() -> Self {
410        ClientBuilder {
411            timeout_idle: DEFAULT_IDLE,
412            timeout_total: None,
413            redirects: Redirects::default(),
414            on_redirect: None,
415            on_challenge: None,
416            on_server_trust: None,
417            trust: Trust::system(),
418            identity: None,
419            cookies: Cookies::default(),
420            cache: Cache::default(),
421            headers: Vec::new(),
422            max_per_host: None,
423            wait_for_connectivity: false,
424            question_timeout: DEFAULT_QUESTION_TIMEOUT,
425            transport: None,
426            session: None,
427        }
428    }
429}
430
431impl std::fmt::Debug for ClientBuilder {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        f.debug_struct("ClientBuilder")
434            .field("redirects", &self.redirects)
435            .field("cookies", &self.cookies)
436            .field("cache", &self.cache)
437            .finish_non_exhaustive()
438    }
439}
440
441impl ClientBuilder {
442    /// How long an exchange may sit without progress, for requests that set no
443    /// [`Request::timeout`]. Default 30 s.
444    pub fn timeout_idle(mut self, limit: Duration) -> Self {
445        self.timeout_idle = limit;
446        self
447    }
448
449    /// How long a whole request may take, redirects, challenges and body included. Default
450    /// none. A request's own [`Request::timeout_total`] wins.
451    pub fn timeout_total(mut self, limit: Duration) -> Self {
452        self.timeout_total = Some(limit);
453        self
454    }
455
456    /// Whether to follow redirects. Default [`Redirects::Follow`]`(10)`.
457    pub fn redirects(mut self, redirects: Redirects) -> Self {
458        self.redirects = redirects;
459        self
460    }
461
462    /// Ask before following each redirect. Needs [`Capabilities::manual_redirects`]; where the
463    /// platform follows redirects itself, requests from this client fail with
464    /// [`HttpError::Unsupported`].
465    pub fn on_redirect(
466        mut self,
467        handler: impl Fn(&Hop, RedirectReply) + Send + Sync + 'static,
468    ) -> Self {
469        self.on_redirect = Some(Arc::new(handler));
470        self
471    }
472
473    /// Answer authentication challenges. Without a handler a 401 or 407 is delivered as the
474    /// response.
475    pub fn on_challenge(
476        mut self,
477        handler: impl Fn(&Challenge, ChallengeReply) + Send + Sync + 'static,
478    ) -> Self {
479        self.on_challenge = Some(Arc::new(handler));
480        self
481    }
482
483    /// Public-key pins, checked on top of the platform's evaluation.
484    pub fn trust(mut self, trust: Trust) -> Self {
485        self.trust = trust;
486        self
487    }
488
489    /// Decide on servers the platform does not trust, or confirm the ones it does. Needs
490    /// [`Capabilities::server_trust`].
491    pub fn on_server_trust(
492        mut self,
493        handler: impl Fn(&ServerTrust, TrustReply) + Send + Sync + 'static,
494    ) -> Self {
495        self.on_server_trust = Some(Arc::new(handler));
496        self
497    }
498
499    /// Present this identity when a server asks for a client certificate. Needs
500    /// [`Capabilities::client_identity`].
501    pub fn identity(mut self, identity: Identity) -> Self {
502        self.identity = Some(identity);
503        self
504    }
505
506    /// Where to keep cookies. Default [`Cookies::default`].
507    pub fn cookies(mut self, cookies: Cookies) -> Self {
508        self.cookies = cookies;
509        self
510    }
511
512    /// Whether to keep an HTTP cache. Default [`Cache::platform`].
513    pub fn cache(mut self, cache: Cache) -> Self {
514        self.cache = cache;
515        self
516    }
517
518    /// A header sent with every request that does not set it itself.
519    pub fn header(mut self, name: &str, value: &str) -> Self {
520        self.headers.push((name.to_string(), value.to_string()));
521        self
522    }
523
524    /// The `User-Agent` sent with every request.
525    pub fn user_agent(self, agent: &str) -> Self {
526        self.header("User-Agent", agent)
527    }
528
529    /// At most this many connections to one host, where the platform lets an app choose.
530    pub fn max_per_host(mut self, limit: u32) -> Self {
531        self.max_per_host = Some(limit.max(1));
532        self
533    }
534
535    /// Wait for a usable network instead of failing at once, where the platform can
536    /// ([`Capabilities::wait_for_connectivity`]).
537    pub fn wait_for_connectivity(mut self, wait: bool) -> Self {
538        self.wait_for_connectivity = wait;
539        self
540    }
541
542    /// How long a handler may hold a question before its default answer is taken. Default two
543    /// minutes.
544    pub fn question_timeout(mut self, limit: Duration) -> Self {
545        self.question_timeout = limit;
546        self
547    }
548
549    /// Route through an isolated session. By default clients follow `Session::global()`.
550    /// An explicit `transport` overrides provider/interception selection for this client.
551    pub fn session(mut self, session: crate::Session) -> Self {
552        self.session = Some(session);
553        self
554    }
555
556    /// Perform exchanges through this transport instead of the platform's: a test double, or
557    /// an app's own stack.
558    pub fn transport(mut self, transport: impl Transport) -> Self {
559        self.transport = Some(Arc::new(transport));
560        self
561    }
562
563    /// The client.
564    pub fn build(self) -> Client {
565        let caps = match &self.transport {
566            Some(t) => t.capabilities(),
567            None => crate::platform_capabilities(),
568        };
569        let cookies = match self.cookies {
570            Cookies::Platform if !caps.platform_cookies => Cookies::jar(),
571            other => other,
572        };
573        let config = TransportConfig {
574            timeout_idle: self.timeout_idle,
575            timeout_total: self.timeout_total,
576            platform_cookies: matches!(cookies, Cookies::Platform),
577            platform_cache: match self.cache {
578                Cache::Platform { memory, disk } => Some((memory, disk)),
579                Cache::Off => None,
580            },
581            redirects: self.redirects,
582            ask_auth: self.on_challenge.is_some(),
583            ask_trust: self.on_server_trust.is_some() || !self.trust.is_empty(),
584            identity: self.identity,
585            max_per_host: self.max_per_host,
586            wait_for_connectivity: self.wait_for_connectivity,
587        };
588        let session = if self.transport.is_some() {
589            None
590        } else {
591            Some(self.session.unwrap_or_else(crate::Session::global))
592        };
593        let transport = match self.transport {
594            Some(t) => t,
595            None => crate::platform_transport(&config),
596        };
597        Client {
598            inner: Arc::new(ClientInner {
599                session,
600                config,
601                clock: None,
602                provider_cache: Arc::new(Mutex::new(None)),
603                fallback_cookies: Cookies::jar(),
604                caps: transport.capabilities(),
605                transport,
606                timeout_idle: self.timeout_idle,
607                timeout_total: self.timeout_total,
608                redirects: self.redirects,
609                on_redirect: self.on_redirect,
610                on_challenge: self.on_challenge,
611                on_server_trust: self.on_server_trust,
612                trust: self.trust,
613                cookies,
614                headers: self.headers,
615                question_timeout: self.question_timeout,
616                credentials: Arc::new(Mutex::new(Vec::new())),
617            }),
618        }
619    }
620}
621
622/// An HTTP client: policy shared by every request it sends, over the platform's transport.
623/// Cloning is cheap and shares the policy, the cookies and the connections.
624#[derive(Clone)]
625pub struct Client {
626    inner: Arc<ClientInner>,
627}
628
629type ProviderCache = Arc<Mutex<Option<(u64, Arc<dyn Transport>)>>>;
630type Credentials = Arc<Mutex<Vec<(String, Option<String>, Resolution)>>>;
631
632#[derive(Clone)]
633struct ClientInner {
634    session: Option<crate::Session>,
635    config: TransportConfig,
636    clock: Option<Arc<dyn crate::simulation::Clock>>,
637    provider_cache: ProviderCache,
638    fallback_cookies: Cookies,
639    transport: Arc<dyn Transport>,
640    caps: Capabilities,
641    timeout_idle: Duration,
642    timeout_total: Option<Duration>,
643    redirects: Redirects,
644    on_redirect: Option<Arc<RedirectHandler>>,
645    on_challenge: Option<Arc<ChallengeHandler>>,
646    on_server_trust: Option<Arc<TrustHandler>>,
647    trust: Trust,
648    cookies: Cookies,
649    headers: Vec<(String, String)>,
650    question_timeout: Duration,
651    /// Credentials that worked, by origin and realm, offered again without asking.
652    credentials: Credentials,
653}
654
655impl std::fmt::Debug for Client {
656    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
657        f.debug_struct("Client")
658            .field("capabilities", &self.inner.caps)
659            .field("redirects", &self.inner.redirects)
660            .field("cookies", &self.inner.cookies)
661            .finish_non_exhaustive()
662    }
663}
664
665impl Default for Client {
666    fn default() -> Self {
667        Client::new()
668    }
669}
670
671impl Client {
672    /// A client with the default policy over the platform's transport.
673    #[must_use]
674    pub fn new() -> Client {
675        ClientBuilder::default().build()
676    }
677
678    /// Configure a client.
679    pub fn builder() -> ClientBuilder {
680        ClientBuilder::default()
681    }
682
683    /// What this client's transport can do.
684    #[must_use]
685    pub fn capabilities(&self) -> Capabilities {
686        self.inner.current_transport().capabilities()
687    }
688
689    /// Send `request`; `on_head` receives the response head with its unread [`Body`], or the
690    /// failure. It runs on the thread the platform reports on.
691    pub fn send_async(
692        &self,
693        request: Request,
694        on_head: impl FnOnce(Result<Streaming, HttpError>) + Send + 'static,
695    ) -> InFlight {
696        InFlight(Arc::downgrade(&Flight::start(
697            &self.inner,
698            request,
699            Box::new(on_head),
700        )))
701    }
702
703    /// Send `request` and await the response head. Dropping the future cancels the request.
704    #[must_use]
705    pub fn send_future(&self, request: Request) -> Sending {
706        let (tx, rx) = day_async::oneshot();
707        let flight = Flight::start(&self.inner, request, Box::new(move |r| tx.send(r)));
708        Sending {
709            flight,
710            rx,
711            done: false,
712        }
713    }
714
715    /// Buffer at most `max_bytes`, cancelling if either Content-Length or the actual streamed
716    /// body exceeds it. The bound applies to decoded response bytes delivered by the transport.
717    ///
718    /// # Errors
719    ///
720    /// [`HttpError::BodyTooLarge`] when the advertised or received body exceeds `max_bytes`, and
721    /// otherwise the [`HttpError`] the request or its body stream fails with.
722    pub async fn fetch_limited_future(
723        &self,
724        request: Request,
725        max_bytes: usize,
726    ) -> Result<Response, HttpError> {
727        self.fetch_limited_with_progress_future(request, max_bytes, |_, _| {})
728            .await
729    }
730
731    /// Bounded download with `(received, total)` observations on the polling thread.
732    /// Unknown or encoded representation lengths report None, never a guessed fraction.
733    /// Observer calls occur at connection start, response headers, and each body chunk;
734    /// UI consumers should throttle their presentation updates.
735    ///
736    /// # Errors
737    ///
738    /// [`HttpError::BodyTooLarge`] when the advertised or received body exceeds `max_bytes`, and
739    /// otherwise the [`HttpError`] the request or its body stream fails with.
740    pub async fn fetch_limited_with_progress_future(
741        &self,
742        request: Request,
743        max_bytes: usize,
744        mut progress: impl FnMut(u64, Option<u64>),
745    ) -> Result<Response, HttpError> {
746        progress(0, None);
747        let is_head = matches!(request.method, Method::Head);
748        let streaming = self.send_future(request).await?;
749        // HEAD/304 can advertise the representation size despite carrying no body.
750        let bodyless = is_head || matches!(streaming.status(), 204 | 304);
751        if !bodyless
752            && streaming
753                .expected_length()
754                .is_some_and(|n| n > max_bytes as u64)
755        {
756            return Err(HttpError::BodyTooLarge { limit: max_bytes });
757        }
758        let (head, mut body) = streaming.into_parts();
759        let encoded = head.headers.iter().any(|(k, v)| {
760            k.eq_ignore_ascii_case("content-encoding") && !v.eq_ignore_ascii_case("identity")
761        });
762        let total = if bodyless || encoded {
763            None
764        } else {
765            head.expected_length.filter(|n| *n > 0)
766        };
767        progress(0, total);
768        let mut bytes = Vec::new();
769        while let Some(chunk) = body.next().await {
770            let chunk = chunk?;
771            if bytes.len().saturating_add(chunk.len()) > max_bytes {
772                return Err(HttpError::BodyTooLarge { limit: max_bytes });
773            }
774            bytes.extend_from_slice(&chunk);
775            let received = bytes.len() as u64;
776            progress(received, total.filter(|n| received <= *n));
777        }
778        Ok(Response::assemble(head, bytes, body.metrics()))
779    }
780
781    /// Send `request` and read its whole body into memory. For large bodies use
782    /// [`Client::send_async`] and read the [`Body`] in chunks.
783    pub fn fetch_async(
784        &self,
785        request: Request,
786        on_done: impl FnOnce(Result<Response, HttpError>) + Send + 'static,
787    ) -> InFlight {
788        InFlight(Arc::downgrade(&Flight::start(
789            &self.inner,
790            request,
791            Box::new(move |head| match head {
792                Ok(streaming) => streaming.collect_async(on_done),
793                Err(e) => on_done(Err(e)),
794            }),
795        )))
796    }
797
798    /// Send `request` and await the whole response. Dropping the future cancels the request.
799    #[must_use]
800    pub fn fetch_future(&self, request: Request) -> Fetching {
801        let (tx, rx) = day_async::oneshot();
802        let flight = Flight::start(
803            &self.inner,
804            request,
805            Box::new(move |head| match head {
806                Ok(streaming) => streaming.collect_async(move |r| tx.send(r)),
807                Err(e) => tx.send(Err(e)),
808            }),
809        );
810        Fetching {
811            flight,
812            rx,
813            done: false,
814        }
815    }
816
817    /// [`Client::fetch_async`], with a closure that cancels the request.
818    #[cfg_attr(target_os = "windows", allow(dead_code))]
819    pub(crate) fn fetch_cancellable(
820        &self,
821        request: Request,
822        on_done: impl FnOnce(Result<Response, HttpError>) + Send + 'static,
823    ) -> Box<dyn FnOnce() + Send> {
824        let flight = Flight::start(
825            &self.inner,
826            request,
827            Box::new(move |head| match head {
828                Ok(streaming) => streaming.collect_async(on_done),
829                Err(e) => on_done(Err(e)),
830            }),
831        );
832        Box::new(move || flight.cancel())
833    }
834
835    /// Open a WebSocket (`ws://` or `wss://`); `on_open` receives it after the handshake, or the
836    /// failure.
837    pub fn websocket_async(
838        &self,
839        request: Request,
840        on_open: impl FnOnce(Result<WebSocket, HttpError>) + Send + 'static,
841    ) {
842        WsShared::open(&self.inner, request, Box::new(on_open));
843    }
844
845    /// Open a WebSocket and await the handshake. Dropping the future abandons the connection.
846    #[must_use]
847    pub fn websocket_future(&self, request: Request) -> Connecting {
848        let (tx, rx) = day_async::oneshot();
849        let shared = WsShared::open(&self.inner, request, Box::new(move |r| tx.send(r)));
850        Connecting {
851            shared,
852            rx,
853            done: false,
854        }
855    }
856
857    /// The cookies this client would send, from its jar or the platform's store.
858    #[must_use]
859    pub fn cookies(&self) -> Vec<Cookie> {
860        match &self.inner.cookies {
861            Cookies::Jar(jar) => jar.cookies(),
862            Cookies::Platform => {
863                let transport = self.inner.current_transport();
864                if transport.capabilities().platform_cookies {
865                    transport.cookies()
866                } else if let Cookies::Jar(jar) = &self.inner.fallback_cookies {
867                    jar.cookies()
868                } else {
869                    Vec::new()
870                }
871            }
872            Cookies::Off => Vec::new(),
873        }
874    }
875
876    /// Forget every cookie in this client's jar or the platform's store.
877    pub fn clear_cookies(&self) {
878        match &self.inner.cookies {
879            Cookies::Jar(jar) => jar.clear(),
880            Cookies::Platform => {
881                self.inner.current_transport().clear_cookies();
882                if let Cookies::Jar(jar) = &self.inner.fallback_cookies {
883                    jar.clear();
884                }
885            }
886            Cookies::Off => {}
887        }
888    }
889
890    /// Empty the platform cache this client uses.
891    pub fn clear_cache(&self) {
892        self.inner.current_transport().clear_cache();
893    }
894}
895
896impl ClientInner {
897    fn current_transport(&self) -> Arc<dyn Transport> {
898        self.session.as_ref().map_or_else(
899            || self.transport.clone(),
900            |s| s.provider_transport(&self.config, &self.provider_cache),
901        )
902    }
903
904    fn snapshot(&self, request: &Request) -> Arc<Self> {
905        let mut inner = self.clone();
906        match &self.session {
907            Some(session) => {
908                let selected = session.resolve(
909                    &self.config,
910                    &self.provider_cache,
911                    &request.url,
912                    request.method.as_str(),
913                );
914                inner.transport = selected.transport;
915                inner.clock = selected.clock;
916            }
917            None => inner.transport = crate::Session::global().observe(self.transport.clone()),
918        }
919        inner.caps = inner.transport.capabilities();
920        if matches!(inner.cookies, Cookies::Platform) && !inner.caps.platform_cookies {
921            inner.cookies = self.fallback_cookies.clone();
922        }
923        Arc::new(inner)
924    }
925    fn prepare(&self, request: &Request, websocket: bool) -> Result<Prepared, HttpError> {
926        let bad = || HttpError::BadUrl(request.url.clone());
927        let written = request.url.trim();
928        let url = match url::Url::parse(written) {
929            Ok(url) => Some(url),
930            // A page resolves a relative reference against its own address, which only the
931            // browser knows, so the request goes out as written.
932            #[cfg(target_arch = "wasm32")]
933            Err(url::ParseError::RelativeUrlWithoutBase) if !written.is_empty() => None,
934            Err(_) => return Err(bad()),
935        };
936        if let Some(url) = &url {
937            let scheme_ok = if websocket {
938                matches!(url.scheme(), "ws" | "wss")
939            } else {
940                matches!(url.scheme(), "http" | "https")
941            };
942            if !scheme_ok || url.host_str().is_none() {
943                return Err(bad());
944            }
945        }
946        let mut headers: Vec<(String, String)> = self
947            .headers
948            .iter()
949            .filter(|(k, _)| !has_header(&request.headers, k))
950            .cloned()
951            .collect();
952        headers.extend(request.headers.iter().cloned());
953        if let Cookies::Jar(jar) = &self.cookies
954            && let Some(url) = &url
955            && !has_header(&headers, "cookie")
956            && let Some(cookie) = jar.header_for(url)
957        {
958            headers.push(("Cookie".into(), cookie));
959        }
960        let body = prepare_body(&request.payload, &mut headers)?;
961        Ok(Prepared {
962            method: request.method.as_str().to_string(),
963            url: url.map_or_else(|| written.to_string(), |url| url.to_string()),
964            headers,
965            body,
966            timeout_idle: request.timeout.unwrap_or(self.timeout_idle),
967            allow_expensive: request.allow_expensive,
968            allow_constrained: request.allow_constrained,
969            cache: request.cache,
970            priority: request.priority,
971            protocols: request.protocols.clone(),
972        })
973    }
974
975    fn cached_credential(&self, origin: &str, realm: Option<&str>) -> Option<Resolution> {
976        lock(&self.credentials)
977            .iter()
978            .find(|(o, r, _)| o == origin && r.as_deref() == realm)
979            .map(|(_, _, c)| c.clone())
980    }
981}
982
983fn has_header(headers: &[(String, String)], name: &str) -> bool {
984    headers.iter().any(|(k, _)| k.eq_ignore_ascii_case(name))
985}
986
987fn prepare_body(
988    payload: &Payload,
989    headers: &mut Vec<(String, String)>,
990) -> Result<PreparedBody, HttpError> {
991    let io = |e: std::io::Error| HttpError::Io(e.to_string());
992    Ok(match payload {
993        Payload::Empty => PreparedBody::Empty,
994        Payload::Bytes(bytes) => PreparedBody::Bytes(bytes.clone()),
995        Payload::File(path) => PreparedBody::File {
996            len: std::fs::metadata(path).map_err(io)?.len(),
997            path: path.clone(),
998        },
999        Payload::Stream(reader, len) => PreparedBody::Stream {
1000            reader: reader.clone(),
1001            len: *len,
1002        },
1003        Payload::Form(form) => {
1004            let (reader, len) = form.reader().map_err(io)?;
1005            if !has_header(headers, "content-type") {
1006                headers.push(("Content-Type".into(), form.content_type()));
1007            }
1008            PreparedBody::Stream {
1009                reader: SharedReader::new(reader),
1010                len: Some(len),
1011            }
1012        }
1013    })
1014}
1015
1016/// The request that follows a redirect (RFC 9110 §15.4): the method rewrite, and no credentials
1017/// or cookies carried to another origin.
1018fn redirect_request(previous: &Request, status: u16, from: &url::Url, to: &url::Url) -> Request {
1019    let mut next = previous.clone();
1020    next.url = to.to_string();
1021    let rewrite = (status == 303 && previous.method != Method::Head)
1022        || (matches!(status, 301 | 302) && previous.method == Method::Post);
1023    if rewrite {
1024        next.method = Method::Get;
1025        next.payload = Payload::Empty;
1026        next.headers.retain(|(k, _)| {
1027            !k.eq_ignore_ascii_case("content-type") && !k.eq_ignore_ascii_case("content-length")
1028        });
1029    }
1030    if from.origin() != to.origin() {
1031        next.headers.retain(|(k, _)| {
1032            !k.eq_ignore_ascii_case("authorization")
1033                && !k.eq_ignore_ascii_case("proxy-authorization")
1034                && !k.eq_ignore_ascii_case("cookie")
1035        });
1036    }
1037    next
1038}
1039
1040fn origin_of(url: &url::Url) -> String {
1041    url.origin().ascii_serialization()
1042}
1043
1044type HeadCallback = Box<dyn FnOnce(Result<Streaming, HttpError>) + Send>;
1045type ItemCallback<T> = Box<dyn FnMut(Option<Result<T, HttpError>>) -> bool + Send>;
1046
1047/// A queue between a transport and one reader, granting demand as the reader takes items.
1048struct Inbox<T> {
1049    queue: VecDeque<T>,
1050    /// Demand granted and not yet used.
1051    outstanding: u32,
1052    /// The terminal outcome, delivered once the queue is empty.
1053    finished: Option<Result<(), HttpError>>,
1054    /// The terminal outcome was delivered.
1055    taken: bool,
1056    paused: bool,
1057    waker: Option<Waker>,
1058    callback: Option<ItemCallback<T>>,
1059    /// A thread holds the callback and is delivering.
1060    draining: bool,
1061}
1062
1063enum Notify {
1064    Wake(Waker),
1065    Drain,
1066}
1067
1068impl<T> Inbox<T> {
1069    fn new() -> Self {
1070        Inbox {
1071            queue: VecDeque::new(),
1072            outstanding: 0,
1073            finished: None,
1074            taken: false,
1075            paused: false,
1076            waker: None,
1077            callback: None,
1078            draining: false,
1079        }
1080    }
1081
1082    fn notify(&mut self) -> Option<Notify> {
1083        if self.callback.is_some() {
1084            Some(Notify::Drain)
1085        } else {
1086            self.waker.take().map(Notify::Wake)
1087        }
1088    }
1089
1090    fn push(&mut self, item: T) -> Option<Notify> {
1091        self.outstanding = self.outstanding.saturating_sub(1);
1092        self.queue.push_back(item);
1093        self.notify()
1094    }
1095
1096    fn finish(&mut self, outcome: Result<(), HttpError>) -> Option<Notify> {
1097        if self.finished.is_none() && !self.taken {
1098            self.finished = Some(outcome);
1099        }
1100        self.notify()
1101    }
1102
1103    /// The next item to deliver: `Some(None)` is the clean end, `None` is nothing yet.
1104    #[expect(
1105        clippy::option_option,
1106        reason = "the inner `Option<Result>` is the item a reader receives, where `None` is the clean end; the outer one says whether an item is ready"
1107    )]
1108    fn take(&mut self) -> Option<Option<Result<T, HttpError>>> {
1109        if let Some(item) = self.queue.pop_front() {
1110            return Some(Some(Ok(item)));
1111        }
1112        if let Some(outcome) = self.finished.take() {
1113            self.taken = true;
1114            return Some(outcome.err().map(Err));
1115        }
1116        if self.taken {
1117            return Some(None);
1118        }
1119        None
1120    }
1121
1122    /// More demand to grant, when the reader's hand runs low.
1123    fn refill(&mut self) -> Option<u32> {
1124        if self.paused || self.finished.is_some() || self.taken {
1125            return None;
1126        }
1127        let held = self.queue.len() as u32 + self.outstanding;
1128        if held > WINDOW / 2 {
1129            return None;
1130        }
1131        let more = WINDOW - held;
1132        self.outstanding += more;
1133        Some(more)
1134    }
1135}
1136
1137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1138enum Stage {
1139    Head,
1140    Body,
1141    Done,
1142}
1143
1144enum Asked {
1145    Redirect {
1146        head: Head,
1147        next: Request,
1148    },
1149    Challenge {
1150        head: Head,
1151        parsed: ParsedChallenge,
1152        challenge: Challenge,
1153        url: url::Url,
1154    },
1155    NativeAuth(QuestionId),
1156    Trust(QuestionId),
1157}
1158
1159enum PendingOp {
1160    Demand(u32),
1161    Answer(QuestionId, Answer),
1162}
1163
1164enum Action {
1165    Demand(Arc<dyn Transfer>, u32),
1166    Answer(Arc<dyn Transfer>, QuestionId, Answer),
1167    Cancel(Arc<dyn Transfer>),
1168    StartHop,
1169    DeliverHead(HeadCallback, Box<Head>),
1170    HeadFailed(HeadCallback, HttpError),
1171    Wake(Waker),
1172    Drain,
1173    AskRedirect(Arc<RedirectHandler>, Hop, u64),
1174    AskChallenge(Arc<ChallengeHandler>, Challenge, u64),
1175    AskTrust(Arc<TrustHandler>, ServerTrust, u64),
1176    CancelTimer(TimerId),
1177    Progress(ProgressFn, u64, Option<u64>),
1178}
1179
1180impl From<Notify> for Action {
1181    fn from(n: Notify) -> Action {
1182        match n {
1183            Notify::Wake(w) => Action::Wake(w),
1184            Notify::Drain => Action::Drain,
1185        }
1186    }
1187}
1188
1189/// One request across its redirects and challenges.
1190struct Flight {
1191    client: Arc<ClientInner>,
1192    state: Mutex<FlightState>,
1193}
1194
1195struct FlightState {
1196    request: Request,
1197    stage: Stage,
1198    /// Bumped for each new exchange, so late events from an abandoned one are ignored.
1199    generation: u64,
1200    transfer: Option<Arc<dyn Transfer>>,
1201    /// The current exchange reported its terminal event.
1202    exchange_over: bool,
1203    pending: Vec<PendingOp>,
1204    on_head: Option<HeadCallback>,
1205    inbox: Inbox<Vec<u8>>,
1206    received: u64,
1207    expected: Option<u64>,
1208    metrics: Option<Metrics>,
1209    redirects_followed: u32,
1210    auth_failures: u32,
1211    /// The handler declined a challenge the transport raised, so its 401 is the response.
1212    native_auth_declined: bool,
1213    /// Credentials offered on the current exchange, remembered once they work.
1214    offered: Option<(String, Option<String>, Resolution)>,
1215    asks: Vec<(u64, Asked, Option<TimerId>)>,
1216    next_ask: u64,
1217    total_timer: Option<TimerId>,
1218}
1219
1220impl Flight {
1221    fn start(client: &Arc<ClientInner>, request: Request, on_head: HeadCallback) -> Arc<Flight> {
1222        let client = client.snapshot(&request);
1223        let total = request.timeout_total.or(client.timeout_total);
1224        // A handler the stack cannot consult, or pins it cannot check, must not be silently
1225        // skipped: such a request fails instead.
1226        let unsupported = (client.on_redirect.is_some()
1227            && !client.caps.manual_redirects
1228            && client.redirects != Redirects::Never)
1229            || ((!client.trust.is_empty() || client.on_server_trust.is_some())
1230                && !client.caps.server_trust)
1231            || (client.config.identity.is_some() && !client.caps.client_identity);
1232        let flight = Arc::new(Flight {
1233            client: client.clone(),
1234            state: Mutex::new(FlightState {
1235                request,
1236                stage: Stage::Head,
1237                generation: 0,
1238                transfer: None,
1239                exchange_over: false,
1240                pending: Vec::new(),
1241                on_head: Some(on_head),
1242                inbox: Inbox::new(),
1243                received: 0,
1244                expected: None,
1245                metrics: None,
1246                redirects_followed: 0,
1247                auth_failures: 0,
1248                native_auth_declined: false,
1249                offered: None,
1250                asks: Vec::new(),
1251                next_ask: 1,
1252                total_timer: None,
1253            }),
1254        });
1255        if unsupported {
1256            flight.fail_now(HttpError::Unsupported);
1257            return flight;
1258        }
1259        if let Some(total) = total {
1260            let weak = Arc::downgrade(&flight);
1261            let job = move || {
1262                if let Some(flight) = weak.upgrade() {
1263                    flight.fail_now(HttpError::Timeout);
1264                }
1265            };
1266            if let Some(clock) = &client.clock {
1267                clock.schedule(total, Box::new(job));
1268            } else {
1269                let timer = day_async::schedule(total, job);
1270                lock(&flight.state).total_timer = Some(timer);
1271            }
1272        }
1273        flight.start_exchange();
1274        flight
1275    }
1276
1277    fn start_exchange(self: &Arc<Self>) {
1278        let (request, generation) = {
1279            let st = lock(&self.state);
1280            if st.stage == Stage::Done {
1281                return;
1282            }
1283            (st.request.clone(), st.generation)
1284        };
1285        let prepared = match self.client.prepare(&request, false) {
1286            Ok(p) => p,
1287            Err(e) => return self.fail_now(e),
1288        };
1289        let this = self.clone();
1290        let events: Events = Arc::new(move |event| this.on_event(generation, event));
1291        let transfer = self.client.transport.start(prepared, events);
1292        let mut actions = Vec::new();
1293        {
1294            let mut st = lock(&self.state);
1295            if st.generation == generation && !st.exchange_over && st.stage != Stage::Done {
1296                for op in std::mem::take(&mut st.pending) {
1297                    actions.push(match op {
1298                        PendingOp::Demand(n) => Action::Demand(transfer.clone(), n),
1299                        PendingOp::Answer(id, a) => Action::Answer(transfer.clone(), id, a),
1300                    });
1301                }
1302                st.transfer = Some(transfer);
1303            } else {
1304                actions.push(Action::Cancel(transfer));
1305            }
1306        }
1307        self.run(actions);
1308    }
1309
1310    fn on_event(self: &Arc<Self>, generation: u64, event: Event) {
1311        let mut actions = Vec::new();
1312        {
1313            let mut st = lock(&self.state);
1314            if generation != st.generation || st.stage == Stage::Done {
1315                return;
1316            }
1317            match event {
1318                Event::Head(head) => self.head_arrived(&mut st, head, &mut actions),
1319                Event::Chunk(bytes) => {
1320                    // A head waiting on a redirect or challenge answer keeps its body too, in
1321                    // case the answer makes that response the response.
1322                    if st.stage == Stage::Body || parked(&st) {
1323                        st.received += bytes.len() as u64;
1324                        if let Some(n) = st.inbox.push(bytes) {
1325                            actions.push(n.into());
1326                        }
1327                    }
1328                }
1329                Event::Sent { sent, total } => {
1330                    if let Some(progress) = st.request.upload_progress.clone() {
1331                        actions.push(Action::Progress(progress, sent, total));
1332                    }
1333                }
1334                Event::Question(id, question) => self.question(&mut st, id, question, &mut actions),
1335                Event::Metrics(mut metrics) => {
1336                    metrics.redirects = st.redirects_followed;
1337                    st.metrics = Some(metrics);
1338                }
1339                Event::End => {
1340                    st.exchange_over = true;
1341                    st.transfer = None;
1342                    match st.stage {
1343                        Stage::Body => {
1344                            if let Some(n) = st.inbox.finish(Ok(())) {
1345                                actions.push(n.into());
1346                            }
1347                        }
1348                        // An empty body can end while its head waits on an answer.
1349                        Stage::Head if parked(&st) => {}
1350                        Stage::Head => fail(
1351                            &mut st,
1352                            HttpError::Io("the exchange ended without a response".into()),
1353                            &mut actions,
1354                        ),
1355                        Stage::Done => {}
1356                    }
1357                }
1358                Event::Failed(error) => {
1359                    st.exchange_over = true;
1360                    st.transfer = None;
1361                    fail(&mut st, error, &mut actions);
1362                }
1363            }
1364        }
1365        self.run(actions);
1366    }
1367
1368    fn head_arrived(&self, st: &mut FlightState, head: Head, actions: &mut Vec<Action>) {
1369        let client = &self.client;
1370        let base = url::Url::parse(&head.url)
1371            .or_else(|_| url::Url::parse(&st.request.url))
1372            .ok();
1373        if let (Cookies::Jar(jar), Some(url)) = (&client.cookies, &base) {
1374            jar.store_all(url, head.headers_named("set-cookie"));
1375        }
1376        let status = head.status;
1377
1378        if client.caps.manual_redirects
1379            && matches!(status, 301 | 302 | 303 | 307 | 308)
1380            && let Redirects::Follow(max) = client.redirects
1381            && let Some(from) = &base
1382            && let Some(to) = head.header("location").and_then(|l| from.join(l).ok())
1383            && matches!(to.scheme(), "http" | "https")
1384        {
1385            if st.redirects_followed >= max {
1386                return fail(st, HttpError::TooManyRedirects, actions);
1387            }
1388            let next = redirect_request(&st.request, status, from, &to);
1389            if let Some(handler) = client.on_redirect.clone() {
1390                let hop = Hop {
1391                    status,
1392                    from: from.to_string(),
1393                    to: to.to_string(),
1394                    method: next.method.as_str().to_string(),
1395                    followed: st.redirects_followed,
1396                };
1397                let ask = register(st, Asked::Redirect { head, next });
1398                actions.push(Action::AskRedirect(handler, hop, ask));
1399                return;
1400            }
1401            st.redirects_followed += 1;
1402            return replace_exchange(st, next, actions);
1403        }
1404
1405        if matches!(status, 401 | 407)
1406            && !st.native_auth_declined
1407            && st.auth_failures < MAX_AUTH_ATTEMPTS
1408            && let Some(url) = base.clone()
1409        {
1410            let proxy = status == 407;
1411            let native = client.caps.auth_questions;
1412            let chosen = parse_challenges(&head.headers, proxy)
1413                .into_iter()
1414                .filter(|c| !(native && c.scheme.raised_natively()))
1415                .max_by_key(|c| match c.scheme {
1416                    Scheme::Digest => 3,
1417                    Scheme::Basic => 2,
1418                    Scheme::Bearer => 1,
1419                    _ => 0,
1420                });
1421            if let Some(parsed) = chosen {
1422                let realm = parsed.param("realm").map(str::to_string);
1423                let challenge = Challenge {
1424                    url: url.to_string(),
1425                    host: url.host_str().unwrap_or_default().to_string(),
1426                    port: url.port_or_known_default().unwrap_or(0),
1427                    realm: realm.clone(),
1428                    scheme: parsed.scheme.clone(),
1429                    proxy,
1430                    previous_failures: st.auth_failures,
1431                };
1432                if st.auth_failures == 0
1433                    && let Some(known) =
1434                        client.cached_credential(&origin_of(&url), realm.as_deref())
1435                {
1436                    return answer_challenge(st, &parsed, &challenge, &url, known, head, actions);
1437                }
1438                if let Some(handler) = client.on_challenge.clone() {
1439                    let ask = register(
1440                        st,
1441                        Asked::Challenge {
1442                            head,
1443                            parsed,
1444                            challenge: challenge.clone(),
1445                            url,
1446                        },
1447                    );
1448                    actions.push(Action::AskChallenge(handler, challenge, ask));
1449                    return;
1450                }
1451            }
1452        }
1453
1454        if let Some(offered) = st.offered.take()
1455            && !matches!(status, 401 | 407)
1456        {
1457            let mut known = lock(&client.credentials);
1458            known.retain(|(o, r, _)| !(o == &offered.0 && r == &offered.1));
1459            known.push(offered);
1460        }
1461        begin_body(st, head, actions);
1462    }
1463
1464    fn question(
1465        &self,
1466        st: &mut FlightState,
1467        id: QuestionId,
1468        question: Question,
1469        actions: &mut Vec<Action>,
1470    ) {
1471        let client = &self.client;
1472        match question {
1473            Question::Auth(asked) => match client.on_challenge.clone() {
1474                Some(handler) if asked.previous_failures < MAX_AUTH_ATTEMPTS => {
1475                    let challenge = Challenge {
1476                        url: st.request.url.clone(),
1477                        host: asked.host,
1478                        port: asked.port,
1479                        realm: asked.realm,
1480                        scheme: asked.scheme,
1481                        proxy: asked.proxy,
1482                        previous_failures: asked.previous_failures,
1483                    };
1484                    let ask = register(st, Asked::NativeAuth(id));
1485                    actions.push(Action::AskChallenge(handler, challenge, ask));
1486                }
1487                _ => {
1488                    st.native_auth_declined = true;
1489                    answer(st, id, Answer::DefaultHandling, actions);
1490                }
1491            },
1492            Question::ServerTrust(trust) => {
1493                if let Some(pins) = client.trust.pins_for(&trust.host) {
1494                    let chain: Vec<[u8; 32]> =
1495                        trust.chain.iter().filter_map(|c| spki_sha256(c)).collect();
1496                    if !pins.iter().flatten().any(|p| chain.contains(p)) {
1497                        return answer(st, id, Answer::Reject, actions);
1498                    }
1499                    if trust.system_trusted {
1500                        return answer(st, id, Answer::Accept, actions);
1501                    }
1502                }
1503                match client.on_server_trust.clone() {
1504                    Some(handler) => {
1505                        let ask = register(st, Asked::Trust(id));
1506                        actions.push(Action::AskTrust(handler, trust, ask));
1507                    }
1508                    None => answer(st, id, Answer::DefaultHandling, actions),
1509                }
1510            }
1511        }
1512    }
1513
1514    fn resolve(self: &Arc<Self>, ask: u64, resolution: Resolution) {
1515        let mut actions = Vec::new();
1516        {
1517            let mut st = lock(&self.state);
1518            let Some(index) = st.asks.iter().position(|(a, _, _)| *a == ask) else {
1519                return;
1520            };
1521            let (_, asked, timer) = st.asks.remove(index);
1522            if let Some(timer) = timer {
1523                actions.push(Action::CancelTimer(timer));
1524            }
1525            if st.stage != Stage::Done {
1526                Self::apply(&mut st, asked, resolution, &mut actions);
1527            }
1528        }
1529        self.run(actions);
1530    }
1531
1532    fn apply(
1533        st: &mut FlightState,
1534        asked: Asked,
1535        resolution: Resolution,
1536        actions: &mut Vec<Action>,
1537    ) {
1538        match asked {
1539            Asked::Redirect { head, next } => match resolution {
1540                Resolution::Stop => begin_body(st, head, actions),
1541                Resolution::Cancel => fail(st, HttpError::Cancelled, actions),
1542                _ => {
1543                    st.redirects_followed += 1;
1544                    replace_exchange(st, next, actions);
1545                }
1546            },
1547            Asked::Challenge {
1548                head,
1549                parsed,
1550                challenge,
1551                url,
1552            } => answer_challenge(st, &parsed, &challenge, &url, resolution, head, actions),
1553            Asked::NativeAuth(id) => {
1554                let answer_with = match resolution {
1555                    Resolution::Credential { user, password } => {
1556                        Answer::Credential { user, password }
1557                    }
1558                    Resolution::Cancel => Answer::Cancel,
1559                    _ => {
1560                        st.native_auth_declined = true;
1561                        Answer::DefaultHandling
1562                    }
1563                };
1564                answer(st, id, answer_with, actions);
1565            }
1566            Asked::Trust(id) => {
1567                let answer_with = match resolution {
1568                    Resolution::Accept => Answer::Accept,
1569                    Resolution::Reject | Resolution::Cancel => Answer::Reject,
1570                    _ => Answer::DefaultHandling,
1571                };
1572                answer(st, id, answer_with, actions);
1573            }
1574        }
1575    }
1576
1577    fn fail_now(self: &Arc<Self>, error: HttpError) {
1578        let mut actions = Vec::new();
1579        fail(&mut lock(&self.state), error, &mut actions);
1580        self.run(actions);
1581    }
1582
1583    /// Abandon the request from the reader's side: nothing more is delivered.
1584    fn cancel(self: &Arc<Self>) {
1585        let mut actions = Vec::new();
1586        let (on_head, callback) = {
1587            let mut st = lock(&self.state);
1588            if st.stage == Stage::Done {
1589                return;
1590            }
1591            st.stage = Stage::Done;
1592            st.inbox.taken = true;
1593            st.inbox.finished = None;
1594            st.inbox.queue.clear();
1595            st.inbox.waker = None;
1596            teardown(&mut st, &mut actions);
1597            (st.on_head.take(), st.inbox.callback.take())
1598        };
1599        drop((on_head, callback));
1600        self.run(actions);
1601    }
1602
1603    fn register_timer(self: &Arc<Self>, ask: u64) {
1604        let weak = Arc::downgrade(self);
1605        let timer = day_async::schedule(self.client.question_timeout, move || {
1606            if let Some(flight) = weak.upgrade() {
1607                flight.resolve(ask, Resolution::Default);
1608            }
1609        });
1610        let mut st = lock(&self.state);
1611        match st.asks.iter_mut().find(|(a, _, _)| *a == ask) {
1612            Some(entry) => entry.2 = Some(timer),
1613            None => day_async::unschedule(timer),
1614        }
1615    }
1616
1617    fn grip(self: &Arc<Self>, ask: u64) -> ReplyGrip {
1618        ReplyGrip {
1619            flight: Arc::downgrade(self),
1620            ask,
1621            answered: false,
1622        }
1623    }
1624
1625    fn run(self: &Arc<Self>, actions: Vec<Action>) {
1626        for action in actions {
1627            match action {
1628                Action::Demand(transfer, n) => transfer.demand(n),
1629                Action::Answer(transfer, id, answer) => transfer.answer(id, answer),
1630                Action::Cancel(transfer) => transfer.cancel(),
1631                Action::StartHop => self.start_exchange(),
1632                Action::DeliverHead(on_head, head) => on_head(Ok(Streaming {
1633                    head: *head,
1634                    body: Body {
1635                        flight: self.clone(),
1636                        handed_off: false,
1637                    },
1638                })),
1639                Action::HeadFailed(on_head, error) => on_head(Err(error)),
1640                Action::Wake(waker) => waker.wake(),
1641                Action::Drain => self.drain(),
1642                Action::AskRedirect(handler, hop, ask) => {
1643                    self.register_timer(ask);
1644                    handler(&hop, RedirectReply(self.grip(ask)));
1645                }
1646                Action::AskChallenge(handler, challenge, ask) => {
1647                    self.register_timer(ask);
1648                    handler(&challenge, ChallengeReply(self.grip(ask)));
1649                }
1650                Action::AskTrust(handler, trust, ask) => {
1651                    self.register_timer(ask);
1652                    handler(&trust, TrustReply(self.grip(ask)));
1653                }
1654                Action::CancelTimer(timer) => day_async::unschedule(timer),
1655                Action::Progress(progress, sent, total) => (progress.0)(sent, total),
1656            }
1657        }
1658    }
1659
1660    /// Deliver queued chunks to the body's callback, one thread at a time and in order.
1661    fn drain(self: &Arc<Self>) {
1662        loop {
1663            let mut actions = Vec::new();
1664            let (item, mut callback) = {
1665                let mut st = lock(&self.state);
1666                if st.inbox.draining {
1667                    return;
1668                }
1669                let Some(callback) = st.inbox.callback.take() else {
1670                    return;
1671                };
1672                let Some(item) = st.inbox.take() else {
1673                    st.inbox.callback = Some(callback);
1674                    return;
1675                };
1676                if let Some(n) = st.inbox.refill() {
1677                    demand(&mut st, n, &mut actions);
1678                }
1679                st.inbox.draining = true;
1680                (item, callback)
1681            };
1682            self.run(actions);
1683            let terminal = !matches!(item, Some(Ok(_)));
1684            if terminal {
1685                self.finish_body();
1686            }
1687            let keep = callback(item);
1688            let mut st = lock(&self.state);
1689            st.inbox.draining = false;
1690            if terminal {
1691                return;
1692            }
1693            if keep {
1694                st.inbox.callback = Some(callback);
1695            } else {
1696                drop(st);
1697                drop(callback);
1698                return self.cancel();
1699            }
1700        }
1701    }
1702
1703    /// The body's terminal outcome went to the reader: stop the clocks.
1704    fn finish_body(self: &Arc<Self>) {
1705        let mut actions = Vec::new();
1706        {
1707            let mut st = lock(&self.state);
1708            if st.stage != Stage::Done {
1709                st.stage = Stage::Done;
1710                teardown(&mut st, &mut actions);
1711            }
1712        }
1713        self.run(actions);
1714    }
1715}
1716
1717/// A response head is waiting on a redirect or challenge answer.
1718fn parked(st: &FlightState) -> bool {
1719    st.asks
1720        .iter()
1721        .any(|(_, asked, _)| matches!(asked, Asked::Redirect { .. } | Asked::Challenge { .. }))
1722}
1723
1724fn register(st: &mut FlightState, asked: Asked) -> u64 {
1725    let ask = st.next_ask;
1726    st.next_ask += 1;
1727    st.asks.push((ask, asked, None));
1728    ask
1729}
1730
1731fn demand(st: &mut FlightState, n: u32, actions: &mut Vec<Action>) {
1732    match &st.transfer {
1733        Some(t) => actions.push(Action::Demand(t.clone(), n)),
1734        None if !st.exchange_over => st.pending.push(PendingOp::Demand(n)),
1735        None => {}
1736    }
1737}
1738
1739fn answer(st: &mut FlightState, id: QuestionId, answer: Answer, actions: &mut Vec<Action>) {
1740    match &st.transfer {
1741        Some(t) => actions.push(Action::Answer(t.clone(), id, answer)),
1742        None if !st.exchange_over => st.pending.push(PendingOp::Answer(id, answer)),
1743        None => {}
1744    }
1745}
1746
1747/// Stop the current exchange and send `next` in its place.
1748fn replace_exchange(st: &mut FlightState, next: Request, actions: &mut Vec<Action>) {
1749    if let Some(t) = st.transfer.take() {
1750        actions.push(Action::Cancel(t));
1751    }
1752    st.generation += 1;
1753    st.exchange_over = false;
1754    st.pending.clear();
1755    st.inbox.queue.clear();
1756    st.inbox.outstanding = 0;
1757    st.inbox.finished = None;
1758    st.received = 0;
1759    st.request = next;
1760    st.stage = Stage::Head;
1761    actions.push(Action::StartHop);
1762}
1763
1764fn answer_challenge(
1765    st: &mut FlightState,
1766    parsed: &ParsedChallenge,
1767    challenge: &Challenge,
1768    url: &url::Url,
1769    resolution: Resolution,
1770    head: Head,
1771    actions: &mut Vec<Action>,
1772) {
1773    let value = match &resolution {
1774        Resolution::Credential { user, password } => match parsed.scheme {
1775            Scheme::Digest => {
1776                let mut uri = url.path().to_string();
1777                if let Some(q) = url.query() {
1778                    uri.push('?');
1779                    uri.push_str(q);
1780                }
1781                digest_authorization(parsed, user, password, st.request.method.as_str(), &uri)
1782            }
1783            _ => Some(basic_authorization(user, password)),
1784        },
1785        Resolution::Bearer(token) => Some(format!("Bearer {token}")),
1786        Resolution::Cancel => return fail(st, HttpError::Cancelled, actions),
1787        _ => None,
1788    };
1789    let Some(value) = value else {
1790        return begin_body(st, head, actions);
1791    };
1792    let name = if challenge.proxy {
1793        "Proxy-Authorization"
1794    } else {
1795        "Authorization"
1796    };
1797    let mut next = st.request.clone();
1798    next.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
1799    next.headers.push((name.to_string(), value));
1800    st.auth_failures += 1;
1801    st.offered = Some((origin_of(url), challenge.realm.clone(), resolution));
1802    replace_exchange(st, next, actions);
1803}
1804
1805/// The final response head: hand it to the reader and start granting demand.
1806fn begin_body(st: &mut FlightState, head: Head, actions: &mut Vec<Action>) {
1807    st.stage = Stage::Body;
1808    st.expected = head.expected_length;
1809    if let Some(on_head) = st.on_head.take() {
1810        actions.push(Action::DeliverHead(on_head, Box::new(head)));
1811    }
1812    if let Some(n) = st.inbox.refill() {
1813        demand(st, n, actions);
1814    }
1815    // The exchange already ended while its head waited on an answer.
1816    if st.exchange_over
1817        && let Some(n) = st.inbox.finish(Ok(()))
1818    {
1819        actions.push(n.into());
1820    }
1821}
1822
1823fn fail(st: &mut FlightState, error: HttpError, actions: &mut Vec<Action>) {
1824    match st.stage {
1825        Stage::Head => {
1826            st.stage = Stage::Done;
1827            // Tear the exchange down before the caller hears of the failure, as the body arm
1828            // does: a caller told "timed out" who retries at once must not have the old exchange
1829            // still running beside the new one. The `Failed(Cancelled)` a transport may raise
1830            // from inside `cancel` finds the flight `Done` and is dropped.
1831            teardown(st, actions);
1832            if let Some(on_head) = st.on_head.take() {
1833                actions.push(Action::HeadFailed(on_head, error));
1834            }
1835        }
1836        Stage::Body => {
1837            if let Some(t) = st.transfer.take() {
1838                actions.push(Action::Cancel(t));
1839            }
1840            if let Some(n) = st.inbox.finish(Err(error)) {
1841                actions.push(n.into());
1842            }
1843        }
1844        Stage::Done => {}
1845    }
1846}
1847
1848fn teardown(st: &mut FlightState, actions: &mut Vec<Action>) {
1849    if let Some(t) = st.transfer.take() {
1850        actions.push(Action::Cancel(t));
1851    }
1852    st.pending.clear();
1853    for (_, _, timer) in st.asks.drain(..) {
1854        if let Some(timer) = timer {
1855            actions.push(Action::CancelTimer(timer));
1856        }
1857    }
1858    if let Some(timer) = st.total_timer.take() {
1859        actions.push(Action::CancelTimer(timer));
1860    }
1861}
1862
1863/// A response head with its unread body.
1864#[derive(Debug)]
1865pub struct Streaming {
1866    head: Head,
1867    body: Body,
1868}
1869
1870impl Streaming {
1871    /// The status code.
1872    #[must_use]
1873    pub fn status(&self) -> u16 {
1874        self.head.status
1875    }
1876
1877    /// The headers, in arrival order.
1878    #[must_use]
1879    pub fn headers(&self) -> &[(String, String)] {
1880        &self.head.headers
1881    }
1882
1883    /// The first header with this name, ASCII case-insensitive.
1884    #[must_use]
1885    pub fn header(&self, name: &str) -> Option<&str> {
1886        self.head.header(name)
1887    }
1888
1889    /// The URL that answered, after redirects.
1890    #[must_use]
1891    pub fn url(&self) -> &str {
1892        &self.head.url
1893    }
1894
1895    /// `Content-Length`, when the response declared one.
1896    #[must_use]
1897    pub fn expected_length(&self) -> Option<u64> {
1898        self.head.expected_length
1899    }
1900
1901    /// The whole head.
1902    #[must_use]
1903    pub fn head(&self) -> &Head {
1904        &self.head
1905    }
1906
1907    /// The body, unread.
1908    #[must_use]
1909    pub fn into_body(self) -> Body {
1910        self.body
1911    }
1912
1913    /// The head and the body, apart.
1914    #[must_use]
1915    pub fn into_parts(self) -> (Head, Body) {
1916        (self.head, self.body)
1917    }
1918
1919    /// Read the whole body into memory; `on_done` receives the response.
1920    pub fn collect_async(self, on_done: impl FnOnce(Result<Response, HttpError>) + Send + 'static) {
1921        let Streaming { head, body } = self;
1922        let flight = Arc::downgrade(&body.flight);
1923        let capacity = head.expected_length.unwrap_or(0).min(16 << 20) as usize;
1924        let mut bytes = Vec::with_capacity(capacity);
1925        let mut on_done = Some(on_done);
1926        let mut head = Some(head);
1927        body.read_async(move |item| {
1928            match item {
1929                Some(Ok(chunk)) => {
1930                    bytes.extend_from_slice(&chunk);
1931                    return true;
1932                }
1933                Some(Err(e)) => {
1934                    if let Some(f) = on_done.take() {
1935                        f(Err(e));
1936                    }
1937                }
1938                None => {
1939                    if let (Some(f), Some(h)) = (on_done.take(), head.take()) {
1940                        let metrics = flight
1941                            .upgrade()
1942                            .and_then(|f| lock(&f.state).metrics.clone());
1943                        f(Ok(Response::assemble(
1944                            h,
1945                            std::mem::take(&mut bytes),
1946                            metrics,
1947                        )));
1948                    }
1949                }
1950            }
1951            false
1952        });
1953    }
1954
1955    /// Read the whole body into memory and await the response.
1956    #[must_use]
1957    pub fn collect_future(self) -> Collecting {
1958        let flight = self.body.flight.clone();
1959        let (tx, rx) = day_async::oneshot();
1960        self.collect_async(move |r| tx.send(r));
1961        Collecting {
1962            flight,
1963            rx,
1964            done: false,
1965        }
1966    }
1967}
1968
1969/// A response body, read in the chunks the platform delivers. The body pulls from the network
1970/// only while its reader keeps up. Dropping it before the end cancels the request.
1971pub struct Body {
1972    flight: Arc<Flight>,
1973    handed_off: bool,
1974}
1975
1976impl std::fmt::Debug for Body {
1977    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1978        f.debug_struct("Body")
1979            .field("received", &self.received())
1980            .finish_non_exhaustive()
1981    }
1982}
1983
1984impl Body {
1985    /// The next chunk; `None` after the last.
1986    // Awaited (`body.next().await`), so it is not `Iterator::next`.
1987    #[allow(clippy::should_implement_trait)]
1988    pub fn next(&mut self) -> NextChunk<'_> {
1989        NextChunk { body: self }
1990    }
1991
1992    /// Wait for the next chunk on this thread. Never call it on the UI thread.
1993    #[cfg(not(target_arch = "wasm32"))]
1994    pub fn next_blocking(&mut self) -> Option<Result<Vec<u8>, HttpError>> {
1995        wait(self.next())
1996    }
1997
1998    /// A grip that cancels this body's request from any thread, also after
1999    /// [`Body::read_async`] took the body.
2000    #[must_use]
2001    pub fn in_flight(&self) -> InFlight {
2002        InFlight(Arc::downgrade(&self.flight))
2003    }
2004
2005    /// Bytes received so far, including chunks not read yet.
2006    #[must_use]
2007    pub fn received(&self) -> u64 {
2008        lock(&self.flight.state).received
2009    }
2010
2011    /// `Content-Length`, when the response declared one.
2012    #[must_use]
2013    pub fn expected_length(&self) -> Option<u64> {
2014        lock(&self.flight.state).expected
2015    }
2016
2017    /// Transfer metrics, once the platform reported them (usually just before the end).
2018    #[must_use]
2019    pub fn metrics(&self) -> Option<Metrics> {
2020        lock(&self.flight.state).metrics.clone()
2021    }
2022
2023    /// Stop pulling from the network. Chunks already on their way still arrive.
2024    pub fn pause(&self) {
2025        lock(&self.flight.state).inbox.paused = true;
2026    }
2027
2028    /// Pull from the network again after [`Body::pause`].
2029    pub fn resume(&self) {
2030        let mut actions = Vec::new();
2031        {
2032            let mut st = lock(&self.flight.state);
2033            st.inbox.paused = false;
2034            if let Some(n) = st.inbox.refill() {
2035                demand(&mut st, n, &mut actions);
2036            }
2037            if let Some(n) = st.inbox.notify() {
2038                actions.push(n.into());
2039            }
2040        }
2041        self.flight.run(actions);
2042    }
2043
2044    /// Hand each chunk to `on_chunk` as it arrives, then `None` at the end or `Some(Err)` on
2045    /// failure. The body pulls the next chunk only after `on_chunk` returns; returning `false`
2046    /// cancels the request.
2047    pub fn read_async(
2048        mut self,
2049        on_chunk: impl FnMut(Option<Result<Vec<u8>, HttpError>>) -> bool + Send + 'static,
2050    ) {
2051        self.handed_off = true;
2052        lock(&self.flight.state).inbox.callback = Some(Box::new(on_chunk));
2053        self.flight.drain();
2054    }
2055}
2056
2057impl Drop for Body {
2058    fn drop(&mut self) {
2059        if !self.handed_off {
2060            self.flight.cancel();
2061        }
2062    }
2063}
2064
2065/// The future [`Body::next`] returns.
2066pub struct NextChunk<'a> {
2067    body: &'a mut Body,
2068}
2069
2070impl Future for NextChunk<'_> {
2071    type Output = Option<Result<Vec<u8>, HttpError>>;
2072
2073    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2074        let flight = self.body.flight.clone();
2075        let mut actions = Vec::new();
2076        let (out, terminal) = {
2077            let mut st = lock(&flight.state);
2078            let item = st.inbox.take();
2079            if let Some(n) = st.inbox.refill() {
2080                demand(&mut st, n, &mut actions);
2081            }
2082            if let Some(item) = item {
2083                let terminal = !matches!(item, Some(Ok(_)));
2084                (Poll::Ready(item), terminal)
2085            } else {
2086                st.inbox.waker = Some(cx.waker().clone());
2087                (Poll::Pending, false)
2088            }
2089        };
2090        flight.run(actions);
2091        if terminal {
2092            flight.finish_body();
2093        }
2094        out
2095    }
2096}
2097
2098/// A grip on a request started with a callback: cancel it from any thread, at any stage. Holding
2099/// it does not keep the request alive, and cancelling a finished request does nothing.
2100#[derive(Clone, Debug)]
2101pub struct InFlight(Weak<Flight>);
2102
2103impl InFlight {
2104    /// Cancel the request. Its callback is not called again.
2105    pub fn cancel(&self) {
2106        if let Some(flight) = self.0.upgrade() {
2107            flight.cancel();
2108        }
2109    }
2110}
2111
2112impl std::fmt::Debug for Flight {
2113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2114        f.write_str("Flight")
2115    }
2116}
2117
2118/// The future [`Client::send_future`] returns.
2119pub struct Sending {
2120    flight: Arc<Flight>,
2121    rx: day_async::Oneshot<Result<Streaming, HttpError>>,
2122    done: bool,
2123}
2124
2125impl Future for Sending {
2126    type Output = Result<Streaming, HttpError>;
2127
2128    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2129        match Pin::new(&mut self.rx).poll(cx) {
2130            Poll::Ready(result) => {
2131                self.done = true;
2132                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
2133            }
2134            Poll::Pending => Poll::Pending,
2135        }
2136    }
2137}
2138
2139impl Drop for Sending {
2140    fn drop(&mut self) {
2141        if !self.done {
2142            self.flight.cancel();
2143        }
2144    }
2145}
2146
2147/// The future [`Client::fetch_future`] returns.
2148pub struct Fetching {
2149    flight: Arc<Flight>,
2150    rx: day_async::Oneshot<Result<Response, HttpError>>,
2151    done: bool,
2152}
2153
2154impl Future for Fetching {
2155    type Output = Result<Response, HttpError>;
2156
2157    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2158        match Pin::new(&mut self.rx).poll(cx) {
2159            Poll::Ready(result) => {
2160                self.done = true;
2161                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
2162            }
2163            Poll::Pending => Poll::Pending,
2164        }
2165    }
2166}
2167
2168impl Drop for Fetching {
2169    fn drop(&mut self) {
2170        if !self.done {
2171            self.flight.cancel();
2172        }
2173    }
2174}
2175
2176/// The future [`Streaming::collect_future`] returns.
2177pub struct Collecting {
2178    flight: Arc<Flight>,
2179    rx: day_async::Oneshot<Result<Response, HttpError>>,
2180    done: bool,
2181}
2182
2183impl Future for Collecting {
2184    type Output = Result<Response, HttpError>;
2185
2186    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2187        match Pin::new(&mut self.rx).poll(cx) {
2188            Poll::Ready(result) => {
2189                self.done = true;
2190                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
2191            }
2192            Poll::Pending => Poll::Pending,
2193        }
2194    }
2195}
2196
2197impl Drop for Collecting {
2198    fn drop(&mut self) {
2199        if !self.done {
2200            self.flight.cancel();
2201        }
2202    }
2203}
2204
2205/// Run a future to completion on this thread, parking between polls.
2206#[cfg(not(target_arch = "wasm32"))]
2207pub(crate) fn wait<F: Future>(future: F) -> F::Output {
2208    struct Unpark(std::thread::Thread);
2209    impl std::task::Wake for Unpark {
2210        fn wake(self: Arc<Self>) {
2211            self.0.unpark();
2212        }
2213        fn wake_by_ref(self: &Arc<Self>) {
2214            self.0.unpark();
2215        }
2216    }
2217    let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
2218    let mut cx = Context::from_waker(&waker);
2219    let mut future = std::pin::pin!(future);
2220    loop {
2221        if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
2222            return value;
2223        }
2224        std::thread::park();
2225    }
2226}
2227
2228// ---------------------------------------------------------------------------
2229// WebSockets
2230// ---------------------------------------------------------------------------
2231
2232type OpenCallback = Box<dyn FnOnce(Result<WebSocket, HttpError>) + Send>;
2233
2234struct WsShared {
2235    state: Mutex<WsState>,
2236}
2237
2238struct WsState {
2239    socket: Option<Arc<dyn Socket>>,
2240    open: bool,
2241    over: bool,
2242    on_open: Option<OpenCallback>,
2243    protocol: Option<String>,
2244    inbox: Inbox<Message>,
2245    pending_demand: u32,
2246    /// Sends and a close requested before the transport handed back its socket.
2247    pending_sends: Vec<(Message, Completion)>,
2248    pending_close: Option<(u16, String)>,
2249}
2250
2251impl WsShared {
2252    #[expect(
2253        clippy::needless_pass_by_value,
2254        reason = "the public `websocket_*` methods own the request and hand it over whole"
2255    )]
2256    fn open(client: &Arc<ClientInner>, request: Request, on_open: OpenCallback) -> Arc<WsShared> {
2257        let client = client.snapshot(&request);
2258        let shared = Arc::new(WsShared {
2259            state: Mutex::new(WsState {
2260                socket: None,
2261                open: false,
2262                over: false,
2263                on_open: None,
2264                protocol: None,
2265                inbox: Inbox::new(),
2266                pending_demand: 0,
2267                pending_sends: Vec::new(),
2268                pending_close: None,
2269            }),
2270        });
2271        // Pins are checked through a transport's trust questions, which a WebSocket handshake
2272        // does not raise: a pinned client fails closed rather than connecting unpinned.
2273        let prepared = match client.prepare(&request, true).and_then(|p| {
2274            if client.trust.is_empty()
2275                && client.config.identity.is_none()
2276                && client.on_server_trust.is_none()
2277            {
2278                Ok(p)
2279            } else {
2280                Err(HttpError::Unsupported)
2281            }
2282        }) {
2283            Ok(p) => p,
2284            Err(e) => {
2285                lock(&shared.state).over = true;
2286                on_open(Err(e));
2287                return shared;
2288            }
2289        };
2290        lock(&shared.state).on_open = Some(on_open);
2291        let this = shared.clone();
2292        let events: WsEvents = Arc::new(move |event| this.on_event(event));
2293        let socket = client.transport.websocket(prepared, events);
2294        let (keep, demand, sends, close) = {
2295            let mut st = lock(&shared.state);
2296            let keep = !st.over;
2297            if keep {
2298                st.socket = Some(socket.clone());
2299            }
2300            (
2301                keep,
2302                std::mem::take(&mut st.pending_demand),
2303                std::mem::take(&mut st.pending_sends),
2304                st.pending_close.take(),
2305            )
2306        };
2307        if !keep {
2308            for (_, done) in sends {
2309                done(Err(HttpError::Io("the WebSocket is closed".into())));
2310            }
2311            let (code, reason) = close.unwrap_or((1000, String::new()));
2312            socket.close(code, &reason);
2313            return shared;
2314        }
2315        if demand > 0 {
2316            socket.demand(demand);
2317        }
2318        for (message, done) in sends {
2319            socket.send(message, done);
2320        }
2321        if let Some((code, reason)) = close {
2322            socket.close(code, &reason);
2323        }
2324        shared
2325    }
2326
2327    fn on_event(self: &Arc<Self>, event: WsEvent) {
2328        let mut notify = None;
2329        let mut opened = None;
2330        let mut failed_open = None;
2331        let mut grant = None;
2332        {
2333            let mut st = lock(&self.state);
2334            if st.over && !matches!(event, WsEvent::Closed { .. }) {
2335                return;
2336            }
2337            match event {
2338                WsEvent::Open { protocol } => {
2339                    st.open = true;
2340                    st.protocol = protocol;
2341                    opened = st.on_open.take();
2342                    grant = st.inbox.refill().map(|n| ws_demand(&mut st, n));
2343                }
2344                WsEvent::Message(message) => notify = st.inbox.push(message),
2345                WsEvent::Closed { code, reason } => {
2346                    if st.over {
2347                        return;
2348                    }
2349                    st.over = true;
2350                    st.socket = None;
2351                    if st.open {
2352                        st.inbox.queue.push_back(Message::Close { code, reason });
2353                        notify = st.inbox.finish(Ok(()));
2354                    } else {
2355                        failed_open = st.on_open.take().map(|f| {
2356                            (
2357                                f,
2358                                HttpError::Io(format!("closed during the handshake ({code})")),
2359                            )
2360                        });
2361                    }
2362                }
2363                WsEvent::Failed(error) => {
2364                    st.over = true;
2365                    st.socket = None;
2366                    if st.open {
2367                        notify = st.inbox.finish(Err(error));
2368                    } else {
2369                        failed_open = st.on_open.take().map(|f| (f, error));
2370                    }
2371                }
2372            }
2373        }
2374        if let Some(Some((socket, n))) = grant {
2375            socket.demand(n);
2376        }
2377        if let Some(on_open) = opened {
2378            on_open(Ok(WebSocket {
2379                shared: self.clone(),
2380                handed_off: false,
2381            }));
2382        }
2383        if let Some((on_open, error)) = failed_open {
2384            on_open(Err(error));
2385        }
2386        match notify {
2387            Some(Notify::Wake(w)) => w.wake(),
2388            Some(Notify::Drain) => self.drain(),
2389            None => {}
2390        }
2391    }
2392
2393    fn socket(&self) -> Option<Arc<dyn Socket>> {
2394        lock(&self.state).socket.clone()
2395    }
2396
2397    fn drain(self: &Arc<Self>) {
2398        loop {
2399            let mut grant = None;
2400            let (item, mut callback) = {
2401                let mut st = lock(&self.state);
2402                if st.inbox.draining {
2403                    return;
2404                }
2405                let Some(callback) = st.inbox.callback.take() else {
2406                    return;
2407                };
2408                let Some(item) = st.inbox.take() else {
2409                    st.inbox.callback = Some(callback);
2410                    return;
2411                };
2412                if let Some(n) = st.inbox.refill() {
2413                    grant = ws_demand(&mut st, n);
2414                }
2415                st.inbox.draining = true;
2416                (item, callback)
2417            };
2418            if let Some((socket, n)) = grant {
2419                socket.demand(n);
2420            }
2421            let terminal = !matches!(item, Some(Ok(_)));
2422            let keep = callback(item);
2423            let mut st = lock(&self.state);
2424            st.inbox.draining = false;
2425            if terminal {
2426                return;
2427            }
2428            if keep {
2429                st.inbox.callback = Some(callback);
2430            } else {
2431                let socket = st.socket.take();
2432                st.over = true;
2433                drop(st);
2434                drop(callback);
2435                if let Some(socket) = socket {
2436                    socket.close(1000, "");
2437                }
2438                return;
2439            }
2440        }
2441    }
2442}
2443
2444fn ws_demand(st: &mut WsState, n: u32) -> Option<(Arc<dyn Socket>, u32)> {
2445    if let Some(socket) = &st.socket {
2446        Some((socket.clone(), n))
2447    } else {
2448        st.pending_demand += n;
2449        None
2450    }
2451}
2452
2453/// An open WebSocket. Read it with [`WebSocket::next`] or [`WebSocket::read_async`], and send
2454/// through it or a [`WsSender`]. Dropping it closes the connection with code 1000.
2455pub struct WebSocket {
2456    shared: Arc<WsShared>,
2457    handed_off: bool,
2458}
2459
2460impl std::fmt::Debug for WebSocket {
2461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2462        f.debug_struct("WebSocket")
2463            .field("protocol", &self.protocol())
2464            .finish_non_exhaustive()
2465    }
2466}
2467
2468impl WebSocket {
2469    /// The subprotocol the server chose.
2470    #[must_use]
2471    pub fn protocol(&self) -> Option<String> {
2472        lock(&self.shared.state).protocol.clone()
2473    }
2474
2475    /// A sending half to give to other code: it can send, ping and close.
2476    #[must_use]
2477    pub fn sender(&self) -> WsSender {
2478        WsSender {
2479            shared: self.shared.clone(),
2480        }
2481    }
2482
2483    /// Send a message; `done` reports when the platform took it.
2484    pub fn send_async(
2485        &self,
2486        message: Message,
2487        done: impl FnOnce(Result<(), HttpError>) + Send + 'static,
2488    ) {
2489        self.sender().send_async(message, done);
2490    }
2491
2492    /// Send a message and await the platform taking it.
2493    #[must_use]
2494    pub fn send_future(&self, message: Message) -> day_async::Oneshot<Result<(), HttpError>> {
2495        self.sender().send_future(message)
2496    }
2497
2498    /// Close with `code` and `reason`.
2499    pub fn close(&self, code: u16, reason: &str) {
2500        self.sender().close(code, reason);
2501    }
2502
2503    /// The next message; the last is a [`Message::Close`], then `None`.
2504    // Awaited (`socket.next().await`), so it is not `Iterator::next`.
2505    #[allow(clippy::should_implement_trait)]
2506    pub fn next(&mut self) -> NextMessage<'_> {
2507        NextMessage { socket: self }
2508    }
2509
2510    /// Hand each message to `on_message` as it arrives, then `None` at the end or `Some(Err)` on
2511    /// failure. Returning `false` closes the connection.
2512    pub fn read_async(
2513        mut self,
2514        on_message: impl FnMut(Option<Result<Message, HttpError>>) -> bool + Send + 'static,
2515    ) {
2516        self.handed_off = true;
2517        lock(&self.shared.state).inbox.callback = Some(Box::new(on_message));
2518        self.shared.drain();
2519    }
2520}
2521
2522impl Drop for WebSocket {
2523    fn drop(&mut self) {
2524        if !self.handed_off {
2525            let socket = {
2526                let mut st = lock(&self.shared.state);
2527                st.over = true;
2528                st.socket.take()
2529            };
2530            if let Some(socket) = socket {
2531                socket.close(1000, "");
2532            }
2533        }
2534    }
2535}
2536
2537/// The sending half of a [`WebSocket`].
2538#[derive(Clone)]
2539pub struct WsSender {
2540    shared: Arc<WsShared>,
2541}
2542
2543impl std::fmt::Debug for WsSender {
2544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2545        f.write_str("WsSender")
2546    }
2547}
2548
2549impl WsSender {
2550    /// Send a message; `done` reports when the platform took it.
2551    pub fn send_async(
2552        &self,
2553        message: Message,
2554        done: impl FnOnce(Result<(), HttpError>) + Send + 'static,
2555    ) {
2556        let socket = {
2557            let mut st = lock(&self.shared.state);
2558            if let Some(socket) = st.socket.clone() {
2559                Some(socket)
2560            } else if !st.over {
2561                st.pending_sends.push((message, Box::new(done)));
2562                return;
2563            } else {
2564                None
2565            }
2566        };
2567        match socket {
2568            Some(socket) => socket.send(message, Box::new(done)),
2569            None => done(Err(HttpError::Io("the WebSocket is closed".into()))),
2570        }
2571    }
2572
2573    /// Send a message and await the platform taking it.
2574    #[must_use]
2575    pub fn send_future(&self, message: Message) -> day_async::Oneshot<Result<(), HttpError>> {
2576        let (tx, rx) = day_async::oneshot();
2577        self.send_async(message, move |r| tx.send(r));
2578        rx
2579    }
2580
2581    /// Send a ping; `done` reports the pong. Needs [`Capabilities::websocket_ping`].
2582    pub fn ping_async(&self, done: impl FnOnce(Result<(), HttpError>) + Send + 'static) {
2583        match self.shared.socket() {
2584            Some(socket) => socket.ping(Box::new(done)),
2585            None => done(Err(HttpError::Io("the WebSocket is closed".into()))),
2586        }
2587    }
2588
2589    /// Send a ping and await the pong.
2590    #[must_use]
2591    pub fn ping_future(&self) -> day_async::Oneshot<Result<(), HttpError>> {
2592        let (tx, rx) = day_async::oneshot();
2593        self.ping_async(move |r| tx.send(r));
2594        rx
2595    }
2596
2597    /// Close with `code` and `reason`. The peer's reply arrives as the last message.
2598    pub fn close(&self, code: u16, reason: &str) {
2599        let socket = {
2600            let mut st = lock(&self.shared.state);
2601            if st.socket.is_none() && !st.over {
2602                st.pending_close = Some((code, reason.to_string()));
2603            }
2604            st.socket.clone()
2605        };
2606        if let Some(socket) = socket {
2607            socket.close(code, reason);
2608        }
2609    }
2610}
2611
2612/// The future [`WebSocket::next`] returns.
2613pub struct NextMessage<'a> {
2614    socket: &'a mut WebSocket,
2615}
2616
2617impl Future for NextMessage<'_> {
2618    type Output = Option<Result<Message, HttpError>>;
2619
2620    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2621        let shared = self.socket.shared.clone();
2622        let mut grant = None;
2623        let out = {
2624            let mut st = lock(&shared.state);
2625            let item = st.inbox.take();
2626            if let Some(n) = st.inbox.refill() {
2627                grant = ws_demand(&mut st, n);
2628            }
2629            if let Some(item) = item {
2630                Poll::Ready(item)
2631            } else {
2632                st.inbox.waker = Some(cx.waker().clone());
2633                Poll::Pending
2634            }
2635        };
2636        if let Some((socket, n)) = grant {
2637            socket.demand(n);
2638        }
2639        out
2640    }
2641}
2642
2643/// The future [`Client::websocket_future`] returns.
2644pub struct Connecting {
2645    shared: Arc<WsShared>,
2646    rx: day_async::Oneshot<Result<WebSocket, HttpError>>,
2647    done: bool,
2648}
2649
2650impl Future for Connecting {
2651    type Output = Result<WebSocket, HttpError>;
2652
2653    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2654        match Pin::new(&mut self.rx).poll(cx) {
2655            Poll::Ready(result) => {
2656                self.done = true;
2657                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
2658            }
2659            Poll::Pending => Poll::Pending,
2660        }
2661    }
2662}
2663
2664impl Drop for Connecting {
2665    fn drop(&mut self) {
2666        if !self.done {
2667            let socket = {
2668                let mut st = lock(&self.shared.state);
2669                st.over = true;
2670                st.on_open = None;
2671                st.socket.take()
2672            };
2673            if let Some(socket) = socket {
2674                socket.close(1000, "");
2675            }
2676        }
2677    }
2678}
2679
2680// ---------------------------------------------------------------------------
2681// Cookies (RFC 6265)
2682// ---------------------------------------------------------------------------
2683
2684/// A cookie, as a jar or the platform's store holds it.
2685#[derive(Clone, Debug, PartialEq, Eq)]
2686pub struct Cookie {
2687    pub name: String,
2688    pub value: String,
2689    pub domain: String,
2690    pub path: String,
2691    /// `None` for a session cookie.
2692    pub expires: Option<SystemTime>,
2693    pub secure: bool,
2694    pub http_only: bool,
2695    /// Sent only to the host that set it, which named no `Domain`.
2696    pub host_only: bool,
2697}
2698
2699/// A cookie store the client reads and writes itself: parsing, matching and expiry follow RFC
2700/// 6265, and a `Domain` that names a public suffix is refused.
2701#[derive(Debug, Default)]
2702pub struct CookieJar {
2703    cookies: Mutex<Vec<(Cookie, u64)>>,
2704    created: AtomicU64,
2705    file: Option<PathBuf>,
2706}
2707
2708impl CookieJar {
2709    /// An empty jar in memory.
2710    #[must_use]
2711    pub fn new() -> CookieJar {
2712        CookieJar::default()
2713    }
2714
2715    /// A jar persisted to `file`, loading what it holds. Session cookies are never written.
2716    pub fn open(file: impl Into<PathBuf>) -> CookieJar {
2717        let file = file.into();
2718        let jar = CookieJar {
2719            file: Some(file.clone()),
2720            ..CookieJar::default()
2721        };
2722        if let Ok(text) = std::fs::read_to_string(&file) {
2723            let now = now();
2724            let mut cookies = lock(&jar.cookies);
2725            for line in text.lines() {
2726                if let Some(cookie) = decode_cookie_line(line)
2727                    && cookie.expires.is_some_and(|e| e > now)
2728                {
2729                    let seq = jar.created.fetch_add(1, Ordering::Relaxed);
2730                    cookies.push((cookie, seq));
2731                }
2732            }
2733        }
2734        jar
2735    }
2736
2737    /// Every unexpired cookie.
2738    pub fn cookies(&self) -> Vec<Cookie> {
2739        let now = now();
2740        lock(&self.cookies)
2741            .iter()
2742            .filter(|(c, _)| c.expires.is_none_or(|e| e > now))
2743            .map(|(c, _)| c.clone())
2744            .collect()
2745    }
2746
2747    /// Forget every cookie.
2748    pub fn clear(&self) {
2749        lock(&self.cookies).clear();
2750        self.save();
2751    }
2752
2753    /// Store the `Set-Cookie` values a response from `url` carried.
2754    pub fn store<'a>(&self, url: &str, set_cookie: impl IntoIterator<Item = &'a str>) {
2755        if let Ok(url) = url::Url::parse(url) {
2756            self.store_all(&url, set_cookie);
2757        }
2758    }
2759
2760    /// The `Cookie` header for a request to `url`.
2761    pub fn header(&self, url: &str) -> Option<String> {
2762        url::Url::parse(url).ok().and_then(|u| self.header_for(&u))
2763    }
2764
2765    fn store_all<'a>(&self, url: &url::Url, set_cookie: impl IntoIterator<Item = &'a str>) {
2766        let now = now();
2767        let mut changed = false;
2768        {
2769            let mut cookies = lock(&self.cookies);
2770            for value in set_cookie {
2771                let Some(cookie) = parse_set_cookie(url, value, now) else {
2772                    continue;
2773                };
2774                let existing = cookies.iter().position(|(c, _)| {
2775                    c.name == cookie.name && c.domain == cookie.domain && c.path == cookie.path
2776                });
2777                let seq = match existing {
2778                    Some(i) => cookies.remove(i).1,
2779                    None => self.created.fetch_add(1, Ordering::Relaxed),
2780                };
2781                if cookie.expires.is_none_or(|e| e > now) {
2782                    cookies.push((cookie, seq));
2783                }
2784                changed = true;
2785            }
2786            cookies.retain(|(c, _)| c.expires.is_none_or(|e| e > now));
2787        }
2788        if changed {
2789            self.save();
2790        }
2791    }
2792
2793    fn header_for(&self, url: &url::Url) -> Option<String> {
2794        let host = url.host_str()?.to_ascii_lowercase();
2795        let secure = matches!(url.scheme(), "https" | "wss");
2796        let path = url.path();
2797        let now = now();
2798        let cookies = lock(&self.cookies);
2799        let mut matching: Vec<&(Cookie, u64)> = cookies
2800            .iter()
2801            .filter(|(c, _)| {
2802                c.expires.is_none_or(|e| e > now)
2803                    && (!c.secure || secure)
2804                    && if c.host_only {
2805                        c.domain == host
2806                    } else {
2807                        domain_matches(&host, &c.domain)
2808                    }
2809                    && path_matches(path, &c.path)
2810            })
2811            .collect();
2812        if matching.is_empty() {
2813            return None;
2814        }
2815        matching.sort_by(|(a, sa), (b, sb)| b.path.len().cmp(&a.path.len()).then(sa.cmp(sb)));
2816        Some(
2817            matching
2818                .iter()
2819                .map(|(c, _)| format!("{}={}", c.name, c.value))
2820                .collect::<Vec<_>>()
2821                .join("; "),
2822        )
2823    }
2824
2825    fn save(&self) {
2826        let Some(file) = &self.file else {
2827            return;
2828        };
2829        let mut text = String::new();
2830        for (cookie, _) in lock(&self.cookies).iter() {
2831            if let Some(line) = encode_cookie_line(cookie) {
2832                text.push_str(&line);
2833                text.push('\n');
2834            }
2835        }
2836        if let Some(dir) = file.parent() {
2837            let _ = std::fs::create_dir_all(dir);
2838        }
2839        let partial = file.with_extension("partial");
2840        if std::fs::write(&partial, text).is_ok() {
2841            let _ = std::fs::rename(&partial, file);
2842        }
2843    }
2844}
2845
2846#[cfg(not(target_arch = "wasm32"))]
2847fn now() -> SystemTime {
2848    SystemTime::now()
2849}
2850
2851/// The browser keeps its own cookies, and `SystemTime::now` does not exist on wasm32.
2852#[cfg(target_arch = "wasm32")]
2853fn now() -> SystemTime {
2854    UNIX_EPOCH
2855}
2856
2857fn domain_matches(host: &str, domain: &str) -> bool {
2858    host == domain
2859        || (host.len() > domain.len()
2860            && host.ends_with(domain)
2861            && host.as_bytes()[host.len() - domain.len() - 1] == b'.'
2862            && host.parse::<std::net::IpAddr>().is_err())
2863}
2864
2865fn path_matches(request: &str, cookie: &str) -> bool {
2866    request == cookie
2867        || (request.starts_with(cookie)
2868            && (cookie.ends_with('/') || request.as_bytes().get(cookie.len()) == Some(&b'/')))
2869}
2870
2871fn default_cookie_path(url: &url::Url) -> String {
2872    let path = url.path();
2873    match path.rfind('/') {
2874        Some(0) | None => "/".to_string(),
2875        Some(i) => path[..i].to_string(),
2876    }
2877}
2878
2879fn parse_cookie_date(text: &str) -> Option<SystemTime> {
2880    httpdate::parse_http_date(text)
2881        .ok()
2882        .or_else(|| httpdate::parse_http_date(&text.replace('-', " ")).ok())
2883}
2884
2885fn parse_set_cookie(url: &url::Url, header: &str, now: SystemTime) -> Option<Cookie> {
2886    let mut parts = header.split(';');
2887    let (name, value) = parts.next()?.split_once('=')?;
2888    let name = name.trim();
2889    if name.is_empty() {
2890        return None;
2891    }
2892    let host = url.host_str()?.to_ascii_lowercase();
2893    let mut cookie = Cookie {
2894        name: name.to_string(),
2895        value: value.trim().to_string(),
2896        domain: host.clone(),
2897        path: default_cookie_path(url),
2898        expires: None,
2899        secure: false,
2900        http_only: false,
2901        host_only: true,
2902    };
2903    let mut max_age = None;
2904    let mut expires = None;
2905    let mut domain = None;
2906    for attribute in parts {
2907        let (key, value) = match attribute.split_once('=') {
2908            Some((k, v)) => (k.trim(), v.trim()),
2909            None => (attribute.trim(), ""),
2910        };
2911        match key.to_ascii_lowercase().as_str() {
2912            "expires" => expires = parse_cookie_date(value),
2913            "max-age" => max_age = value.parse::<i64>().ok(),
2914            "domain" => {
2915                let d = value.trim_start_matches('.').to_ascii_lowercase();
2916                if !d.is_empty() {
2917                    domain = Some(d);
2918                }
2919            }
2920            "path" if value.starts_with('/') => cookie.path = value.to_string(),
2921            "secure" => cookie.secure = true,
2922            "httponly" => cookie.http_only = true,
2923            _ => {}
2924        }
2925    }
2926    if let Some(domain) = domain {
2927        if domain != host && psl::suffix_str(&domain) == Some(domain.as_str()) {
2928            return None;
2929        }
2930        if !domain_matches(&host, &domain) {
2931            return None;
2932        }
2933        cookie.domain = domain;
2934        cookie.host_only = false;
2935    }
2936    cookie.expires = match max_age {
2937        Some(seconds) if seconds <= 0 => Some(UNIX_EPOCH),
2938        Some(seconds) => now.checked_add(Duration::from_secs(seconds as u64)),
2939        None => expires,
2940    };
2941    if cookie.secure && !matches!(url.scheme(), "https" | "wss") {
2942        return None;
2943    }
2944    Some(cookie)
2945}
2946
2947fn encode_cookie_line(c: &Cookie) -> Option<String> {
2948    let expires = c.expires?.duration_since(UNIX_EPOCH).ok()?.as_secs();
2949    let fields = [&c.name, &c.value, &c.domain, &c.path];
2950    if fields.iter().any(|f| f.contains(['\t', '\n', '\r'])) {
2951        return None;
2952    }
2953    let flags: String = [(c.secure, 's'), (c.http_only, 'h'), (c.host_only, 'o')]
2954        .iter()
2955        .filter(|(on, _)| *on)
2956        .map(|(_, f)| *f)
2957        .collect();
2958    Some(format!(
2959        "{}\t{}\t{}\t{}\t{expires}\t{flags}",
2960        c.name, c.value, c.domain, c.path
2961    ))
2962}
2963
2964fn decode_cookie_line(line: &str) -> Option<Cookie> {
2965    let mut fields = line.split('\t');
2966    let name = fields.next()?.to_string();
2967    let value = fields.next()?.to_string();
2968    let domain = fields.next()?.to_string();
2969    let path = fields.next()?.to_string();
2970    let expires = UNIX_EPOCH.checked_add(Duration::from_secs(fields.next()?.parse().ok()?))?;
2971    let flags = fields.next().unwrap_or("");
2972    Some(Cookie {
2973        name,
2974        value,
2975        domain,
2976        path,
2977        expires: Some(expires),
2978        secure: flags.contains('s'),
2979        http_only: flags.contains('h'),
2980        host_only: flags.contains('o'),
2981    })
2982}
2983
2984// ---------------------------------------------------------------------------
2985// Transports
2986// ---------------------------------------------------------------------------
2987
2988// The transport contract beneath [`crate::Client`] (docs/http.md "Transports").
2989//
2990// A transport performs one exchange: it sends a prepared request and reports what the platform
2991// stack saw, as [`Event`]s, in order. Policy (following a redirect, retrying a challenge,
2992// attaching cookies, deciding trust) belongs to the client above it, so every backend applies the
2993// same rules. Where a stack insists on deciding something itself (URLSession asks its delegate
2994// about redirects and challenges), the transport turns that into a [`Question`] and waits for the
2995// client's [`Answer`].
2996//
2997// Apps implement [`Transport`] only to install a test double through `ClientBuilder::transport`.
2998
2999/// What a backend can do. The client consults it to decide what it must do itself, and apps can
3000/// read it (`day_part_http::capabilities()`) to say what a platform offers.
3001#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3002pub struct Capabilities {
3003    /// Response bodies arrive in chunks, pulled on demand.
3004    pub streaming: bool,
3005    /// A request body can be sent from a reader without buffering it first.
3006    pub upload_streaming: bool,
3007    /// Upload progress is reported while a body is sent.
3008    pub upload_progress: bool,
3009    /// The stack hands back redirect responses, so the client can follow and approve each hop.
3010    pub manual_redirects: bool,
3011    /// The stack asks about HTTP challenges itself ([`Question::Auth`]).
3012    pub auth_questions: bool,
3013    /// NTLM and Negotiate are answered by the stack.
3014    pub native_auth_schemes: bool,
3015    /// The stack reports each server certificate chain for evaluation ([`Question::ServerTrust`]).
3016    pub server_trust: bool,
3017    /// A client certificate identity can be presented.
3018    pub client_identity: bool,
3019    /// The platform's own cookie store is available.
3020    pub platform_cookies: bool,
3021    /// The platform's own HTTP cache is available.
3022    pub platform_cache: bool,
3023    /// Transfer metrics are reported.
3024    pub metrics: bool,
3025    /// WebSockets are available.
3026    pub websockets: bool,
3027    /// A WebSocket can send an explicit ping.
3028    pub websocket_ping: bool,
3029    /// A WebSocket handshake can carry custom request headers.
3030    pub websocket_headers: bool,
3031    /// Requests can wait for connectivity instead of failing at once.
3032    pub wait_for_connectivity: bool,
3033}
3034
3035/// How a request may use the platform's cache.
3036#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3037pub enum CachePolicy {
3038    /// Follow the response's cache headers.
3039    #[default]
3040    Default,
3041    /// Always load from the network, ignoring cached data.
3042    Reload,
3043    /// Use cached data when present, whatever its age; load otherwise.
3044    PreferCache,
3045}
3046
3047/// A request body reader shared between clones of a request. A stream can be sent once: a retry
3048/// or a 307 redirect that needs the body again finds it taken and fails.
3049#[derive(Clone)]
3050pub struct SharedReader(Arc<Mutex<Option<Box<dyn Read + Send>>>>);
3051
3052impl SharedReader {
3053    /// Wrap a reader.
3054    pub fn new(reader: impl Read + Send + 'static) -> Self {
3055        Self(Arc::new(Mutex::new(Some(Box::new(reader)))))
3056    }
3057
3058    /// Take the reader; `None` once it was taken.
3059    #[must_use]
3060    pub fn take(&self) -> Option<Box<dyn Read + Send>> {
3061        self.0
3062            .lock()
3063            .unwrap_or_else(std::sync::PoisonError::into_inner)
3064            .take()
3065    }
3066}
3067
3068impl std::fmt::Debug for SharedReader {
3069    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3070        f.write_str("SharedReader")
3071    }
3072}
3073
3074/// The body a transport sends.
3075#[derive(Debug)]
3076pub enum PreparedBody {
3077    Empty,
3078    Bytes(Arc<Vec<u8>>),
3079    File {
3080        path: PathBuf,
3081        len: u64,
3082    },
3083    Stream {
3084        reader: SharedReader,
3085        len: Option<u64>,
3086    },
3087}
3088
3089/// One request, ready for a transport: headers merged, cookies and credentials attached.
3090#[derive(Debug)]
3091pub struct Prepared {
3092    pub method: String,
3093    pub url: String,
3094    pub headers: Vec<(String, String)>,
3095    pub body: PreparedBody,
3096    /// The idle bound: connecting, awaiting the head, and gaps in the body.
3097    pub timeout_idle: Duration,
3098    pub allow_expensive: bool,
3099    pub allow_constrained: bool,
3100    pub cache: CachePolicy,
3101    pub priority: Option<f32>,
3102    /// WebSocket subprotocols, in preference order.
3103    pub protocols: Vec<String>,
3104}
3105
3106/// Per-client settings a transport applies when it is created.
3107#[derive(Clone, Debug)]
3108pub struct TransportConfig {
3109    pub timeout_idle: Duration,
3110    pub timeout_total: Option<Duration>,
3111    pub platform_cookies: bool,
3112    /// `(memory bytes, disk bytes)` for the platform cache; `None` = no cache.
3113    pub platform_cache: Option<(u64, u64)>,
3114    /// A stack with [`Capabilities::manual_redirects`] hands back every redirect whatever this
3115    /// says, and the client applies it; the others follow natively up to the limit, or refuse.
3116    pub redirects: Redirects,
3117    /// The client wants challenges as questions.
3118    pub ask_auth: bool,
3119    /// The client evaluates server trust (pins or a handler).
3120    pub ask_trust: bool,
3121    pub identity: Option<Identity>,
3122    pub max_per_host: Option<u32>,
3123    pub wait_for_connectivity: bool,
3124}
3125
3126/// The response head.
3127#[derive(Clone, Debug, PartialEq, Eq)]
3128pub struct Head {
3129    pub status: u16,
3130    /// In arrival order, duplicates preserved.
3131    pub headers: Vec<(String, String)>,
3132    /// The URL that answered, after any redirects the stack followed itself.
3133    pub url: String,
3134    /// `Content-Length`, when the response declared one.
3135    pub expected_length: Option<u64>,
3136}
3137
3138impl Head {
3139    /// The first header with this name, ASCII case-insensitive.
3140    #[must_use]
3141    pub fn header(&self, name: &str) -> Option<&str> {
3142        self.headers
3143            .iter()
3144            .find(|(k, _)| k.eq_ignore_ascii_case(name))
3145            .map(|(_, v)| v.as_str())
3146    }
3147
3148    /// Every header with this name, in order.
3149    pub fn headers_named<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str> + 'a {
3150        self.headers
3151            .iter()
3152            .filter(move |(k, _)| k.eq_ignore_ascii_case(name))
3153            .map(|(_, v)| v.as_str())
3154    }
3155}
3156
3157/// Timings and facts about one completed transfer. Every field a platform does not report is
3158/// `None`.
3159#[derive(Clone, Debug, Default, PartialEq)]
3160pub struct Metrics {
3161    /// Resolving the host name.
3162    pub dns: Option<Duration>,
3163    /// Establishing the connection, TLS included.
3164    pub connect: Option<Duration>,
3165    /// The TLS handshake.
3166    pub tls: Option<Duration>,
3167    /// From the start of the request to its first response byte.
3168    pub first_byte: Option<Duration>,
3169    /// From the start of the request to its last response byte.
3170    pub total: Option<Duration>,
3171    /// `http/1.1`, `h2`, `h3`.
3172    pub protocol: Option<String>,
3173    pub reused_connection: Option<bool>,
3174    pub proxy: Option<bool>,
3175    pub remote_address: Option<String>,
3176    pub tls_version: Option<String>,
3177    /// The response came from the local cache.
3178    pub from_cache: bool,
3179    pub bytes_sent: Option<u64>,
3180    pub bytes_received: Option<u64>,
3181    /// Redirects followed on the way to this response.
3182    pub redirects: u32,
3183}
3184
3185/// An HTTP authentication scheme.
3186#[derive(Clone, Debug, PartialEq, Eq)]
3187pub enum Scheme {
3188    Basic,
3189    Bearer,
3190    Digest,
3191    Ntlm,
3192    Negotiate,
3193    Other(String),
3194}
3195
3196impl Scheme {
3197    pub(crate) fn parse(token: &str) -> Scheme {
3198        match token.to_ascii_lowercase().as_str() {
3199            "basic" => Scheme::Basic,
3200            "bearer" => Scheme::Bearer,
3201            "digest" => Scheme::Digest,
3202            "ntlm" => Scheme::Ntlm,
3203            "negotiate" => Scheme::Negotiate,
3204            _ => Scheme::Other(token.to_string()),
3205        }
3206    }
3207
3208    /// Schemes a stack with native challenge handling (`URLSession`) raises as questions itself.
3209    pub(crate) fn raised_natively(&self) -> bool {
3210        matches!(
3211            self,
3212            Scheme::Basic | Scheme::Digest | Scheme::Ntlm | Scheme::Negotiate
3213        )
3214    }
3215}
3216
3217/// The certificate chain a server presented, with the platform's own verdict on it.
3218#[derive(Clone, Debug, PartialEq, Eq)]
3219pub struct ServerTrust {
3220    pub host: String,
3221    /// DER certificates, leaf first.
3222    pub chain: Vec<Vec<u8>>,
3223    /// The platform's trust evaluation passed.
3224    pub system_trusted: bool,
3225    /// Why it failed, when it did.
3226    pub system_error: Option<String>,
3227}
3228
3229impl ServerTrust {
3230    /// Each certificate's public-key pin, `sha256/<base64>`, leaf first, the value
3231    /// `Trust::pin` takes.
3232    #[must_use]
3233    pub fn pins(&self) -> Vec<String> {
3234        self.chain
3235            .iter()
3236            .filter_map(|der| spki_sha256(der))
3237            .map(|h| pin_string(&h))
3238            .collect()
3239    }
3240}
3241
3242/// A challenge a stack raised itself.
3243#[derive(Clone, Debug, PartialEq, Eq)]
3244pub struct AuthQuestion {
3245    pub host: String,
3246    pub port: u16,
3247    pub realm: Option<String>,
3248    pub scheme: Scheme,
3249    pub proxy: bool,
3250    pub previous_failures: u32,
3251}
3252
3253/// Something the stack waits on the client for.
3254#[derive(Clone, Debug, PartialEq, Eq)]
3255pub enum Question {
3256    Auth(AuthQuestion),
3257    ServerTrust(ServerTrust),
3258}
3259
3260/// The identifier a transport pairs a question with its answer by.
3261pub type QuestionId = u64;
3262
3263/// The client's answer to a [`Question`].
3264#[derive(Clone, Debug, PartialEq, Eq)]
3265pub enum Answer {
3266    Credential {
3267        user: String,
3268        password: String,
3269    },
3270    /// Let the stack decide: for a challenge, deliver the 401; for trust, the platform verdict.
3271    DefaultHandling,
3272    /// Abandon the request.
3273    Cancel,
3274    /// Trust the server despite the platform verdict.
3275    Accept,
3276    /// Refuse the server.
3277    Reject,
3278}
3279
3280/// What a transport reports about one exchange, in order.
3281#[derive(Debug)]
3282pub enum Event {
3283    Head(Head),
3284    Chunk(Vec<u8>),
3285    Sent { sent: u64, total: Option<u64> },
3286    Question(QuestionId, Question),
3287    Metrics(Metrics),
3288    End,
3289    Failed(HttpError),
3290}
3291
3292/// The sink a transport reports through.
3293pub type Events = Arc<dyn Fn(Event) + Send + Sync>;
3294
3295/// The client's grip on one exchange.
3296pub trait Transfer: Send + Sync {
3297    /// Read up to `chunks` more body chunks.
3298    fn demand(&self, chunks: u32);
3299    /// Answer a question the transport raised.
3300    fn answer(&self, id: QuestionId, answer: Answer);
3301    /// Abandon the exchange. A transport still reports a terminal event afterwards.
3302    fn cancel(&self);
3303}
3304
3305/// A WebSocket message.
3306#[derive(Clone, Debug, PartialEq, Eq)]
3307pub enum Message {
3308    Text(String),
3309    Binary(Vec<u8>),
3310    /// The peer closed the connection; nothing follows.
3311    Close {
3312        code: u16,
3313        reason: String,
3314    },
3315}
3316
3317/// What a transport reports about one WebSocket.
3318#[derive(Debug)]
3319pub enum WsEvent {
3320    Open { protocol: Option<String> },
3321    Message(Message),
3322    Closed { code: u16, reason: String },
3323    Failed(HttpError),
3324}
3325
3326/// The sink a WebSocket transport reports through.
3327pub type WsEvents = Arc<dyn Fn(WsEvent) + Send + Sync>;
3328
3329/// A completion callback.
3330pub type Completion = Box<dyn FnOnce(Result<(), HttpError>) + Send>;
3331
3332/// The client's grip on one WebSocket.
3333pub trait Socket: Send + Sync {
3334    fn send(&self, message: Message, done: Completion);
3335    fn ping(&self, done: Completion);
3336    fn close(&self, code: u16, reason: &str);
3337    /// Receive up to `messages` more messages.
3338    fn demand(&self, messages: u32);
3339}
3340
3341/// One backend.
3342pub trait Transport: Send + Sync + 'static {
3343    fn capabilities(&self) -> Capabilities;
3344    /// Start an exchange. Events may arrive before this returns.
3345    fn start(&self, request: Prepared, events: Events) -> Arc<dyn Transfer>;
3346    /// Open a WebSocket.
3347    fn websocket(&self, request: Prepared, events: WsEvents) -> Arc<dyn Socket> {
3348        let _ = request;
3349        events(WsEvent::Failed(HttpError::Unsupported));
3350        Arc::new(NoSocket)
3351    }
3352    /// The platform store's cookies, for [`Cookies::Platform`].
3353    fn cookies(&self) -> Vec<Cookie> {
3354        Vec::new()
3355    }
3356    /// Forget the platform store's cookies.
3357    fn clear_cookies(&self) {}
3358    /// Empty the platform cache.
3359    fn clear_cache(&self) {}
3360}
3361
3362struct NoSocket;
3363
3364impl Socket for NoSocket {
3365    fn send(&self, _message: Message, done: Completion) {
3366        done(Err(HttpError::Unsupported));
3367    }
3368    fn ping(&self, done: Completion) {
3369        done(Err(HttpError::Unsupported));
3370    }
3371    fn close(&self, _code: u16, _reason: &str) {}
3372    fn demand(&self, _messages: u32) {}
3373}
3374
3375// ---------------------------------------------------------------------------
3376// Pins
3377// ---------------------------------------------------------------------------
3378
3379// Public-key pins (docs/http.md "Trust"): the SHA-256 of a certificate's SubjectPublicKeyInfo,
3380// written `sha256/<base64>`. Pinning the key rather than the certificate survives a renewal that
3381// keeps the key. The DER walk here reads exactly as far as the SPKI and no further.
3382
3383const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3384
3385/// Standard base64 with padding.
3386pub(crate) fn base64_encode(bytes: &[u8]) -> String {
3387    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
3388    for chunk in bytes.chunks(3) {
3389        let b = [
3390            chunk[0],
3391            *chunk.get(1).unwrap_or(&0),
3392            *chunk.get(2).unwrap_or(&0),
3393        ];
3394        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
3395        out.push(B64[(n >> 18) as usize & 63] as char);
3396        out.push(B64[(n >> 12) as usize & 63] as char);
3397        out.push(if chunk.len() > 1 {
3398            B64[(n >> 6) as usize & 63] as char
3399        } else {
3400            '='
3401        });
3402        out.push(if chunk.len() > 2 {
3403            B64[n as usize & 63] as char
3404        } else {
3405            '='
3406        });
3407    }
3408    out
3409}
3410
3411/// Standard base64, padding optional, whitespace ignored. `None` on any other character.
3412pub(crate) fn base64_decode(text: &str) -> Option<Vec<u8>> {
3413    let mut acc = 0u32;
3414    let mut bits = 0u32;
3415    let mut out = Vec::with_capacity(text.len() * 3 / 4);
3416    for c in text.bytes() {
3417        let v = match c {
3418            b'A'..=b'Z' => c - b'A',
3419            b'a'..=b'z' => c - b'a' + 26,
3420            b'0'..=b'9' => c - b'0' + 52,
3421            b'+' => 62,
3422            b'/' => 63,
3423            b'=' => break,
3424            b' ' | b'\n' | b'\r' | b'\t' => continue,
3425            _ => return None,
3426        };
3427        acc = (acc << 6) | u32::from(v);
3428        bits += 6;
3429        if bits >= 8 {
3430            bits -= 8;
3431            out.push((acc >> bits) as u8);
3432            acc &= (1 << bits) - 1;
3433        }
3434    }
3435    Some(out)
3436}
3437
3438pub(crate) fn sha256(bytes: &[u8]) -> [u8; 32] {
3439    let digest = Sha256::digest(bytes);
3440    let mut out = [0u8; 32];
3441    out.copy_from_slice(digest.as_slice());
3442    out
3443}
3444
3445pub(crate) fn hex(bytes: &[u8]) -> String {
3446    use std::fmt::Write as _;
3447    let mut s = String::with_capacity(bytes.len() * 2);
3448    for b in bytes {
3449        let _ = write!(s, "{b:02x}");
3450    }
3451    s
3452}
3453
3454/// One DER element: `(tag, content, the whole element, what follows it)`.
3455type Tlv<'a> = (u8, &'a [u8], &'a [u8], &'a [u8]);
3456
3457/// Read the DER element at the start of `data`.
3458fn read_tlv(data: &[u8]) -> Option<Tlv<'_>> {
3459    let tag = *data.first()?;
3460    let first = *data.get(1)?;
3461    let (len, header) = if first & 0x80 == 0 {
3462        (usize::from(first), 2)
3463    } else {
3464        let n = usize::from(first & 0x7f);
3465        if n == 0 || n > 4 {
3466            return None;
3467        }
3468        let mut len = 0usize;
3469        for i in 0..n {
3470            len = (len << 8) | usize::from(*data.get(2 + i)?);
3471        }
3472        (len, 2 + n)
3473    };
3474    let end = header.checked_add(len)?;
3475    if data.len() < end {
3476        return None;
3477    }
3478    Some((tag, &data[header..end], &data[..end], &data[end..]))
3479}
3480
3481/// The `SubjectPublicKeyInfo` element of a DER certificate.
3482///
3483/// `Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, signature }` and
3484/// `TBSCertificate ::= SEQUENCE { [0] version OPTIONAL, serialNumber, signature, issuer, validity,
3485/// subject, subjectPublicKeyInfo, … }`.
3486pub(crate) fn spki(cert: &[u8]) -> Option<&[u8]> {
3487    const SEQUENCE: u8 = 0x30;
3488    let (tag, certificate, _, _) = read_tlv(cert)?;
3489    if tag != SEQUENCE {
3490        return None;
3491    }
3492    let (tag, tbs, _, _) = read_tlv(certificate)?;
3493    if tag != SEQUENCE {
3494        return None;
3495    }
3496    let mut rest = tbs;
3497    let (tag, _, _, after) = read_tlv(rest)?;
3498    if tag == 0xa0 {
3499        rest = after;
3500    }
3501    for _ in 0..5 {
3502        let (_, _, _, after) = read_tlv(rest)?;
3503        rest = after;
3504    }
3505    let (tag, _, whole, _) = read_tlv(rest)?;
3506    (tag == SEQUENCE).then_some(whole)
3507}
3508
3509/// The SHA-256 of a certificate's SPKI.
3510pub(crate) fn spki_sha256(cert: &[u8]) -> Option<[u8; 32]> {
3511    spki(cert).map(sha256)
3512}
3513
3514/// `sha256/<base64>`.
3515pub(crate) fn pin_string(hash: &[u8; 32]) -> String {
3516    format!("sha256/{}", base64_encode(hash))
3517}
3518
3519/// Parse `sha256/<base64>` (the prefix optional).
3520pub(crate) fn parse_pin(pin: &str) -> Option<[u8; 32]> {
3521    let text = pin.trim();
3522    let text = text.strip_prefix("sha256/").unwrap_or(text);
3523    let bytes = base64_decode(text)?;
3524    <[u8; 32]>::try_from(bytes.as_slice()).ok()
3525}
3526
3527#[cfg(test)]
3528mod pin_tests {
3529    use super::*;
3530
3531    fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
3532        let mut out = vec![tag];
3533        if content.len() < 0x80 {
3534            out.push(content.len() as u8);
3535        } else {
3536            out.push(0x82);
3537            out.extend_from_slice(&(content.len() as u16).to_be_bytes());
3538        }
3539        out.extend_from_slice(content);
3540        out
3541    }
3542
3543    #[test]
3544    fn base64_round_trips() {
3545        // RFC 4648's vectors: each prefix of "foobar".
3546        let full = b"foobar";
3547        let expected = [
3548            "", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy",
3549        ];
3550        for (n, want) in expected.iter().enumerate() {
3551            let sample = &full[..n];
3552            assert_eq!(base64_encode(sample), *want);
3553            assert_eq!(base64_decode(want).as_deref(), Some(sample));
3554        }
3555    }
3556
3557    #[test]
3558    fn the_spki_is_found_after_the_optional_version() {
3559        let spki_elem = tlv(0x30, &[0x30, 0x00, 0x03, 0x02, 0x00, 0xAA]);
3560        let mut tbs = Vec::new();
3561        tbs.extend(tlv(0xa0, &tlv(0x02, &[2])));
3562        tbs.extend(tlv(0x02, &[1]));
3563        for _ in 0..4 {
3564            tbs.extend(tlv(0x30, &[]));
3565        }
3566        tbs.extend(spki_elem.clone());
3567        tbs.extend(tlv(0xa3, &[0x30, 0x00]));
3568        let mut cert = tlv(0x30, &tbs);
3569        cert.extend(tlv(0x30, &[]));
3570        let cert = tlv(0x30, &cert);
3571        assert_eq!(spki(&cert), Some(spki_elem.as_slice()));
3572        let pin = pin_string(&spki_sha256(&cert).unwrap());
3573        assert_eq!(parse_pin(&pin), Some(sha256(&spki_elem)));
3574    }
3575
3576    #[test]
3577    fn a_malformed_certificate_has_no_spki() {
3578        assert_eq!(spki(&[0x30, 0x05, 0x30]), None);
3579        assert_eq!(spki(&[]), None);
3580    }
3581}
3582
3583// ---------------------------------------------------------------------------
3584// Challenges
3585// ---------------------------------------------------------------------------
3586
3587// HTTP authentication the client performs itself (docs/http.md "Challenges"): parsing
3588// `WWW-Authenticate` and `Proxy-Authenticate`, and writing Basic, Bearer and Digest credentials.
3589// NTLM and Negotiate are handshakes only an OS stack performs; those arrive as questions from a
3590// transport that can answer them.
3591
3592/// One challenge: its scheme and parameters (names lowercased).
3593#[derive(Clone, Debug, PartialEq, Eq)]
3594pub(crate) struct ParsedChallenge {
3595    pub scheme: Scheme,
3596    pub params: Vec<(String, String)>,
3597}
3598
3599impl ParsedChallenge {
3600    pub(crate) fn param(&self, name: &str) -> Option<&str> {
3601        self.params
3602            .iter()
3603            .find(|(k, _)| k == name)
3604            .map(|(_, v)| v.as_str())
3605    }
3606}
3607
3608/// Every challenge in the response's `WWW-Authenticate` (or `Proxy-Authenticate`) headers, in
3609/// order.
3610pub(crate) fn parse_challenges(headers: &[(String, String)], proxy: bool) -> Vec<ParsedChallenge> {
3611    let name = if proxy {
3612        "proxy-authenticate"
3613    } else {
3614        "www-authenticate"
3615    };
3616    let mut out = Vec::new();
3617    for (_, value) in headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case(name)) {
3618        parse_value(value, &mut out);
3619    }
3620    out
3621}
3622
3623fn parse_value(value: &str, out: &mut Vec<ParsedChallenge>) {
3624    for item in split_outside_quotes(value) {
3625        let item = item.trim();
3626        if item.is_empty() {
3627            continue;
3628        }
3629        let (first, rest) = match item.find(char::is_whitespace) {
3630            Some(i) => (&item[..i], item[i..].trim()),
3631            None => (item, ""),
3632        };
3633        if first.contains('=') {
3634            push_param(out, item);
3635        } else {
3636            out.push(ParsedChallenge {
3637                scheme: Scheme::parse(first),
3638                params: Vec::new(),
3639            });
3640            if !rest.is_empty() {
3641                push_param(out, rest);
3642            }
3643        }
3644    }
3645}
3646
3647fn push_param(out: &mut [ParsedChallenge], text: &str) {
3648    let Some(last) = out.last_mut() else {
3649        return;
3650    };
3651    match text.split_once('=') {
3652        Some((k, v)) if !k.trim().is_empty() => last
3653            .params
3654            .push((k.trim().to_ascii_lowercase(), unquote(v.trim()))),
3655        _ => last.params.push(("token68".into(), text.to_string())),
3656    }
3657}
3658
3659fn split_outside_quotes(value: &str) -> Vec<String> {
3660    let mut items = Vec::new();
3661    let mut current = String::new();
3662    let mut quoted = false;
3663    let mut escaped = false;
3664    for c in value.chars() {
3665        if escaped {
3666            current.push(c);
3667            escaped = false;
3668            continue;
3669        }
3670        match c {
3671            '\\' if quoted => {
3672                current.push(c);
3673                escaped = true;
3674            }
3675            '"' => {
3676                quoted = !quoted;
3677                current.push(c);
3678            }
3679            ',' if !quoted => items.push(std::mem::take(&mut current)),
3680            _ => current.push(c),
3681        }
3682    }
3683    items.push(current);
3684    items
3685}
3686
3687fn unquote(value: &str) -> String {
3688    let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) else {
3689        return value.to_string();
3690    };
3691    let mut out = String::with_capacity(inner.len());
3692    let mut escaped = false;
3693    for c in inner.chars() {
3694        if escaped {
3695            out.push(c);
3696            escaped = false;
3697        } else if c == '\\' {
3698            escaped = true;
3699        } else {
3700            out.push(c);
3701        }
3702    }
3703    out
3704}
3705
3706/// `Basic <base64(user:password)>`.
3707pub(crate) fn basic_authorization(user: &str, password: &str) -> String {
3708    format!(
3709        "Basic {}",
3710        base64_encode(format!("{user}:{password}").as_bytes())
3711    )
3712}
3713
3714/// A fresh client nonce.
3715fn digest_cnonce() -> String {
3716    static CNONCES: AtomicU64 = AtomicU64::new(1);
3717    let n = CNONCES.fetch_add(1, Ordering::Relaxed);
3718    let now = std::time::SystemTime::now()
3719        .duration_since(std::time::UNIX_EPOCH)
3720        .map_or(0, |d| d.as_nanos());
3721    hex(&sha256(format!("{n}:{now}").as_bytes())[..8])
3722}
3723
3724fn md5_hex(text: &str) -> String {
3725    use md5::{Digest, Md5};
3726    let digest = Md5::digest(text.as_bytes());
3727    hex(digest.as_slice())
3728}
3729
3730/// The `Authorization` value answering a Digest challenge (RFC 7616, `qop=auth`), or `None` when
3731/// the challenge lacks what it needs or names an algorithm this does not implement.
3732pub(crate) fn digest_authorization(
3733    challenge: &ParsedChallenge,
3734    user: &str,
3735    password: &str,
3736    method: &str,
3737    uri: &str,
3738) -> Option<String> {
3739    use std::fmt::Write as _;
3740    let realm = challenge.param("realm")?;
3741    let nonce = challenge.param("nonce")?;
3742    let algorithm = challenge.param("algorithm").unwrap_or("MD5");
3743    let hash = |text: String| -> Option<String> {
3744        match algorithm.to_ascii_uppercase().as_str() {
3745            "MD5" => Some(md5_hex(&text)),
3746            "SHA-256" => Some(hex(&sha256(text.as_bytes()))),
3747            _ => None,
3748        }
3749    };
3750    let ha1 = hash(format!("{user}:{realm}:{password}"))?;
3751    let ha2 = hash(format!("{method}:{uri}"))?;
3752    let auth_qop = challenge
3753        .param("qop")
3754        .is_some_and(|q| q.split(',').any(|t| t.trim() == "auth"));
3755    let mut value = format!(
3756        "Digest username=\"{user}\", realm=\"{realm}\", nonce=\"{nonce}\", uri=\"{uri}\", \
3757         algorithm={algorithm}"
3758    );
3759    if auth_qop {
3760        let nc = "00000001";
3761        let cnonce = digest_cnonce();
3762        let response = hash(format!("{ha1}:{nonce}:{nc}:{cnonce}:auth:{ha2}"))?;
3763        let _ = write!(
3764            value,
3765            ", response=\"{response}\", qop=auth, nc={nc}, cnonce=\"{cnonce}\""
3766        );
3767    } else {
3768        let response = hash(format!("{ha1}:{nonce}:{ha2}"))?;
3769        let _ = write!(value, ", response=\"{response}\"");
3770    }
3771    if let Some(opaque) = challenge.param("opaque") {
3772        let _ = write!(value, ", opaque=\"{opaque}\"");
3773    }
3774    Some(value)
3775}
3776
3777/// Check a Digest `Authorization` value against the expected credentials; the test server
3778/// verifies with it.
3779// The test server, its one caller, is native-only.
3780#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
3781pub(crate) fn verify_digest(authorization: &str, user: &str, password: &str, method: &str) -> bool {
3782    let Some(rest) = authorization.strip_prefix("Digest ") else {
3783        return false;
3784    };
3785    let mut parsed = Vec::new();
3786    parse_value(&format!("Digest {rest}"), &mut parsed);
3787    let Some(p) = parsed.first() else {
3788        return false;
3789    };
3790    let (Some(realm), Some(nonce), Some(uri), Some(response)) = (
3791        p.param("realm"),
3792        p.param("nonce"),
3793        p.param("uri"),
3794        p.param("response"),
3795    ) else {
3796        return false;
3797    };
3798    if p.param("username") != Some(user) {
3799        return false;
3800    }
3801    let ha1 = md5_hex(&format!("{user}:{realm}:{password}"));
3802    let ha2 = md5_hex(&format!("{method}:{uri}"));
3803    let expected = match (p.param("qop"), p.param("nc"), p.param("cnonce")) {
3804        (Some(qop), Some(nc), Some(cnonce)) => {
3805            md5_hex(&format!("{ha1}:{nonce}:{nc}:{cnonce}:{qop}:{ha2}"))
3806        }
3807        _ => md5_hex(&format!("{ha1}:{nonce}:{ha2}")),
3808    };
3809    expected == response
3810}
3811
3812#[cfg(test)]
3813mod auth_tests {
3814    use super::*;
3815
3816    fn headers(values: &[&str]) -> Vec<(String, String)> {
3817        values
3818            .iter()
3819            .map(|v| ("WWW-Authenticate".to_string(), v.to_string()))
3820            .collect()
3821    }
3822
3823    #[test]
3824    fn parses_several_challenges_with_quoted_commas() {
3825        let parsed = parse_challenges(
3826            &headers(&[
3827                r#"Basic realm="Day, test", charset="UTF-8""#,
3828                r#"Bearer realm="api", error="invalid_token""#,
3829            ]),
3830            false,
3831        );
3832        assert_eq!(parsed.len(), 2);
3833        assert_eq!(parsed[0].scheme, Scheme::Basic);
3834        assert_eq!(parsed[0].param("realm"), Some("Day, test"));
3835        assert_eq!(parsed[0].param("charset"), Some("UTF-8"));
3836        assert_eq!(parsed[1].scheme, Scheme::Bearer);
3837        assert_eq!(parsed[1].param("error"), Some("invalid_token"));
3838    }
3839
3840    #[test]
3841    fn parses_two_challenges_in_one_header() {
3842        let parsed = parse_challenges(
3843            &headers(&[r#"Negotiate, Digest realm="r", nonce="n", qop="auth""#]),
3844            false,
3845        );
3846        assert_eq!(parsed.len(), 2);
3847        assert_eq!(parsed[0].scheme, Scheme::Negotiate);
3848        assert_eq!(parsed[1].scheme, Scheme::Digest);
3849        assert_eq!(parsed[1].param("nonce"), Some("n"));
3850    }
3851
3852    #[test]
3853    fn basic_encodes_the_pair() {
3854        assert_eq!(
3855            basic_authorization("Aladdin", "open sesame"),
3856            "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
3857        );
3858    }
3859
3860    #[test]
3861    fn a_digest_answer_verifies() {
3862        let challenge = parse_challenges(
3863            &headers(&[r#"Digest realm="Day test", nonce="abc", qop="auth", opaque="xyz""#]),
3864            false,
3865        )
3866        .remove(0);
3867        let value = digest_authorization(
3868            &challenge,
3869            "day",
3870            "sunrise",
3871            "GET",
3872            "/digest-auth/day/sunrise",
3873        )
3874        .expect("answer");
3875        assert!(value.contains("opaque=\"xyz\""), "{value}");
3876        assert!(verify_digest(&value, "day", "sunrise", "GET"));
3877        assert!(!verify_digest(&value, "day", "sunset", "GET"));
3878    }
3879}
3880
3881// ---------------------------------------------------------------------------
3882// Multipart forms
3883// ---------------------------------------------------------------------------
3884
3885// `multipart/form-data` bodies (docs/http.md "Uploads"), encoded as a stream: a file part is read
3886// from disk while it is sent, so a form carrying a large file never sits in memory.
3887
3888#[derive(Clone, Debug)]
3889enum PartBody {
3890    Bytes(Vec<u8>),
3891    File(PathBuf),
3892}
3893
3894#[derive(Clone, Debug)]
3895struct Part {
3896    name: String,
3897    filename: Option<String>,
3898    content_type: Option<String>,
3899    body: PartBody,
3900}
3901
3902/// A multipart form. Build it, then hand it to `Request::form`.
3903#[derive(Clone, Debug)]
3904#[must_use]
3905pub struct Form {
3906    boundary: String,
3907    parts: Vec<Part>,
3908}
3909
3910impl Default for Form {
3911    fn default() -> Self {
3912        Self::new()
3913    }
3914}
3915
3916impl Form {
3917    /// An empty form with a fresh boundary.
3918    pub fn new() -> Self {
3919        static BOUNDARIES: AtomicU64 = AtomicU64::new(1);
3920        let n = BOUNDARIES.fetch_add(1, Ordering::Relaxed);
3921        let seed = std::time::SystemTime::now()
3922            .duration_since(std::time::UNIX_EPOCH)
3923            .map_or(0, |d| d.as_nanos());
3924        let hash = sha256(format!("{n}:{seed}").as_bytes());
3925        Self {
3926            boundary: format!("day-{}", hex(&hash[..12])),
3927            parts: Vec::new(),
3928        }
3929    }
3930
3931    /// A text field.
3932    pub fn text(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
3933        self.parts.push(Part {
3934            name: name.into(),
3935            filename: None,
3936            content_type: None,
3937            body: PartBody::Bytes(value.into().into_bytes()),
3938        });
3939        self
3940    }
3941
3942    /// A file part from bytes in memory.
3943    pub fn bytes(
3944        mut self,
3945        name: impl Into<String>,
3946        filename: impl Into<String>,
3947        content_type: impl Into<String>,
3948        bytes: Vec<u8>,
3949    ) -> Self {
3950        self.parts.push(Part {
3951            name: name.into(),
3952            filename: Some(filename.into()),
3953            content_type: Some(content_type.into()),
3954            body: PartBody::Bytes(bytes),
3955        });
3956        self
3957    }
3958
3959    /// A file part read from disk while the form is sent.
3960    pub fn file(
3961        mut self,
3962        name: impl Into<String>,
3963        path: impl Into<PathBuf>,
3964        content_type: impl Into<String>,
3965    ) -> Self {
3966        let path = path.into();
3967        let filename = path
3968            .file_name()
3969            .map_or_else(|| "file".into(), |n| n.to_string_lossy().into_owned());
3970        self.parts.push(Part {
3971            name: name.into(),
3972            filename: Some(filename),
3973            content_type: Some(content_type.into()),
3974            body: PartBody::File(path),
3975        });
3976        self
3977    }
3978
3979    /// The `Content-Type` header value, boundary included.
3980    #[must_use]
3981    pub fn content_type(&self) -> String {
3982        format!("multipart/form-data; boundary={}", self.boundary)
3983    }
3984
3985    fn part_header(&self, part: &Part) -> Vec<u8> {
3986        use std::fmt::Write as _;
3987        let escape = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
3988        let mut head = format!(
3989            "--{}\r\nContent-Disposition: form-data; name=\"{}\"",
3990            self.boundary,
3991            escape(&part.name)
3992        );
3993        if let Some(filename) = &part.filename {
3994            let _ = write!(head, "; filename=\"{}\"", escape(filename));
3995        }
3996        head.push_str("\r\n");
3997        if let Some(ct) = &part.content_type {
3998            let _ = write!(head, "Content-Type: {ct}\r\n");
3999        }
4000        head.push_str("\r\n");
4001        head.into_bytes()
4002    }
4003
4004    /// The encoded body as a reader, with its exact length.
4005    pub(crate) fn reader(&self) -> std::io::Result<(Box<dyn Read + Send>, u64)> {
4006        let mut pieces: VecDeque<Box<dyn Read + Send>> = VecDeque::new();
4007        let mut len = 0u64;
4008        for part in &self.parts {
4009            let head = self.part_header(part);
4010            len += head.len() as u64;
4011            pieces.push_back(Box::new(Cursor::new(head)));
4012            match &part.body {
4013                PartBody::Bytes(bytes) => {
4014                    len += bytes.len() as u64;
4015                    pieces.push_back(Box::new(Cursor::new(bytes.clone())));
4016                }
4017                PartBody::File(path) => {
4018                    let file = std::fs::File::open(path)?;
4019                    len += file.metadata()?.len();
4020                    pieces.push_back(Box::new(file));
4021                }
4022            }
4023            len += 2;
4024            pieces.push_back(Box::new(Cursor::new(b"\r\n".to_vec())));
4025        }
4026        let tail = format!("--{}--\r\n", self.boundary).into_bytes();
4027        len += tail.len() as u64;
4028        pieces.push_back(Box::new(Cursor::new(tail)));
4029        Ok((Box::new(Chain { pieces }), len))
4030    }
4031}
4032
4033struct Chain {
4034    pieces: VecDeque<Box<dyn Read + Send>>,
4035}
4036
4037impl Read for Chain {
4038    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
4039        while let Some(front) = self.pieces.front_mut() {
4040            let n = front.read(buf)?;
4041            if n > 0 {
4042                return Ok(n);
4043            }
4044            self.pieces.pop_front();
4045        }
4046        Ok(0)
4047    }
4048}
4049
4050#[cfg(test)]
4051mod form_tests {
4052    use super::*;
4053
4054    #[test]
4055    fn the_declared_length_is_the_encoded_length() {
4056        let form = Form::new().text("title", "Sunrise").bytes(
4057            "photo",
4058            "day.png",
4059            "image/png",
4060            vec![1, 2, 3, 4],
4061        );
4062        let (mut reader, len) = form.reader().expect("reader");
4063        let mut out = Vec::new();
4064        reader.read_to_end(&mut out).expect("read");
4065        assert_eq!(out.len() as u64, len);
4066        let text = String::from_utf8_lossy(&out);
4067        assert!(text.contains("name=\"title\"\r\n\r\nSunrise\r\n"), "{text}");
4068        assert!(
4069            text.contains("filename=\"day.png\"\r\nContent-Type: image/png"),
4070            "{text}"
4071        );
4072        assert!(text.ends_with(&format!("--{}--\r\n", form.boundary)));
4073    }
4074}
4075
4076#[cfg(all(test, not(target_arch = "wasm32")))]
4077mod client_tests {
4078    use super::*;
4079    use std::sync::atomic::AtomicUsize;
4080
4081    #[derive(Clone, Debug)]
4082    struct Seen {
4083        method: String,
4084        url: String,
4085        headers: Vec<(String, String)>,
4086    }
4087
4088    impl Seen {
4089        fn header(&self, name: &str) -> Option<&str> {
4090            self.headers
4091                .iter()
4092                .find(|(k, _)| k.eq_ignore_ascii_case(name))
4093                .map(|(_, v)| v.as_str())
4094        }
4095    }
4096
4097    #[derive(Default)]
4098    struct Reply {
4099        status: u16,
4100        headers: Vec<(String, String)>,
4101        chunks: Vec<Vec<u8>>,
4102        question: Option<Question>,
4103        stall: bool,
4104        #[expect(
4105            clippy::option_option,
4106            reason = "the outer `None` derives the length from the chunks; the inner one is the length the reply advertises, which can be absent"
4107        )]
4108        expected: Option<Option<u64>>,
4109    }
4110
4111    impl Reply {
4112        fn new(status: u16) -> Reply {
4113            Reply {
4114                status,
4115                ..Reply::default()
4116            }
4117        }
4118        fn header(mut self, name: &str, value: &str) -> Reply {
4119            self.headers.push((name.into(), value.into()));
4120            self
4121        }
4122        fn body(mut self, text: &str) -> Reply {
4123            self.chunks = vec![text.as_bytes().to_vec()];
4124            self
4125        }
4126        fn chunks(mut self, n: u8) -> Reply {
4127            self.chunks = (0..n).map(|i| vec![i]).collect();
4128            self
4129        }
4130        fn question(mut self, question: Question) -> Reply {
4131            self.question = Some(question);
4132            self
4133        }
4134        fn stall(mut self) -> Reply {
4135            self.stall = true;
4136            self
4137        }
4138    }
4139
4140    type Script = dyn Fn(&Seen) -> Reply + Send + Sync;
4141
4142    /// A transport that answers each exchange from a script, pulled by demand.
4143    #[derive(Clone)]
4144    struct Scripted {
4145        caps: Capabilities,
4146        script: Arc<Script>,
4147        seen: Arc<Mutex<Vec<Seen>>>,
4148        granted: Arc<AtomicU64>,
4149        cancels: Arc<AtomicUsize>,
4150        answers: Arc<Mutex<Vec<Answer>>>,
4151    }
4152
4153    impl Scripted {
4154        fn new(script: impl Fn(&Seen) -> Reply + Send + Sync + 'static) -> Scripted {
4155            Scripted {
4156                caps: Capabilities {
4157                    streaming: true,
4158                    manual_redirects: true,
4159                    server_trust: true,
4160                    websockets: true,
4161                    ..Capabilities::default()
4162                },
4163                script: Arc::new(script),
4164                seen: Arc::default(),
4165                granted: Arc::default(),
4166                cancels: Arc::default(),
4167                answers: Arc::default(),
4168            }
4169        }
4170
4171        fn seen(&self) -> Vec<Seen> {
4172            lock(&self.seen).clone()
4173        }
4174    }
4175
4176    struct ExchangeState {
4177        events: Option<Events>,
4178        head: Option<Head>,
4179        chunks: VecDeque<Vec<u8>>,
4180        demand: u32,
4181        waiting: bool,
4182        emitting: bool,
4183        /// Emits nothing but keeps its events until cancelled, like a real stalled exchange; that
4184        /// hold is what keeps a callback-started flight alive.
4185        stalled: bool,
4186    }
4187
4188    struct ScriptedTransfer {
4189        owner: Scripted,
4190        state: Mutex<ExchangeState>,
4191    }
4192
4193    impl ScriptedTransfer {
4194        fn pump(&self) {
4195            loop {
4196                let (events, event) = {
4197                    let mut st = lock(&self.state);
4198                    if st.emitting || st.waiting || st.stalled {
4199                        return;
4200                    }
4201                    let Some(events) = st.events.clone() else {
4202                        return;
4203                    };
4204                    let event = if let Some(head) = st.head.take() {
4205                        Event::Head(head)
4206                    } else if st.chunks.is_empty() {
4207                        st.events = None;
4208                        Event::End
4209                    } else if st.demand == 0 {
4210                        return;
4211                    } else {
4212                        st.demand -= 1;
4213                        Event::Chunk(st.chunks.pop_front().unwrap_or_default())
4214                    };
4215                    st.emitting = true;
4216                    (events, event)
4217                };
4218                events(event);
4219                lock(&self.state).emitting = false;
4220            }
4221        }
4222    }
4223
4224    impl Transfer for ScriptedTransfer {
4225        fn demand(&self, chunks: u32) {
4226            self.owner
4227                .granted
4228                .fetch_add(u64::from(chunks), Ordering::SeqCst);
4229            lock(&self.state).demand += chunks;
4230            self.pump();
4231        }
4232
4233        fn answer(&self, _id: QuestionId, answer: Answer) {
4234            lock(&self.owner.answers).push(answer.clone());
4235            let refused = {
4236                let mut st = lock(&self.state);
4237                st.waiting = false;
4238                if matches!(answer, Answer::Reject | Answer::Cancel) {
4239                    st.events.take()
4240                } else {
4241                    None
4242                }
4243            };
4244            match refused {
4245                Some(events) => events(Event::Failed(HttpError::Tls("refused".into()))),
4246                None => self.pump(),
4247            }
4248        }
4249
4250        fn cancel(&self) {
4251            self.owner.cancels.fetch_add(1, Ordering::SeqCst);
4252            let events = lock(&self.state).events.take();
4253            if let Some(events) = events {
4254                events(Event::Failed(HttpError::Cancelled));
4255            }
4256        }
4257    }
4258
4259    struct EchoState {
4260        events: Option<WsEvents>,
4261        queue: VecDeque<Message>,
4262        demand: u32,
4263    }
4264
4265    struct EchoSocket(Mutex<EchoState>);
4266
4267    impl EchoSocket {
4268        fn pump(&self) {
4269            loop {
4270                let (events, message) = {
4271                    let mut st = lock(&self.0);
4272                    if st.demand == 0 || st.queue.is_empty() {
4273                        return;
4274                    }
4275                    let Some(events) = st.events.clone() else {
4276                        return;
4277                    };
4278                    st.demand -= 1;
4279                    (events, st.queue.pop_front())
4280                };
4281                if let Some(message) = message {
4282                    events(WsEvent::Message(message));
4283                }
4284            }
4285        }
4286    }
4287
4288    impl Socket for EchoSocket {
4289        fn send(&self, message: Message, done: Completion) {
4290            lock(&self.0).queue.push_back(message);
4291            done(Ok(()));
4292            self.pump();
4293        }
4294        fn ping(&self, done: Completion) {
4295            done(Ok(()));
4296        }
4297        fn close(&self, code: u16, reason: &str) {
4298            let events = lock(&self.0).events.take();
4299            if let Some(events) = events {
4300                events(WsEvent::Closed {
4301                    code,
4302                    reason: reason.to_string(),
4303                });
4304            }
4305        }
4306        fn demand(&self, messages: u32) {
4307            lock(&self.0).demand += messages;
4308            self.pump();
4309        }
4310    }
4311
4312    impl Transport for Scripted {
4313        fn capabilities(&self) -> Capabilities {
4314            self.caps
4315        }
4316
4317        fn start(&self, request: Prepared, events: Events) -> Arc<dyn Transfer> {
4318            let seen = Seen {
4319                method: request.method.clone(),
4320                url: request.url.clone(),
4321                headers: request.headers.clone(),
4322            };
4323            lock(&self.seen).push(seen.clone());
4324            let reply = (self.script)(&seen);
4325            let expected = reply.chunks.iter().map(|c| c.len() as u64).sum();
4326            let transfer = Arc::new(ScriptedTransfer {
4327                owner: self.clone(),
4328                state: Mutex::new(ExchangeState {
4329                    events: Some(events.clone()),
4330                    head: Some(Head {
4331                        status: reply.status,
4332                        headers: reply.headers,
4333                        url: request.url,
4334                        expected_length: reply.expected.unwrap_or(Some(expected)),
4335                    }),
4336                    chunks: reply.chunks.into(),
4337                    demand: 0,
4338                    waiting: reply.question.is_some(),
4339                    emitting: false,
4340                    stalled: reply.stall,
4341                }),
4342            });
4343            if let Some(question) = reply.question {
4344                events(Event::Question(7, question));
4345            }
4346            transfer.pump();
4347            transfer
4348        }
4349
4350        fn websocket(&self, request: Prepared, events: WsEvents) -> Arc<dyn Socket> {
4351            let socket = Arc::new(EchoSocket(Mutex::new(EchoState {
4352                events: Some(events.clone()),
4353                queue: VecDeque::new(),
4354                demand: 0,
4355            })));
4356            events(WsEvent::Open {
4357                protocol: request.protocols.first().cloned(),
4358            });
4359            socket
4360        }
4361    }
4362
4363    fn builder(t: &Scripted) -> ClientBuilder {
4364        Client::builder()
4365            .transport(t.clone())
4366            .cookies(Cookies::jar())
4367    }
4368
4369    fn der(tag: u8, content: &[u8]) -> Vec<u8> {
4370        let mut out = vec![tag, content.len() as u8];
4371        out.extend_from_slice(content);
4372        out
4373    }
4374
4375    fn fake_certificate(key: u8) -> Vec<u8> {
4376        let mut tbs = der(0x02, &[1]);
4377        for _ in 0..4 {
4378            tbs.extend(der(0x30, &[]));
4379        }
4380        tbs.extend(der(0x30, &[0x03, 0x02, 0x00, key]));
4381        der(0x30, &der(0x30, &tbs))
4382    }
4383
4384    #[test]
4385    fn a_303_is_followed_as_a_get() {
4386        let t = Scripted::new(|seen| match seen.url.as_str() {
4387            "http://day.test/a" => Reply::new(303).header("Location", "/b"),
4388            _ => Reply::new(200).body("done"),
4389        });
4390        let client = builder(&t).build();
4391        let resp = wait(client.fetch_future(Request::post("http://day.test/a", b"x".to_vec())))
4392            .expect("response");
4393        assert_eq!(resp.text(), "done");
4394        assert_eq!(resp.url, "http://day.test/b");
4395        let methods: Vec<String> = t.seen().into_iter().map(|s| s.method).collect();
4396        assert_eq!(methods, ["POST", "GET"]);
4397    }
4398
4399    #[test]
4400    fn credentials_and_cookies_stay_behind_on_another_origin() {
4401        let t = Scripted::new(|seen| match seen.url.as_str() {
4402            "http://one.test/" => Reply::new(302).header("Location", "http://two.test/"),
4403            _ => Reply::new(200),
4404        });
4405        let jar = Arc::new(CookieJar::new());
4406        jar.store("http://one.test/", ["id=1"]);
4407        let client = Client::builder()
4408            .transport(t.clone())
4409            .cookies(Cookies::Jar(jar))
4410            .build();
4411        wait(client.fetch_future(Request::get("http://one.test/").bearer("secret")))
4412            .expect("response");
4413        let seen = t.seen();
4414        assert_eq!(seen[0].header("authorization"), Some("Bearer secret"));
4415        assert_eq!(seen[0].header("cookie"), Some("id=1"));
4416        assert_eq!(seen[1].header("authorization"), None);
4417        assert_eq!(seen[1].header("cookie"), None);
4418    }
4419
4420    #[test]
4421    fn the_redirect_limit_fails_the_request() {
4422        let t = Scripted::new(|_| Reply::new(302).header("Location", "/again"));
4423        let client = builder(&t).redirects(Redirects::Follow(3)).build();
4424        let err = wait(client.fetch_future(Request::get("http://day.test/"))).unwrap_err();
4425        assert_eq!(err, HttpError::TooManyRedirects);
4426        assert_eq!(t.seen().len(), 4);
4427    }
4428
4429    #[test]
4430    fn never_delivers_the_redirect_itself() {
4431        let t = Scripted::new(|_| Reply::new(301).header("Location", "/moved").body("moved"));
4432        let client = builder(&t).redirects(Redirects::Never).build();
4433        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
4434        assert_eq!((resp.status, resp.text().as_ref()), (301, "moved"));
4435    }
4436
4437    #[test]
4438    fn a_redirect_handler_decides_each_hop() {
4439        let t = Scripted::new(|seen| match seen.url.as_str() {
4440            "http://day.test/1" => Reply::new(302).header("Location", "/2"),
4441            "http://day.test/2" => Reply::new(302)
4442                .header("Location", "/3")
4443                .body("stopped here"),
4444            _ => Reply::new(200),
4445        });
4446        let hops = Arc::new(Mutex::new(Vec::new()));
4447        let log = hops.clone();
4448        let client = builder(&t)
4449            .on_redirect(move |hop, reply| {
4450                lock(&log).push(hop.to.clone());
4451                if hop.followed == 0 {
4452                    drop(reply);
4453                } else {
4454                    reply.stop();
4455                }
4456            })
4457            .build();
4458        let resp = wait(client.fetch_future(Request::get("http://day.test/1"))).expect("response");
4459        assert_eq!((resp.status, resp.text().as_ref()), (302, "stopped here"));
4460        assert_eq!(*lock(&hops), ["http://day.test/2", "http://day.test/3"]);
4461    }
4462
4463    #[test]
4464    fn a_redirect_handler_needs_manual_redirects() {
4465        let mut t = Scripted::new(|_| Reply::new(200));
4466        t.caps.manual_redirects = false;
4467        let client = builder(&t).on_redirect(|_, reply| reply.follow()).build();
4468        let err = wait(client.fetch_future(Request::get("http://day.test/"))).unwrap_err();
4469        assert_eq!(err, HttpError::Unsupported);
4470    }
4471
4472    #[test]
4473    fn a_basic_challenge_is_answered_once_and_remembered() {
4474        let t = Scripted::new(|seen| match seen.header("authorization") {
4475            Some(a) if a == basic_authorization("day", "sunrise") => Reply::new(200).body("in"),
4476            _ => Reply::new(401).header("WWW-Authenticate", "Basic realm=\"Day test\""),
4477        });
4478        let asked = Arc::new(AtomicUsize::new(0));
4479        let count = asked.clone();
4480        let client = builder(&t)
4481            .on_challenge(move |challenge, reply| {
4482                count.fetch_add(1, Ordering::SeqCst);
4483                assert_eq!(challenge.scheme, Scheme::Basic);
4484                assert_eq!(challenge.realm.as_deref(), Some("Day test"));
4485                reply.credential("day", "sunrise");
4486            })
4487            .build();
4488        for _ in 0..2 {
4489            let resp = wait(client.fetch_future(Request::get("http://day.test/private")))
4490                .expect("response");
4491            assert_eq!(resp.text(), "in");
4492        }
4493        assert_eq!(asked.load(Ordering::SeqCst), 1);
4494        assert_eq!(t.seen().len(), 4);
4495    }
4496
4497    #[test]
4498    fn a_digest_challenge_is_answered() {
4499        let t = Scripted::new(|seen| match seen.header("authorization") {
4500            Some(a) if verify_digest(a, "day", "sunrise", &seen.method) => {
4501                Reply::new(200).body("in")
4502            }
4503            _ => Reply::new(401).header(
4504                "WWW-Authenticate",
4505                "Digest realm=\"Day test\", nonce=\"n1\", qop=\"auth\"",
4506            ),
4507        });
4508        let client = builder(&t)
4509            .on_challenge(|_, reply| reply.credential("day", "sunrise"))
4510            .build();
4511        let resp = wait(client.fetch_future(Request::get("http://day.test/digest?x=1")))
4512            .expect("response");
4513        assert_eq!(resp.text(), "in");
4514    }
4515
4516    #[test]
4517    fn refused_credentials_end_with_the_401() {
4518        let t = Scripted::new(|_| {
4519            Reply::new(401).header("WWW-Authenticate", "Basic realm=\"Day test\"")
4520        });
4521        let client = builder(&t)
4522            .on_challenge(|_, reply| reply.credential("day", "wrong"))
4523            .build();
4524        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
4525        assert_eq!(resp.status, 401);
4526        assert_eq!(t.seen().len(), 1 + MAX_AUTH_ATTEMPTS as usize);
4527    }
4528
4529    #[test]
4530    fn without_a_handler_the_401_is_the_response() {
4531        let t = Scripted::new(|_| Reply::new(401).header("WWW-Authenticate", "Bearer"));
4532        let client = builder(&t).build();
4533        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
4534        assert_eq!(resp.status, 401);
4535        assert_eq!(t.seen().len(), 1);
4536    }
4537
4538    #[test]
4539    fn cookies_set_during_a_redirect_reach_the_next_hop() {
4540        let t = Scripted::new(|seen| match seen.url.as_str() {
4541            "http://day.test/login" => Reply::new(302)
4542                .header("Location", "/home")
4543                .header("Set-Cookie", "session=abc; Path=/; HttpOnly"),
4544            _ => Reply::new(200),
4545        });
4546        let client = builder(&t).build();
4547        wait(client.fetch_future(Request::get("http://day.test/login"))).expect("response");
4548        assert_eq!(t.seen()[1].header("cookie"), Some("session=abc"));
4549        assert_eq!(client.cookies().len(), 1);
4550        client.clear_cookies();
4551        assert_eq!(client.cookies(), [] as [Cookie; 0]);
4552    }
4553
4554    #[test]
4555    fn the_jar_follows_domain_path_and_secure_rules() {
4556        let jar = CookieJar::new();
4557        jar.store(
4558            "https://www.day.test/app/page",
4559            [
4560                "a=1",
4561                "b=2; Domain=day.test; Path=/",
4562                "c=3; Secure; Path=/",
4563                "d=4; Domain=test",
4564                "e=5; Max-Age=0",
4565                "f=6; Domain=other.test",
4566            ],
4567        );
4568        assert_eq!(
4569            jar.header("https://www.day.test/app/x").as_deref(),
4570            Some("a=1; b=2; c=3")
4571        );
4572        assert_eq!(
4573            jar.header("http://www.day.test/app/x").as_deref(),
4574            Some("a=1; b=2")
4575        );
4576        assert_eq!(jar.header("https://api.day.test/").as_deref(), Some("b=2"));
4577        assert_eq!(
4578            jar.header("https://www.day.test/other").as_deref(),
4579            Some("b=2; c=3")
4580        );
4581        jar.store(
4582            "https://www.day.test/",
4583            ["b=; Domain=day.test; Path=/; Max-Age=0"],
4584        );
4585        assert_eq!(
4586            jar.header("https://www.day.test/other").as_deref(),
4587            Some("c=3")
4588        );
4589    }
4590
4591    #[test]
4592    fn a_persistent_jar_keeps_only_cookies_with_an_expiry() {
4593        let dir = std::env::temp_dir().join(format!("day-http-jar-{}", std::process::id()));
4594        let file = dir.join("cookies");
4595        let _ = std::fs::remove_file(&file);
4596        let jar = CookieJar::open(&file);
4597        jar.store(
4598            "https://day.test/",
4599            ["session=1", "remember=2; Max-Age=3600"],
4600        );
4601        let reopened = CookieJar::open(&file);
4602        assert_eq!(
4603            reopened.header("https://day.test/").as_deref(),
4604            Some("remember=2")
4605        );
4606        let _ = std::fs::remove_dir_all(&dir);
4607    }
4608
4609    #[test]
4610    fn bounded_progress_distinguishes_known_unknown_and_encoded_bodies() {
4611        for (advertised, encoding, expected) in [
4612            (Some(4), "identity", Some(4)),
4613            (None, "identity", None),
4614            (Some(2), "gzip", None),
4615        ] {
4616            let t = Scripted::new(move |_| {
4617                let mut reply = Reply::new(200)
4618                    .chunks(4)
4619                    .header("Content-Encoding", encoding);
4620                reply.expected = Some(advertised);
4621                reply
4622            });
4623            let client = builder(&t).build();
4624            let mut observations = Vec::new();
4625            let response = wait(client.fetch_limited_with_progress_future(
4626                Request::get("http://day.test/progress"),
4627                10,
4628                |received, total| observations.push((received, total)),
4629            ))
4630            .unwrap();
4631            assert_eq!(response.body, vec![0, 1, 2, 3]);
4632            assert_eq!(observations.first(), Some(&(0, None)));
4633            assert_eq!(observations.last(), Some(&(4, expected)));
4634            assert!(observations.windows(2).all(|pair| pair[0].0 <= pair[1].0));
4635        }
4636    }
4637
4638    #[test]
4639    fn bounded_downloads_check_both_headers_and_streamed_bytes() {
4640        for advertised in [Some(100), None, Some(1)] {
4641            let t = Scripted::new(move |_| {
4642                let mut reply = Reply::new(200).chunks(100);
4643                reply.expected = Some(advertised);
4644                reply
4645            });
4646            let client = builder(&t).build();
4647            std::assert_matches!(
4648                wait(client.fetch_limited_future(Request::get("http://day.test/big"), 10)),
4649                Err(HttpError::BodyTooLarge { limit: 10 })
4650            );
4651            assert_eq!(t.cancels.load(Ordering::SeqCst), 1);
4652        }
4653        let t = Scripted::new(|_| Reply::new(200).body("exact"));
4654        let client = builder(&t).build();
4655        assert_eq!(
4656            wait(client.fetch_limited_future(Request::get("http://day.test/exact"), 5))
4657                .unwrap()
4658                .body,
4659            b"exact"
4660        );
4661    }
4662
4663    #[test]
4664    fn bounded_bodyless_responses_ignore_representation_length() {
4665        for (method, status) in [(Method::Get, 304), (Method::Head, 200), (Method::Get, 204)] {
4666            let t = Scripted::new(move |_| {
4667                let mut reply = Reply::new(status);
4668                reply.expected = Some(Some(100_000));
4669                reply
4670            });
4671            let mut req = Request::get("http://day.test/unchanged");
4672            req.method = method;
4673            let response = wait(builder(&t).build().fetch_limited_future(req, 0)).unwrap();
4674            assert_eq!(response.status, status);
4675            assert_eq!(response.body, [] as [u8; 0]);
4676        }
4677    }
4678
4679    #[test]
4680    fn a_slow_reader_holds_the_transport_to_its_window() {
4681        let t = Scripted::new(|_| Reply::new(200).chunks(100));
4682        let client = builder(&t).build();
4683        let streaming =
4684            wait(client.send_future(Request::get("http://day.test/big"))).expect("head");
4685        assert_eq!(streaming.expected_length(), Some(100));
4686        let mut body = streaming.into_body();
4687        assert_eq!(wait(body.next()), Some(Ok(vec![0])));
4688        let granted = t.granted.load(Ordering::SeqCst);
4689        assert!(granted <= u64::from(WINDOW), "granted {granted}");
4690        let mut all = vec![0u8];
4691        while let Some(chunk) = wait(body.next()) {
4692            all.extend(chunk.expect("chunk"));
4693        }
4694        assert_eq!(all, (0..100).collect::<Vec<u8>>());
4695        assert_eq!(body.received(), 100);
4696    }
4697
4698    #[test]
4699    fn dropping_an_unread_body_cancels_the_exchange() {
4700        let t = Scripted::new(|_| Reply::new(200).chunks(100));
4701        let client = builder(&t).build();
4702        let streaming =
4703            wait(client.send_future(Request::get("http://day.test/big"))).expect("head");
4704        drop(streaming);
4705        assert_eq!(t.cancels.load(Ordering::SeqCst), 1);
4706    }
4707
4708    #[test]
4709    fn dropping_the_send_future_cancels_the_exchange() {
4710        let t = Scripted::new(|_| Reply::new(200).stall());
4711        let client = builder(&t).build();
4712        drop(client.send_future(Request::get("http://day.test/")));
4713        assert_eq!(t.cancels.load(Ordering::SeqCst), 1);
4714    }
4715
4716    #[test]
4717    fn read_async_hands_over_every_chunk_then_the_end() {
4718        let t = Scripted::new(|_| Reply::new(200).chunks(10));
4719        let client = builder(&t).build();
4720        let (tx, rx) = std::sync::mpsc::channel();
4721        client.send_async(Request::get("http://day.test/"), move |head| {
4722            let body = head.expect("head").into_body();
4723            body.read_async(move |item| {
4724                let more = matches!(item, Some(Ok(_)));
4725                let _ = tx.send(item.map(|r| r.map(|c| c[0])));
4726                more
4727            });
4728        });
4729        let items: Vec<_> = rx.iter().take(11).collect();
4730        let expected: Vec<_> = (0..10).map(|i| Some(Ok(i))).collect();
4731        assert_eq!(&items[..10], &expected[..]);
4732        assert_eq!(items[10], None);
4733    }
4734
4735    #[test]
4736    fn a_pin_that_matches_accepts_and_one_that_does_not_rejects() {
4737        let cert = fake_certificate(0xAA);
4738        let good = pin_string(&spki_sha256(&cert).expect("spki"));
4739        let asking = |cert: Vec<u8>| {
4740            move |_: &Seen| {
4741                Reply::new(200)
4742                    .body("secure")
4743                    .question(Question::ServerTrust(ServerTrust {
4744                        host: "day.test".into(),
4745                        chain: vec![cert.clone()],
4746                        system_trusted: true,
4747                        system_error: None,
4748                    }))
4749            }
4750        };
4751        let t = Scripted::new(asking(cert.clone()));
4752        let client = builder(&t)
4753            .trust(Trust::system().pin("day.test", &good))
4754            .build();
4755        let resp = wait(client.fetch_future(Request::get("https://day.test/"))).expect("response");
4756        assert_eq!(resp.text(), "secure");
4757        assert_eq!(*lock(&t.answers), [Answer::Accept]);
4758
4759        let t = Scripted::new(asking(cert));
4760        let wrong = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
4761        let client = builder(&t)
4762            .trust(Trust::system().pin("*.test", wrong))
4763            .build();
4764        let err = wait(client.fetch_future(Request::get("https://day.test/"))).unwrap_err();
4765        std::assert_matches!(err, HttpError::Tls(_), "{err:?}");
4766        assert_eq!(*lock(&t.answers), [Answer::Reject]);
4767    }
4768
4769    #[test]
4770    fn a_trust_handler_may_accept_what_the_platform_refused() {
4771        let t = Scripted::new(|_| {
4772            Reply::new(200).question(Question::ServerTrust(ServerTrust {
4773                host: "self-signed.test".into(),
4774                chain: Vec::new(),
4775                system_trusted: false,
4776                system_error: Some("self-signed".into()),
4777            }))
4778        });
4779        let client = builder(&t)
4780            .on_server_trust(|trust, reply| {
4781                if trust.host == "self-signed.test" {
4782                    reply.accept();
4783                } else {
4784                    reply.reject();
4785                }
4786            })
4787            .build();
4788        let resp =
4789            wait(client.fetch_future(Request::get("https://self-signed.test/"))).expect("response");
4790        assert_eq!(resp.status, 200);
4791        assert_eq!(*lock(&t.answers), [Answer::Accept]);
4792    }
4793
4794    #[test]
4795    fn a_question_nobody_answers_takes_its_default_after_the_timeout() {
4796        static HELD: Mutex<Vec<ChallengeReply>> = Mutex::new(Vec::new());
4797        let t =
4798            Scripted::new(|_| Reply::new(401).header("WWW-Authenticate", "Bearer realm=\"api\""));
4799        let client = builder(&t)
4800            .question_timeout(Duration::from_millis(50))
4801            .on_challenge(|_, reply| lock(&HELD).push(reply))
4802            .build();
4803        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
4804        assert_eq!(resp.status, 401);
4805        lock(&HELD).clear();
4806    }
4807
4808    #[test]
4809    fn the_total_limit_fails_a_stalled_request() {
4810        let t = Scripted::new(|_| Reply::new(200).stall());
4811        let client = builder(&t).timeout_total(Duration::from_millis(50)).build();
4812        // The count is read inside the callback, where the caller first hears of the timeout:
4813        // the stalled exchange must be cancelled by then, not a moment later on the timer's
4814        // thread (reading it after a woken future raced that thread, and lost on Windows CI).
4815        let cancels = t.cancels.clone();
4816        let (tx, rx) = std::sync::mpsc::channel();
4817        let _flight = client.fetch_async(Request::get("http://day.test/"), move |result| {
4818            let _ = tx.send((result.err(), cancels.load(Ordering::SeqCst)));
4819        });
4820        let (err, cancelled) = rx
4821            .recv_timeout(Duration::from_secs(5))
4822            .expect("the total limit fires");
4823        assert_eq!(err, Some(HttpError::Timeout));
4824        assert_eq!(cancelled, 1);
4825    }
4826
4827    #[test]
4828    fn a_bad_url_fails_before_any_exchange() {
4829        let t = Scripted::new(|_| Reply::new(200));
4830        let client = builder(&t).build();
4831        let err = wait(client.fetch_future(Request::get("ftp://day.test/"))).unwrap_err();
4832        std::assert_matches!(err, HttpError::BadUrl(_), "{err:?}");
4833        assert!(t.seen().is_empty());
4834    }
4835
4836    #[test]
4837    fn a_websocket_echoes_then_closes_with_a_code() {
4838        let t = Scripted::new(|_| Reply::new(200));
4839        let client = builder(&t).build();
4840        let mut socket =
4841            wait(client.websocket_future(Request::get("ws://day.test/echo").protocols(["chat"])))
4842                .expect("open");
4843        assert_eq!(socket.protocol().as_deref(), Some("chat"));
4844        wait(socket.send_future(Message::Text("hello".into())))
4845            .expect("delivered")
4846            .expect("sent");
4847        assert_eq!(wait(socket.next()), Some(Ok(Message::Text("hello".into()))));
4848        socket.close(4000, "done");
4849        assert_eq!(
4850            wait(socket.next()),
4851            Some(Ok(Message::Close {
4852                code: 4000,
4853                reason: "done".into()
4854            }))
4855        );
4856        assert_eq!(wait(socket.next()), None);
4857    }
4858}