Skip to main content

netio/
client.rs

1// client -- a blocking HTTP/1.1 client
2//
3//   Client::new().request("GET", &url, &headers, body) -> Result<Response, HttpError>
4//   client.fetch(method, &url, &headers, body) -> Fetched { url: the last one, response }
5//   client.get_to(&url, &headers, max, on)   a download piece by piece (Part::Head, Part::Data)
6//   client.request_on(&stream, method, &url, &headers, body)   one request over a connection the
7//                                            caller opened (no proxy, no pool, no redirects)
8//   client.with_connector(Arc<dyn Fn(&Url, TcpStream) -> Result<Box<dyn Stream>, HttpError>>)
9//   client.with_proxy(Proxy)          HTTP proxies (netio::proxy; Proxy::from_env)
10//   client.with_pool(Arc<Pool>)       connections kept open for the next requests
11//   client.with_cookies(Arc<Mutex<Jar>>)   netpkt::cookie's jar: Set-Cookie stored, Cookie sent
12//   client.with_redirect_check(f)     f(from, to) before each redirect (false: the 3xx answer)
13//   client.request_async(method, &url, &headers, body) -> future of the answer (the request on
14//   plat::task's blocking pool: ui.spawn / block_on await it without blocking)
15//   client.download(&url, &headers, path, &ctl) -> future of the status: the body into the file
16//   (plat::AtomicFile: replaced only by a whole 2xx body), progress and cancel in ctl
17//
18// The fields: connect_ms, timeout_ms (any single read or write), deadline_ms (a whole request,
19// its redirects included: see below; 0: none), max_body (the body as it came and after decoding),
20// user_agent, redirects (followed at most; 0: a 3xx answer comes back as it is) and decode.
21//
22// decode (on by default): without an Accept-Encoding or Range header of the caller's, a request
23// offers "gzip, br" and a body in gzip, br, zstd (window up to 8 MiB, RFC 9659) or deflate (zlib)
24// is decoded as it arrives, through compress's stream decoders; Content-Encoding and
25// Content-Length then leave the answer's headers.  A body that does not decode is
26// HttpError::Encoding; stacked or unknown codings come back as they are.
27//
28// Redirects (301, 302, 303, 307, 308 with a Location, RFC 9110 15.4): the Location is resolved
29// against the request's URL (Url::join) and handed to the redirect check; one from https to http
30// that it lets pass is refused (HttpError::Redirect);
31// 303 (not after HEAD) and 301 / 302 after POST go on as GET without the body and its headers;
32// to another origin, Authorization, Cookie, Proxy-Authorization and Host stay behind (the jar's
33// cookies are those of the new URL).
34//
35// Answers are read as RFC 9112 6.3 says: a status line "HTTP/1.x NNN" with a code of 100 to 599,
36// interim answers (1xx) skipped up to 16 of them, 101 refused (no upgrade was asked for); no body
37// after HEAD or with 204 and 304 (whatever Content-Length says), else the body by
38// Transfer-Encoding: chunked, else Content-Length, else up to the end of the connection.
39// A connection carries another request (the pool, Session) only after a body of known length
40// that was read to its end with no byte beyond it, and when neither side said close.
41//
42// deadline_ms: each address connected to gets connect_ms or the time left, whichever is less;
43// every read waits for bytes only until the deadline (a TLS record that arrives in pieces too);
44// a request is written in pieces of 16 KiB, each with the time left as its timeout -- a server
45// that takes a piece byte by byte can still keep that piece's write going past the deadline; a
46// write that runs out of time is TimedOut. Outside the deadline: the name lookup (the resolver's
47// own timeouts) and the TLS handshake (the connector's: the socket's timeouts are set once, to
48// the time left when it begins, and each of its reads and writes may take that long; a handshake
49// that ends past the deadline, done or failed, is TimedOut).
50
51use alloc::boxed::Box;
52use alloc::format;
53use alloc::string::String;
54use alloc::sync::Arc;
55use alloc::vec;
56use alloc::vec::Vec;
57use core::future::Future;
58
59use compress::stream::{Decode, Status};
60use netpkt::cookie::{Asks, Jar, Origin};
61use plat::aio::Ctl;
62use plat::net::{NetError, NetErrorKind, TcpStream};
63use plat::sync::Mutex;
64use plat::task::CancelToken;
65
66use crate::http::{self, Body, Headers, ReadError, Reader, Response};
67use crate::proxy::{Endpoint, Proxy};
68use crate::url::Url;
69use crate::Stream;
70
71#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum HttpError {
74    /// not an http(s) URL, or https without a connector
75    Url(String),
76    Net(NetError),
77    /// the TLS layer refused (certificate, handshake)
78    Tls(String),
79    /// a malformed answer
80    Bad,
81    /// an answer over the size limit
82    TooLarge,
83    /// (download) the target file could not be created, written or put in place
84    File,
85    /// (download) cancelled through the Ctl, or the future was dropped
86    Cancelled,
87    /// a redirect that is not followed: from https to http, a Location that is not a URL, more
88    /// than Client::redirects of them
89    Redirect(String),
90    /// the proxy refused the tunnel (its status; 407: it wants other credentials)
91    Proxy(u16),
92    /// the body does not decode as its Content-Encoding says
93    Encoding,
94}
95
96impl core::fmt::Display for HttpError {
97    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
98        match self {
99            HttpError::Url(s) => write!(f, "invalid address: {}", s),
100            HttpError::Net(e) => write!(f, "{}", e),
101            HttpError::Tls(s) => write!(f, "TLS: {}", s),
102            HttpError::Bad => f.write_str("malformed HTTP answer"),
103            HttpError::TooLarge => f.write_str("answer too large"),
104            HttpError::File => f.write_str("the file cannot be written"),
105            HttpError::Cancelled => f.write_str("cancelled"),
106            HttpError::Redirect(s) => write!(f, "redirect: {}", s),
107            HttpError::Proxy(407) => f.write_str("the proxy wants credentials (407)"),
108            HttpError::Proxy(s) => write!(f, "the proxy refused the connection ({})", s),
109            HttpError::Encoding => f.write_str("the body does not decode as its Content-Encoding says"),
110        }
111    }
112}
113
114impl From<NetError> for HttpError {
115    fn from(e: NetError) -> Self {
116        HttpError::Net(e)
117    }
118}
119
120pub type Connector = Arc<dyn Fn(&Url, TcpStream) -> Result<Box<dyn Stream>, HttpError> + Send + Sync>;
121
122/// asked before a redirect is followed: (from, to) -> false: the 3xx answer is the result
123pub type RedirectCheck = Arc<dyn Fn(&Url, &Url) -> bool + Send + Sync>;
124
125/// a piece of an answer that Client::get_to streams
126pub enum Part<'a> {
127    /// the status and the headers (first)
128    Head(u16, &'a Headers),
129    /// the next bytes of the body
130    Data(&'a [u8]),
131}
132
133/// an answer and the URL it came from (after redirects)
134#[derive(Debug)]
135pub struct Fetched {
136    pub url: Url,
137    pub response: Response,
138}
139
140/// interim answers (1xx) read before the final one at most
141const MAX_INTERIM: usize = 16;
142/// the body of a redirect that is followed: read (so the connection can go on) up to this
143const REDIRECT_BODY: u64 = 64 << 10;
144/// what a request offers when it decodes
145const ACCEPT_ENCODING: &str = "gzip, br";
146/// zstd's window in HTTP (RFC 9659 3: a decoder need not take more than 8 MiB)
147const ZSTD_WINDOW: usize = 8 << 20;
148
149#[derive(Clone)]
150pub struct Client {
151    pub connect_ms: u32,
152    /// the longest wait for any read or write
153    pub timeout_ms: u32,
154    /// the longest a whole request may take, from connecting to the last byte of the body,
155    /// redirects and retries included; what it bounds and what not: the module header (0: no
156    /// limit beyond timeout_ms per read)
157    pub deadline_ms: u32,
158    pub max_body: usize,
159    pub user_agent: String,
160    /// redirects followed at most (0: a 3xx answer comes back as it is)
161    pub redirects: u8,
162    /// offer gzip and br and decode the body (see the module header)
163    pub decode: bool,
164    connector: Option<Connector>,
165    proxy: Option<Proxy>,
166    pool: Option<Arc<Pool>>,
167    cookies: Option<Arc<Mutex<Jar>>>,
168    redirect_check: Option<RedirectCheck>,
169}
170
171impl Default for Client {
172    fn default() -> Self {
173        Client::new()
174    }
175}
176
177/// one request as it goes out
178struct Hop<'a> {
179    method: &'a str,
180    url: &'a Url,
181    headers: &'a Headers,
182    body: &'a [u8],
183}
184
185/// the head of the final answer
186struct Head {
187    /// x of HTTP/1.x
188    minor: u8,
189    status: u16,
190    headers: Headers,
191}
192
193/// "HTTP/1.x NNN[ reason]" -> (x, NNN)
194fn status_line(start: &str) -> Option<(u8, u16)> {
195    let b = start.strip_prefix("HTTP/1.")?.as_bytes();
196    if b.len() < 5 || !b[0].is_ascii_digit() || b[1] != b' ' || !b[2..5].iter().all(u8::is_ascii_digit) || (b.len() > 5 && b[5] != b' ') {
197        return None;
198    }
199    let status = (b[2] - b'0') as u16 * 100 + (b[3] - b'0') as u16 * 10 + (b[4] - b'0') as u16;
200    (100..=599).contains(&status).then_some((b[0] - b'0', status))
201}
202
203/// the final answer's head, after up to MAX_INTERIM interim ones
204fn read_head(rd: &mut Reader<'_>) -> Result<Head, ReadError> {
205    for i in 0..=MAX_INTERIM {
206        // only an end before the first answer is a closed connection (a reused one, to retry)
207        let (start, headers) = rd.head().map_err(|e| if i > 0 && e == ReadError::Closed { ReadError::Bad } else { e })?;
208        let (minor, status) = status_line(&start).ok_or(ReadError::Bad)?;
209        if status == 101 {
210            return Err(ReadError::Bad); // no upgrade was asked for
211        }
212        if status >= 200 {
213            return Ok(Head { minor, status, headers });
214        }
215    }
216    Err(ReadError::Bad)
217}
218
219fn read_err(e: ReadError) -> HttpError {
220    match e {
221        ReadError::Net(n) => HttpError::Net(n),
222        ReadError::BodyTooLarge | ReadError::HeadTooLarge => HttpError::TooLarge,
223        ReadError::Closed | ReadError::Bad => HttpError::Bad,
224    }
225}
226
227fn reset() -> HttpError {
228    HttpError::Net(NetError::new(NetErrorKind::Reset, 0))
229}
230
231fn timed_out() -> NetError {
232    NetError::new(NetErrorKind::TimedOut, 0)
233}
234
235/// `ms`, or less when the deadline comes sooner; None when it has passed
236fn left(ms: u32, deadline: Option<u64>) -> Option<u32> {
237    let Some(d) = deadline else { return Some(ms) };
238    let left = d.saturating_sub(plat::time_us()) / 1000;
239    (left > 0).then(|| ms.min(left.min(u32::MAX as u64) as u32))
240}
241
242/// left(), TimedOut when the deadline has passed
243fn within(ms: u32, deadline: Option<u64>) -> Result<u32, HttpError> {
244    left(ms, deadline).ok_or_else(|| HttpError::Net(timed_out()))
245}
246
247/// Writes go out in pieces of this size, the deadline checked before each
248const WRITE_PIECE: usize = 16 << 10;
249
250/// A stream whose reads and writes keep to a deadline: before each read and each piece of a
251/// write, its timeouts become the time left (at most `ms`), and past the deadline they fail with
252/// TimedOut.  Without a deadline it passes everything on as it is
253struct Bounded<'a> {
254    s: &'a dyn Stream,
255    ms: u32,
256    deadline: Option<u64>,
257    // a write ran out of time (the deadline or a write's own timeout): write_request only says
258    // false, which is then TimedOut rather than Reset
259    late: core::sync::atomic::AtomicBool,
260}
261
262impl<'a> Bounded<'a> {
263    fn new(s: &'a dyn Stream, ms: u32, deadline: Option<u64>) -> Self {
264        Bounded { s, ms, deadline, late: core::sync::atomic::AtomicBool::new(false) }
265    }
266
267    // the error for a request write_request did not write, and whether a retry may help (not
268    // when time ran out: the server is there but does not read)
269    fn write_failed(&self) -> (HttpError, bool) {
270        if self.late.load(core::sync::atomic::Ordering::Relaxed) {
271            (HttpError::Net(timed_out()), false)
272        } else {
273            (reset(), true)
274        }
275    }
276
277    fn pieces(&self, buf: &[u8]) -> plat::net::NetResult<()> {
278        if self.deadline.is_none() {
279            return self.s.write_all(buf);
280        }
281        for piece in buf.chunks(WRITE_PIECE) {
282            self.limit()?;
283            self.s.write_all(piece)?;
284        }
285        Ok(())
286    }
287
288    fn limit(&self) -> plat::net::NetResult<()> {
289        if self.deadline.is_some() {
290            let ms = left(self.ms, self.deadline).ok_or_else(timed_out)?;
291            self.s.set_timeouts(Some(ms), Some(ms));
292        }
293        Ok(())
294    }
295}
296
297impl Stream for Bounded<'_> {
298    fn read(&self, buf: &mut [u8]) -> plat::net::NetResult<usize> {
299        self.limit()?;
300        self.s.read(buf)
301    }
302    fn write_all(&self, buf: &[u8]) -> plat::net::NetResult<()> {
303        let r = self.pieces(buf);
304        if matches!(r, Err(e) if e.kind == NetErrorKind::TimedOut) {
305            self.late.store(true, core::sync::atomic::Ordering::Relaxed);
306        }
307        r
308    }
309    fn set_timeouts(&self, read_ms: Option<u32>, write_ms: Option<u32>) {
310        self.s.set_timeouts(read_ms, write_ms);
311    }
312    fn shutdown(&self) {
313        self.s.shutdown();
314    }
315    fn wait_readable(&self, ms: u32) -> bool {
316        self.s.wait_readable(ms)
317    }
318    fn end_is_clean(&self) -> bool {
319        self.s.end_is_clean()
320    }
321}
322
323fn is_redirect(status: u16) -> bool {
324    matches!(status, 301 | 302 | 303 | 307 | 308)
325}
326
327fn idempotent(method: &str) -> bool {
328    matches!(method, "GET" | "HEAD" | "PUT" | "DELETE" | "OPTIONS" | "TRACE")
329}
330
331/// the decoder of a body's Content-Encoding (None: identity, or one this client does not decode)
332/// and whether its format may hold several streams in a row (gzip members, zstd frames)
333fn decoder_of(h: &Headers) -> Option<(Box<dyn Decode>, bool)> {
334    let mut codings = h
335        .0
336        .iter()
337        .filter(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
338        .flat_map(|(_, v)| v.split(','))
339        .map(|t| t.trim())
340        .filter(|t| !t.is_empty() && !t.eq_ignore_ascii_case("identity"));
341    let c = codings.next()?;
342    if codings.next().is_some() {
343        return None; // stacked codings: left as they are
344    }
345    let c = c.to_ascii_lowercase();
346    Some(match c.as_str() {
347        "gzip" | "x-gzip" => (Box::new(compress::gzip::Decoder::new()), true),
348        "br" => (Box::new(compress::brotli::Decoder::new()), false),
349        "zstd" => (Box::new(compress::zstd::Decoder::new().with_window_max(ZSTD_WINDOW)), true),
350        // "deflate" is zlib (RFC 9110 8.4.1.2)
351        "deflate" => (Box::new(compress::zlib::Decoder::new()), false),
352        _ => return None,
353    })
354}
355
356/// a body's bytes through its decoder into `sink` (at most `max` decoded bytes in all)
357struct Decoding {
358    dec: Box<dyn Decode>,
359    multi: bool,
360    buf: Vec<u8>,
361    total: u64,
362    max: u64,
363    ended: bool,
364    fail: Option<HttpError>,
365}
366
367impl Decoding {
368    fn feed(&mut self, mut input: &[u8], sink: &mut dyn FnMut(&[u8]) -> bool) -> Result<(), HttpError> {
369        loop {
370            if self.ended {
371                if input.is_empty() {
372                    return Ok(());
373                }
374                if !self.multi {
375                    return Err(HttpError::Encoding); // bytes after the stream
376                }
377                self.ended = false; // the next gzip member or zstd frame
378            }
379            let s = self.dec.decode(input, &mut self.buf).map_err(|_| HttpError::Encoding)?;
380            input = &input[s.read..];
381            if s.written > 0 {
382                self.total += s.written as u64;
383                if self.total > self.max {
384                    return Err(HttpError::TooLarge);
385                }
386                if !sink(&self.buf[..s.written]) {
387                    return Err(HttpError::Bad);
388                }
389            }
390            match s.status {
391                Status::End if s.read == 0 && s.written == 0 && !input.is_empty() && self.multi => return Err(HttpError::Encoding),
392                Status::End => self.ended = true,
393                Status::Output => {}
394                Status::Input => return Ok(()),
395            }
396        }
397    }
398}
399
400/// the body of an answer as a reader of it takes it: framed (chunked, Content-Length, to the
401/// end), decoded where the client asked for it, at most `max` bytes either way
402struct Incoming<'r, 's> {
403    rd: &'r mut Reader<'s>,
404    /// the headers as they came (the framing)
405    raw: &'r Headers,
406    until_close: bool,
407    dec: Option<(Box<dyn Decode>, bool)>,
408    /// no body at all (HEAD, 204, 304)
409    none: bool,
410    /// read to its end
411    done: bool,
412}
413
414impl Incoming<'_, '_> {
415    /// the body piece by piece to `sink` (false from it: stop, Err(Bad)) -> its length (decoded)
416    fn to(&mut self, max: u64, sink: &mut dyn FnMut(&[u8]) -> bool) -> Result<u64, HttpError> {
417        if self.none {
418            self.done = true;
419            return Ok(0);
420        }
421        let Some((dec, multi)) = self.dec.take() else {
422            let n = self.rd.body_to(self.raw, max, self.until_close, sink).map_err(read_err)?;
423            self.done = true;
424            return Ok(n);
425        };
426        let mut d = Decoding { dec, multi, buf: vec![0u8; 16 << 10], total: 0, max, ended: false, fail: None };
427        let mut raw = 0u64;
428        let r = self.rd.body_to(self.raw, max, self.until_close, &mut |piece| match {
429            raw += piece.len() as u64;
430            d.feed(piece, sink)
431        } {
432            Ok(()) => true,
433            Err(e) => {
434                d.fail = Some(e);
435                false
436            }
437        });
438        if let Some(e) = d.fail.take() {
439            return Err(e);
440        }
441        r.map_err(read_err)?;
442        // the body ended: the stream must have ended with it (all its output is written); an
443        // empty body is empty, whatever its Content-Encoding says (servers send that for nothing)
444        if raw > 0 && !d.ended && d.dec.finish().is_err() {
445            return Err(HttpError::Encoding);
446        }
447        self.done = true;
448        Ok(d.total)
449    }
450
451    /// the whole body (at most max bytes)
452    fn all(&mut self, max: usize) -> Result<Vec<u8>, HttpError> {
453        let mut out = Vec::new();
454        if self.dec.is_none() && self.raw.get("transfer-encoding").is_none() {
455            if let Ok(Some(n)) = self.raw.content_length() {
456                out.reserve((n.min(max as u64) as usize).min(1 << 20));
457            }
458        }
459        self.to(max as u64, &mut |b| {
460            out.extend_from_slice(b);
461            true
462        })?;
463        Ok(out)
464    }
465}
466
467type ReadFn<'f> = &'f mut dyn FnMut(u16, &Headers, &mut Incoming<'_, '_>) -> Result<Response, HttpError>;
468
469/// a kept connection: the stream, the proxy it goes through as absolute-form requests, and the
470/// TLS layer it was made with (held, so that its address in the key stays its own)
471struct Idle {
472    key: String,
473    conn: Box<dyn Stream>,
474    via: Option<Endpoint>,
475    _tls: Option<Connector>,
476    since_us: u64,
477}
478
479/// connections kept open between requests (Client::with_pool): per origin, proxy and TLS
480/// layer, at most `per_host` of them and `idle_ms` long
481pub struct Pool {
482    idle: Mutex<Vec<Idle>>,
483    pub per_host: usize,
484    pub max_idle: usize,
485    pub idle_ms: u32,
486}
487
488impl Pool {
489    /// 4 per host, 64 in all, 60 s
490    pub fn new() -> Arc<Pool> {
491        Pool::with_limits(4, 64, 60_000)
492    }
493
494    pub fn with_limits(per_host: usize, max_idle: usize, idle_ms: u32) -> Arc<Pool> {
495        Arc::new(Pool { idle: Mutex::new(Vec::new()), per_host, max_idle, idle_ms })
496    }
497
498    /// the connections waiting now
499    pub fn idle(&self) -> usize {
500        self.idle.lock().len()
501    }
502
503    /// close them all
504    pub fn clear(&self) {
505        self.idle.lock().clear();
506    }
507
508    fn take(&self, key: &str) -> Option<(Box<dyn Stream>, Option<Endpoint>)> {
509        let now = plat::time_us();
510        let mut v = self.idle.lock();
511        v.retain(|c| now.saturating_sub(c.since_us) < self.idle_ms as u64 * 1000);
512        while let Some(i) = v.iter().rposition(|c| c.key == key) {
513            let c = v.remove(i);
514            // bytes or an end while idle: the server closed it, or sent what nobody asked for
515            if !c.conn.wait_readable(0) {
516                return Some((c.conn, c.via));
517            }
518        }
519        None
520    }
521
522    fn put(&self, key: String, conn: Box<dyn Stream>, via: Option<Endpoint>, tls: Option<Connector>) {
523        if self.per_host == 0 || self.max_idle == 0 {
524            return;
525        }
526        let mut v = self.idle.lock();
527        if v.iter().filter(|c| c.key == key).count() >= self.per_host {
528            if let Some(i) = v.iter().position(|c| c.key == key) {
529                v.remove(i);
530            }
531        }
532        if v.len() >= self.max_idle {
533            v.remove(0);
534        }
535        v.push(Idle { key, conn, via, _tls: tls, since_us: plat::time_us() });
536    }
537}
538
539impl Client {
540    pub fn new() -> Client {
541        Client {
542            connect_ms: 5000,
543            timeout_ms: 30_000,
544            deadline_ms: 0,
545            max_body: 64 << 20,
546            user_agent: String::from("JFLib-netio"),
547            redirects: 0,
548            decode: true,
549            connector: None,
550            proxy: None,
551            pool: None,
552            cookies: None,
553            redirect_check: None,
554        }
555    }
556
557    /// the TLS layer for https URLs
558    pub fn with_connector(mut self, c: Connector) -> Client {
559        self.connector = Some(c);
560        self
561    }
562
563    /// requests go through these proxies (netio::proxy)
564    pub fn with_proxy(mut self, p: Proxy) -> Client {
565        self.proxy = Some(p);
566        self
567    }
568
569    /// connections stay open for the next requests (keep-alive); clones of the client share them
570    pub fn with_pool(mut self, p: Arc<Pool>) -> Client {
571        self.pool = Some(p);
572        self
573    }
574
575    /// cookies: what answers set is stored in the jar, a request without a Cookie header of the
576    /// caller's sends the jar's for its URL (netpkt::cookie, with the public suffix list)
577    pub fn with_cookies(mut self, jar: Arc<Mutex<Jar>>) -> Client {
578        self.cookies = Some(jar);
579        self
580    }
581
582    /// redirects: followed up to `n` (0: none)
583    pub fn with_redirects(mut self, n: u8) -> Client {
584        self.redirects = n;
585        self
586    }
587
588    /// each redirect first asks f(from, to); false: the 3xx answer is the result
589    pub fn with_redirect_check(mut self, f: RedirectCheck) -> Client {
590        self.redirect_check = Some(f);
591        self
592    }
593
594    /// the jar given to with_cookies
595    pub fn cookies(&self) -> Option<&Arc<Mutex<Jar>>> {
596        self.cookies.as_ref()
597    }
598
599    fn deadline(&self) -> Option<u64> {
600        (self.deadline_ms > 0).then(|| plat::time_us() + self.deadline_ms as u64 * 1000)
601    }
602
603    // A TCP connection, within the deadline: the name lookup has the resolver's own timeouts
604    // (the deadline is checked before and after it); each address tried gets connect_ms or the
605    // time left, whichever is less
606    fn tcp(&self, url: &Url, deadline: Option<u64>) -> Result<TcpStream, HttpError> {
607        within(self.connect_ms, deadline)?;
608        let addrs = crate::dns::resolve(&url.host, url.port)?;
609        let mut last = NetError::new(NetErrorKind::NotFound, 0);
610        let mut got = None;
611        for a in &addrs {
612            match TcpStream::connect(a, within(self.connect_ms, deadline)?) {
613                Ok(s) => {
614                    got = Some(s);
615                    break;
616                }
617                Err(e) => last = e,
618            }
619        }
620        let tcp = got.ok_or(HttpError::Net(last))?;
621        let _ = tcp.set_nodelay(true);
622        self.bound(&tcp, deadline)?;
623        Ok(tcp)
624    }
625
626    // the client's timeout for each read and write on s, or the time left when that is less
627    // (a kept connection gets this client's, not those of the one that opened it)
628    fn bound(&self, s: &dyn Stream, deadline: Option<u64>) -> Result<(), HttpError> {
629        let ms = within(self.timeout_ms, deadline)?;
630        s.set_timeouts(Some(ms), Some(ms));
631        Ok(())
632    }
633
634    fn tls(&self, url: &Url, tcp: TcpStream) -> Result<Box<dyn Stream>, HttpError> {
635        let c = self.connector.as_ref().ok_or_else(|| HttpError::Url(String::from("https needs a TLS connector")))?;
636        c(url, tcp)
637    }
638
639    /// open the connection a request to `url` goes over, directly (no proxy)
640    pub fn connect(&self, url: &Url) -> Result<Box<dyn Stream>, HttpError> {
641        let tcp = self.tcp(url, None)?;
642        if url.is_https() { self.tls(url, tcp) } else { Ok(Box::new(tcp)) }
643    }
644
645    // a CONNECT tunnel through the proxy to url's host and port (RFC 9110 9.3.6)
646    fn tunnel(&self, tcp: &TcpStream, ep: &Endpoint, url: &Url, deadline: Option<u64>) -> Result<(), HttpError> {
647        let mut h = Headers::new();
648        h.set("Host", &url.authority());
649        h.set("User-Agent", &self.user_agent);
650        if let Some(a) = ep.authorization() {
651            h.set("Proxy-Authorization", a);
652        }
653        let s = Bounded::new(tcp, self.timeout_ms, deadline);
654        if !http::write_request(&s, "CONNECT", &url.authority(), &h, &[]) {
655            return Err(s.write_failed().0);
656        }
657        let mut rd = Reader::new(&s);
658        rd.set_deadline(deadline);
659        let head = read_head(&mut rd).map_err(read_err)?;
660        if !(200..300).contains(&head.status) {
661            return Err(HttpError::Proxy(head.status));
662        }
663        // the proxy's own bytes past its answer would pass for the server's
664        if rd.has_buffered() {
665            return Err(HttpError::Bad);
666        }
667        Ok(())
668    }
669
670    // a new connection for url: direct, to the proxy (http), or through its tunnel (https)
671    fn open(&self, url: &Url, deadline: Option<u64>) -> Result<(Box<dyn Stream>, Option<Endpoint>), HttpError> {
672        let Some(ep) = self.proxy.as_ref().and_then(|p| p.for_url(url)).cloned() else {
673            let tcp = self.tcp(url, deadline)?;
674            return Ok((if url.is_https() { self.tls_within(url, tcp, deadline)? } else { Box::new(tcp) }, None));
675        };
676        let tcp = self.tcp(&ep.url(), deadline)?;
677        if !url.is_https() {
678            return Ok((Box::new(tcp), Some(ep)));
679        }
680        self.tunnel(&tcp, &ep, url, deadline)?;
681        Ok((self.tls_within(url, tcp, deadline)?, None))
682    }
683
684    // The TLS layer over tcp within the deadline.  The handshake is the connector's: the
685    // socket's timeouts are set once, to the time left when the handshake begins, so each of its
686    // reads and writes may take that long; a handshake that ends past the deadline, done or
687    // failed, is TimedOut
688    fn tls_within(&self, url: &Url, tcp: TcpStream, deadline: Option<u64>) -> Result<Box<dyn Stream>, HttpError> {
689        self.bound(&tcp, deadline)?;
690        let r = self.tls(url, tcp);
691        within(self.timeout_ms, deadline)?;
692        r
693    }
694
695    // What tells kept connections apart: the origin, the proxy with its credentials (a hash:
696    // a tunnel or a proxy connection is not lent to a client with other ones), the TLS layer
697    // (its address; the pool holds the connector while its connections wait, so the address
698    // cannot pass to another one meanwhile)
699    fn pool_key(&self, url: &Url) -> String {
700        let via = match self.proxy.as_ref().and_then(|p| p.for_url(url)) {
701            Some(e) => {
702                let who = e.authorization().map(|a| crypto::sha256(a.as_bytes())).unwrap_or_default();
703                format!("{}#{}", e.key(), who.iter().map(|b| format!("{:02x}", b)).collect::<String>())
704            }
705            None => String::new(),
706        };
707        let tls = self.connector.as_ref().map_or(0, |c| Arc::as_ptr(c) as *const () as usize);
708        format!("{}|{}|{}|{:x}", url.scheme, url.authority(), via, tls)
709    }
710
711    // the cookies of the jar for a request (None: no jar, the caller's own header, or none)
712    fn cookie_header(&self, req: &Hop) -> Option<String> {
713        let jar = self.cookies.as_ref()?;
714        if req.headers.get("cookie").is_some() {
715            return None;
716        }
717        let now = plat::unix_time_ns().div_euclid(1_000_000_000);
718        let safe = matches!(req.method, "GET" | "HEAD");
719        let a = Asks { host: &req.url.host, path: req.url.path(), secure: req.url.is_https(), http: true, site: None, top: true, safe };
720        Some(jar.lock().header(&a, now)).filter(|h| !h.is_empty())
721    }
722
723    fn store_cookies(&self, url: &Url, h: &Headers) {
724        let Some(jar) = self.cookies.as_ref() else { return };
725        let now = plat::unix_time_ns().div_euclid(1_000_000_000);
726        let o = Origin { host: &url.host, path: url.path(), secure: url.is_https(), http: true };
727        let mut jar = jar.lock();
728        for (_, v) in h.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case("set-cookie")) {
729            let _ = jar.store(v, o, now);
730        }
731    }
732
733    /// One request over `s` and its answer: the head to `read`, which reads the body.  `via`:
734    /// the proxy that gets it in absolute form; `keep`: ask for keep-alive.  -> the answer and
735    /// whether the connection may carry another request, or the error and whether the
736    /// connection ended before any answer (a kept one the server had closed: worth a retry)
737    fn on_stream(&self, s: &dyn Stream, req: &Hop, via: Option<&Endpoint>, keep: bool, deadline: Option<u64>, read: ReadFn) -> Result<(Response, bool), (HttpError, bool)> {
738        let b = Bounded::new(s, self.timeout_ms, deadline);
739        let s: &dyn Stream = &b;
740        let mut h = req.headers.clone();
741        if h.get("host").is_none() {
742            h.set("Host", &req.url.host_header());
743        }
744        if h.get("user-agent").is_none() {
745            h.set("User-Agent", &self.user_agent);
746        }
747        h.set("Connection", if keep { "keep-alive" } else { "close" });
748        let decode = self.decode && req.method != "HEAD" && h.get("accept-encoding").is_none() && h.get("range").is_none();
749        if decode {
750            h.set("Accept-Encoding", ACCEPT_ENCODING);
751        }
752        if let Some(c) = self.cookie_header(req) {
753            h.set("Cookie", &c);
754        }
755        let target = match via {
756            Some(ep) => {
757                if let Some(a) = ep.authorization() {
758                    h.set("Proxy-Authorization", a);
759                }
760                format!("{}", req.url) // absolute form (RFC 9112 3.2.2)
761            }
762            None => {
763                // credentials for a proxy are no business of the server's (RFC 9110 11.7.2)
764                h.remove("proxy-authorization");
765                req.url.target.clone()
766            }
767        };
768        if !http::write_request(s, req.method, &target, &h, req.body) {
769            return Err(b.write_failed());
770        }
771        let mut rd = Reader::new(s);
772        rd.set_deadline(deadline);
773        let head = match read_head(&mut rd) {
774            Ok(h) => h,
775            Err(ReadError::Closed) => return Err((HttpError::Bad, true)),
776            Err(e) => return Err((read_err(e), false)),
777        };
778        self.store_cookies(req.url, &head.headers);
779        let none = req.method == "HEAD" || head.status == 204 || head.status == 304;
780        let te = head.headers.get("transfer-encoding").is_some();
781        let cl = head.headers.get("content-length").is_some();
782        let until_close = !none && !te && !cl;
783        let mut shown = head.headers.clone();
784        let dec = if decode && !none { decoder_of(&head.headers) } else { None };
785        if dec.is_some() {
786            shown.remove("content-encoding");
787            shown.remove("content-length");
788        }
789        let mut body = Incoming { rd: &mut rd, raw: &head.headers, until_close, dec, none, done: false };
790        let r = read(head.status, &shown, &mut body).map_err(|e| (e, false))?;
791        let done = body.done;
792        let alive = !head.headers.has_token("connection", "close") && (head.minor >= 1 || head.headers.has_token("connection", "keep-alive"));
793        // TE with CL is a smuggling attempt or a broken server: the connection goes (RFC 9112 6.3)
794        let again = keep && alive && done && !until_close && !(te && cl) && !rd.has_buffered();
795        Ok((r, again))
796    }
797
798    // one request on a kept or a new connection (a kept one that turns out closed: once more)
799    fn hop(&self, req: &Hop, deadline: Option<u64>, read: ReadFn) -> Result<Response, HttpError> {
800        let key = self.pool.as_ref().map(|_| self.pool_key(req.url));
801        for attempt in 0..2 {
802            let kept = match (&self.pool, &key) {
803                (Some(p), Some(k)) if attempt == 0 => p.take(k),
804                _ => None,
805            };
806            let reused = kept.is_some();
807            let (s, via) = match kept {
808                Some(c) => c,
809                None => self.open(req.url, deadline)?,
810            };
811            self.bound(&*s, deadline)?;
812            match self.on_stream(&*s, req, via.as_ref(), key.is_some(), deadline, read) {
813                Ok((r, again)) => {
814                    match (&self.pool, key) {
815                        (Some(p), Some(k)) if again => p.put(k, s, via, self.connector.clone()),
816                        _ => s.shutdown(),
817                    }
818                    return Ok(r);
819                }
820                Err((e, unanswered)) => {
821                    if !(reused && unanswered && idempotent(req.method)) {
822                        return Err(e);
823                    }
824                }
825            }
826        }
827        Err(HttpError::Bad)
828    }
829
830    // a request with its redirects -> the last URL and its answer
831    fn run(&self, method: &str, url: &Url, headers: &Headers, body: &[u8], read: ReadFn) -> Result<(Url, Response), HttpError> {
832        let deadline = self.deadline();
833        let (mut m, mut u, mut h, mut b) = (String::from(method), url.clone(), headers.clone(), body);
834        let mut hops = 0usize;
835        loop {
836            let mut next: Option<(Url, u16)> = None;
837            let follow = self.redirects > 0;
838            let r = {
839                let (cur, check, limit) = (&u, &self.redirect_check, self.redirects as usize);
840                self.hop(&Hop { method: &m, url: &u, headers: &h, body: b }, deadline, &mut |status, hd, inc| {
841                    if follow && is_redirect(status) {
842                        if let Some(loc) = hd.get("location") {
843                            let to = cur.join(loc.trim()).ok_or_else(|| HttpError::Redirect(String::from("a Location that is not an http(s) URL")))?;
844                            if check.as_ref().is_none_or(|f| f(cur, &to)) {
845                                if cur.is_https() && !to.is_https() {
846                                    return Err(HttpError::Redirect(format!("from https to http ({})", to)));
847                                }
848                                if hops >= limit {
849                                    return Err(HttpError::Redirect(format!("more than {} redirects", limit)));
850                                }
851                                // its body is read (the connection can go on), up to a limit
852                                let _ = inc.to(REDIRECT_BODY, &mut |_| true);
853                                next = Some((to, status));
854                                return Ok(Response { status, headers: hd.clone(), body: Body::Empty });
855                            }
856                        }
857                    }
858                    read(status, hd, inc)
859                })?
860            };
861            let Some((to, status)) = next else { return Ok((u, r)) };
862            hops += 1;
863            // 303 (but HEAD), and 301 / 302 after a POST, go on as GET without the body
864            if (status == 303 && m != "HEAD") || ((status == 301 || status == 302) && m == "POST") {
865                m = String::from("GET");
866                b = &[];
867                for n in ["content-type", "content-length", "content-encoding", "content-language", "content-location", "transfer-encoding"] {
868                    h.remove(n);
869                }
870            }
871            // credentials stay with their origin
872            if !u.same_origin(&to) {
873                for n in ["authorization", "cookie", "proxy-authorization", "host"] {
874                    h.remove(n);
875                }
876            }
877            u = to;
878        }
879    }
880
881    /// send one request and read the whole answer
882    pub fn request(&self, method: &str, url: &Url, headers: &Headers, body: &[u8]) -> Result<Response, HttpError> {
883        self.fetch(method, url, headers, body).map(|f| f.response)
884    }
885
886    /// request(), and the URL the answer came from (after redirects)
887    pub fn fetch(&self, method: &str, url: &Url, headers: &Headers, body: &[u8]) -> Result<Fetched, HttpError> {
888        let max = self.max_body;
889        let (url, response) = self.run(method, url, headers, body, &mut |status, headers, inc| {
890            let body = inc.all(max)?;
891            Ok(Response { status, headers: headers.clone(), body: Body::Bytes(body) })
892        })?;
893        Ok(Fetched { url, response })
894    }
895
896    /// One request over a connection the caller opened (a socket of its own, a test's stream):
897    /// the client's headers, cookies and decoding, no proxy, pool or redirects; the request asks
898    /// to close the connection, and the stream stays open (with deadline_ms, its timeouts are
899    /// the time left as the request goes)
900    pub fn request_on(&self, s: &dyn Stream, method: &str, url: &Url, headers: &Headers, body: &[u8]) -> Result<Response, HttpError> {
901        let max = self.max_body;
902        let req = Hop { method, url, headers, body };
903        self.on_stream(s, &req, None, false, self.deadline(), &mut |status, headers, inc| {
904            let body = inc.all(max)?;
905            Ok(Response { status, headers: headers.clone(), body: Body::Bytes(body) })
906        })
907        .map(|(r, _)| r)
908        .map_err(|(e, _)| e)
909    }
910
911    /// a GET whose answer goes piece by piece to `on` (downloads larger than memory): first
912    /// Part::Head (false: skip the body), then Part::Data for every piece of the body (false:
913    /// stop, Err(HttpError::Bad)).  The body may have up to `max` bytes.  Redirects the client
914    /// follows do not reach `on`.  -> the status and the headers
915    pub fn get_to(&self, url: &Url, headers: &Headers, max: u64, on: &mut dyn FnMut(Part<'_>) -> bool) -> Result<(u16, Headers), HttpError> {
916        self.run("GET", url, headers, &[], &mut |status, headers, inc| {
917            if on(Part::Head(status, headers)) {
918                inc.to(max, &mut |b| on(Part::Data(b)))?;
919            }
920            Ok(Response { status, headers: headers.clone(), body: Body::Empty })
921        })
922        .map(|(_, r)| (r.status, r.headers))
923    }
924
925    pub fn get(&self, url: &Url, headers: &Headers) -> Result<Response, HttpError> {
926        self.request("GET", url, headers, &[])
927    }
928
929    /// request() on the blocking pool (plat::task::spawn_blocking): a future of the answer
930    pub fn request_async(&self, method: &str, url: &Url, headers: &Headers, body: Vec<u8>) -> impl Future<Output = Result<Response, HttpError>> + use<> {
931        let (c, m, u, h) = (self.clone(), String::from(method), url.clone(), headers.clone());
932        plat::task::spawn_blocking(move || c.request(&m, &u, &h, &body))
933    }
934
935    /// A GET whose body goes into the file at path, on the blocking pool.  The file is replaced
936    /// like plat::write_file (plat::AtomicFile) and only by the whole body of a 2xx answer;
937    /// other answers leave it alone.  ctl.progress counts the bytes (the total from
938    /// Content-Length); ctl.cancel, or dropping the future, stops between pieces:
939    /// Err(Cancelled), the file unchanged.  -> the status
940    pub fn download(&self, url: &Url, headers: &Headers, path: &str, ctl: &Ctl) -> impl Future<Output = Result<u16, HttpError>> + use<> {
941        let (c, u, h, p, ctl) = (self.clone(), url.clone(), headers.clone(), String::from(path), ctl.clone());
942        plat::task::spawn_cancellable(move |gone| c.download_to(&u, &h, &p, &ctl, gone))
943    }
944
945    fn download_to(&self, url: &Url, headers: &Headers, path: &str, ctl: &Ctl, gone: &CancelToken) -> Result<u16, HttpError> {
946        let stop = || ctl.cancel.is_cancelled() || gone.is_cancelled();
947        if stop() {
948            return Err(HttpError::Cancelled);
949        }
950        let mut file: Option<plat::AtomicFile> = None;
951        let mut off = 0u64;
952        let mut failed = false;
953        let r = self.get_to(url, headers, u64::MAX, &mut |part| match part {
954            Part::Head(status, h) => {
955                if !(200..300).contains(&status) || stop() {
956                    return false; // the body is skipped
957                }
958                if let Some(n) = h.get("content-length").and_then(|v| v.trim().parse::<u64>().ok()) {
959                    ctl.progress.set_total(n);
960                }
961                file = plat::AtomicFile::create(path);
962                failed = file.is_none();
963                !failed
964            }
965            Part::Data(b) => {
966                let Some(f) = file.as_ref().filter(|_| !stop()) else { return false };
967                if f.write_at(off, b) != Some(b.len()) {
968                    failed = true;
969                    return false;
970                }
971                off += b.len() as u64;
972                ctl.progress.set(off);
973                true
974            }
975        });
976        // the AtomicFile is dropped unless committed: its sibling goes, the file stays
977        if stop() {
978            return Err(HttpError::Cancelled);
979        }
980        if failed {
981            return Err(HttpError::File);
982        }
983        let (status, _) = r?;
984        if let Some(f) = file {
985            if !f.commit() {
986                return Err(HttpError::File);
987            }
988        }
989        Ok(status)
990    }
991}
992
993/// requests over one kept-alive connection (reconnected when the server closed it); the
994/// client's proxy, cookies and decoding apply, its pool and redirects do not
995pub struct Session {
996    client: Client,
997    url: Url,
998    conn: Option<(Box<dyn Stream>, Option<Endpoint>)>,
999}
1000
1001impl Session {
1002    pub fn new(client: Client, url: Url) -> Session {
1003        Session { client, url, conn: None }
1004    }
1005
1006    pub fn url(&self) -> &Url {
1007        &self.url
1008    }
1009
1010    fn once(&mut self, deadline: Option<u64>, method: &str, target: &str, headers: &Headers, body: &[u8], max_body: usize) -> Result<Response, (HttpError, bool)> {
1011        let reused = self.conn.is_some();
1012        if self.conn.is_none() {
1013            self.conn = Some(self.client.open(&self.url, deadline).map_err(|e| (e, false))?);
1014        }
1015        let (s, via) = self.conn.as_ref().ok_or((HttpError::Bad, false))?;
1016        self.client.bound(&**s, deadline).map_err(|e| (e, false))?;
1017        let url = self.url.with_target(target);
1018        let req = Hop { method, url: &url, headers, body };
1019        let r = self.client.on_stream(&**s, &req, via.as_ref(), true, deadline, &mut |status, headers, inc| {
1020            let body = inc.all(max_body)?;
1021            Ok(Response { status, headers: headers.clone(), body: Body::Bytes(body) })
1022        });
1023        match r {
1024            Ok((r, again)) => {
1025                if !again {
1026                    self.conn = None;
1027                }
1028                Ok(r)
1029            }
1030            Err((e, unanswered)) => {
1031                self.conn = None;
1032                Err((e, reused && unanswered))
1033            }
1034        }
1035    }
1036
1037    /// one request (an answer of at most `max_body` bytes)
1038    pub fn request(&mut self, method: &str, target: &str, headers: &Headers, body: &[u8], max_body: usize) -> Result<Response, HttpError> {
1039        // one deadline for both tries
1040        let deadline = self.client.deadline();
1041        for attempt in 0..2 {
1042            match self.once(deadline, method, target, headers, body, max_body) {
1043                Ok(r) => return Ok(r),
1044                // a request that may have run already is not sent twice
1045                Err((e, retry)) => {
1046                    if !(retry && idempotent(method) && attempt == 0) {
1047                        return Err(e);
1048                    }
1049                }
1050            }
1051        }
1052        Err(HttpError::Bad)
1053    }
1054}
1055
1056/// "Bearer <token>" headers plus JSON content type
1057pub fn json_headers(token: &str) -> Headers {
1058    let mut h = Headers::new();
1059    h.set("Accept", "application/json");
1060    h.set("Content-Type", "application/json");
1061    if !token.is_empty() {
1062        h.set("Authorization", &format!("Bearer {}", token));
1063    }
1064    h
1065}