1use 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 Url(String),
76 Net(NetError),
77 Tls(String),
79 Bad,
81 TooLarge,
83 File,
85 Cancelled,
87 Redirect(String),
90 Proxy(u16),
92 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
122pub type RedirectCheck = Arc<dyn Fn(&Url, &Url) -> bool + Send + Sync>;
124
125pub enum Part<'a> {
127 Head(u16, &'a Headers),
129 Data(&'a [u8]),
131}
132
133#[derive(Debug)]
135pub struct Fetched {
136 pub url: Url,
137 pub response: Response,
138}
139
140const MAX_INTERIM: usize = 16;
142const REDIRECT_BODY: u64 = 64 << 10;
144const ACCEPT_ENCODING: &str = "gzip, br";
146const ZSTD_WINDOW: usize = 8 << 20;
148
149#[derive(Clone)]
150pub struct Client {
151 pub connect_ms: u32,
152 pub timeout_ms: u32,
154 pub deadline_ms: u32,
158 pub max_body: usize,
159 pub user_agent: String,
160 pub redirects: u8,
162 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
177struct Hop<'a> {
179 method: &'a str,
180 url: &'a Url,
181 headers: &'a Headers,
182 body: &'a [u8],
183}
184
185struct Head {
187 minor: u8,
189 status: u16,
190 headers: Headers,
191}
192
193fn 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
203fn read_head(rd: &mut Reader<'_>) -> Result<Head, ReadError> {
205 for i in 0..=MAX_INTERIM {
206 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); }
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
235fn 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
242fn within(ms: u32, deadline: Option<u64>) -> Result<u32, HttpError> {
244 left(ms, deadline).ok_or_else(|| HttpError::Net(timed_out()))
245}
246
247const WRITE_PIECE: usize = 16 << 10;
249
250struct Bounded<'a> {
254 s: &'a dyn Stream,
255 ms: u32,
256 deadline: Option<u64>,
257 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 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
331fn 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; }
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" => (Box::new(compress::zlib::Decoder::new()), false),
352 _ => return None,
353 })
354}
355
356struct 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); }
377 self.ended = false; }
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
400struct Incoming<'r, 's> {
403 rd: &'r mut Reader<'s>,
404 raw: &'r Headers,
406 until_close: bool,
407 dec: Option<(Box<dyn Decode>, bool)>,
408 none: bool,
410 done: bool,
412}
413
414impl Incoming<'_, '_> {
415 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 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 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
469struct Idle {
472 key: String,
473 conn: Box<dyn Stream>,
474 via: Option<Endpoint>,
475 _tls: Option<Connector>,
476 since_us: u64,
477}
478
479pub 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 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 pub fn idle(&self) -> usize {
500 self.idle.lock().len()
501 }
502
503 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 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 pub fn with_connector(mut self, c: Connector) -> Client {
559 self.connector = Some(c);
560 self
561 }
562
563 pub fn with_proxy(mut self, p: Proxy) -> Client {
565 self.proxy = Some(p);
566 self
567 }
568
569 pub fn with_pool(mut self, p: Arc<Pool>) -> Client {
571 self.pool = Some(p);
572 self
573 }
574
575 pub fn with_cookies(mut self, jar: Arc<Mutex<Jar>>) -> Client {
578 self.cookies = Some(jar);
579 self
580 }
581
582 pub fn with_redirects(mut self, n: u8) -> Client {
584 self.redirects = n;
585 self
586 }
587
588 pub fn with_redirect_check(mut self, f: RedirectCheck) -> Client {
590 self.redirect_check = Some(f);
591 self
592 }
593
594 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 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 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 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 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 if rd.has_buffered() {
665 return Err(HttpError::Bad);
666 }
667 Ok(())
668 }
669
670 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 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 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 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 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) }
762 None => {
763 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 let again = keep && alive && done && !until_close && !(te && cl) && !rd.has_buffered();
795 Ok((r, again))
796 }
797
798 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 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 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 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 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 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 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 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 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 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 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; }
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 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
993pub 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 pub fn request(&mut self, method: &str, target: &str, headers: &Headers, body: &[u8], max_body: usize) -> Result<Response, HttpError> {
1039 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 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
1056pub 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}