1use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::Duration;
6
7use http::Method;
8use hyper_util::rt::TokioExecutor;
9use tokio::sync::Mutex;
10
11use crate::error::{Error, Result};
12use crate::headers::Headers;
13use crate::http_version::HttpVersionPolicy;
14use crate::limits::Limits;
15use crate::pool::{Pool, PoolConfig, PoolMetrics};
16#[cfg(feature = "proxy")]
17use crate::proxy::Proxy;
18use crate::redirect::RedirectPolicy;
19use crate::request::{Request, RequestBuilder};
20use crate::response::Response;
21use crate::retry::RetryPolicy;
22use crate::timeout::Timeout;
23use crate::transport::Connector;
24
25#[cfg(feature = "cookies")]
26use crate::cookie::CookieJar;
27
28#[derive(Clone)]
34pub(crate) struct ClientConfig {
35 pub(crate) default_headers: Headers,
36 pub(crate) user_agent: Option<String>,
37 pub(crate) timeout: Option<Timeout>,
38 pub(crate) redirect: RedirectPolicy,
39 pub(crate) auth: Option<crate::auth::AuthScheme>,
40 #[cfg(feature = "cookies")]
41 pub(crate) cookie_jar: CookieJar,
42 pub(crate) automatic_decompression: bool,
43 pub(crate) max_decoded_body_size: Option<usize>,
44 pub(crate) max_decompression_ratio: Option<f64>,
45 #[cfg(feature = "proxy")]
46 pub(crate) proxy: Option<Proxy>,
47 #[cfg(feature = "proxy")]
48 pub(crate) environment_proxies: Vec<Proxy>,
49 #[cfg(any(feature = "proxy", feature = "http3"))]
50 pub(crate) tls_config: Option<crate::tls::TlsConfig>,
51 pub(crate) retry: Option<RetryPolicy>,
52 #[allow(
53 dead_code,
54 reason = "stored for inspection and future request-level use"
55 )]
56 pub(crate) http_version_policy: HttpVersionPolicy,
57}
58
59impl std::fmt::Debug for ClientConfig {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 let mut debug = f.debug_struct("ClientConfig");
62 debug
63 .field("default_headers", &self.default_headers)
64 .field("user_agent", &self.user_agent)
65 .field("timeout", &self.timeout)
66 .field("redirect", &self.redirect)
67 .field("auth", &self.auth);
68 #[cfg(feature = "cookies")]
69 debug.field("cookie_jar", &self.cookie_jar);
70 debug
71 .field("automatic_decompression", &self.automatic_decompression)
72 .field("max_decoded_body_size", &self.max_decoded_body_size)
73 .field("max_decompression_ratio", &self.max_decompression_ratio);
74 #[cfg(feature = "proxy")]
75 debug
76 .field("proxy", &self.proxy)
77 .field("environment_proxies", &self.environment_proxies);
78 #[cfg(any(feature = "proxy", feature = "http3"))]
79 debug.field("tls_config", &self.tls_config);
80 debug
81 .field("retry", &self.retry)
82 .field("http_version_policy", &self.http_version_policy)
83 .finish_non_exhaustive()
84 }
85}
86
87impl Default for ClientConfig {
88 fn default() -> Self {
89 Self {
90 default_headers: Headers::new(),
91 user_agent: None,
92 timeout: None,
93 redirect: RedirectPolicy::default(),
94 auth: None,
95 #[cfg(feature = "cookies")]
96 cookie_jar: CookieJar::new(),
97 automatic_decompression: true,
98 max_decoded_body_size: None,
99 max_decompression_ratio: None,
100 #[cfg(feature = "proxy")]
101 proxy: None,
102 #[cfg(feature = "proxy")]
103 environment_proxies: Vec::new(),
104 #[cfg(any(feature = "proxy", feature = "http3"))]
105 tls_config: None,
106 retry: None,
107 http_version_policy: HttpVersionPolicy::default(),
108 }
109 }
110}
111
112#[derive(Clone)]
117pub struct Client {
118 inner: Arc<ClientInner>,
119}
120
121impl std::fmt::Debug for Client {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 f.debug_struct("Client").finish_non_exhaustive()
124 }
125}
126
127pub(crate) struct ClientInner {
128 pub(crate) hyper_client: Option<crate::transport::TimeoutHyperClient>,
129 pub(crate) tls_config_error: Option<String>,
135 pub(crate) direct_client: Option<crate::transport::TimeoutDirectClient>,
139 pub(crate) direct_connector_config:
143 Option<crate::transport::direct_connector::DirectConnectorConfig>,
144 pub(crate) sni_clients: Mutex<HashMap<String, crate::transport::TimeoutDirectClient>>,
162 #[cfg(unix)]
164 pub(crate) uds_client: Option<crate::transport::TimeoutUdsClient>,
165 #[cfg(feature = "proxy")]
169 pub(crate) socks_clients: Mutex<
170 HashMap<crate::transport::socks::SocksRouteKey, crate::transport::TimeoutSocksClient>,
171 >,
172 pub(crate) config: ClientConfig,
173 pub(crate) pool: Pool,
174 pub(crate) transport_metrics: Arc<crate::transport::metrics::TransportMetrics>,
177 #[cfg(feature = "http3")]
178 pub(crate) h3_connector: Option<crate::transport::http3::H3Connector>,
179 #[cfg(feature = "http3")]
183 pub(crate) alt_svc_state: Arc<crate::transport::alt_svc::AltSvcState>,
184}
185
186const SNI_CLIENT_CACHE_MAX_ENTRIES: usize = 256;
188
189#[cfg(feature = "proxy")]
191const SOCKS_CLIENT_CACHE_MAX_ENTRIES: usize = 64;
192
193fn evict_one<K: std::clone::Clone + Eq + std::hash::Hash, V>(map: &mut HashMap<K, V>) {
201 if let Some(key) = map.keys().next().cloned() {
202 map.remove(&key);
203 }
204}
205
206pub(crate) fn configure_tls_alpn(
211 mut config: rustls::ClientConfig,
212 policy: crate::http_version::HttpVersionPolicyEnabler,
213) -> rustls::ClientConfig {
214 config.alpn_protocols.clear();
215 if policy.enable_http2() {
216 config.alpn_protocols.push(b"h2".to_vec());
217 }
218 if policy.enable_http1() {
219 config.alpn_protocols.push(b"http/1.1".to_vec());
220 }
221 config
222}
223
224impl ClientInner {
225 pub(crate) async fn sni_client(
232 &self,
233 sni_hostname: &str,
234 ) -> Result<crate::transport::TimeoutDirectClient> {
235 let mut clients = self.sni_clients.lock().await;
236 if let Some(client) = clients.get(sni_hostname) {
237 return Ok(client.clone());
238 }
239
240 let connect_timeout = self.config.timeout.as_ref().and_then(|t| t.connect);
241 #[cfg(any(feature = "http2", feature = "http3", feature = "proxy"))]
242 let policy = self.config.http_version_policy;
243
244 #[cfg(any(feature = "proxy", feature = "http3"))]
245 let tls_connector = match self.config.tls_config.as_ref() {
246 Some(tls_config) => {
247 let rc = tls_config
248 .build_rustls_config()
249 .map_err(|e| Error::Tls(format!("failed to build TLS config: {e}")))?;
250 let rc = configure_tls_alpn(
251 rc,
252 crate::http_version::HttpVersionPolicyEnabler::from_policy(policy),
253 );
254 Some(tokio_rustls::TlsConnector::from(Arc::new(rc)))
255 }
256 None => None,
257 };
258 #[cfg(not(any(feature = "proxy", feature = "http3")))]
259 let tls_connector = None;
260
261 let base_config = self.direct_connector_config.clone().unwrap_or(
262 crate::transport::direct_connector::DirectConnectorConfig {
263 local_address: None,
264 socket_options: Vec::new(),
265 },
266 );
267 let base_connector = crate::transport::direct_connector::DirectConnector::with_metrics(
268 base_config,
269 tls_connector,
270 self.transport_metrics.clone(),
271 );
272 let sni_connector = base_connector.with_sni(sni_hostname.to_owned());
273 let connector =
274 crate::transport::connect_timeout::ConnectTimeout::new(sni_connector, connect_timeout);
275
276 let mut builder =
277 hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
278 #[cfg(feature = "http2")]
279 if matches!(policy, crate::HttpVersionPolicy::Http2Only) {
280 builder.http2_only(true);
281 }
282 if let Some(idle_timeout) = self.pool.idle_timeout() {
287 builder.pool_idle_timeout(idle_timeout);
288 }
289 let client = builder.build(connector);
290 if clients.len() >= SNI_CLIENT_CACHE_MAX_ENTRIES {
291 evict_one(&mut clients);
292 }
293 clients.insert(sni_hostname.to_owned(), client.clone());
294 Ok(client)
295 }
296}
297
298#[cfg(feature = "proxy")]
299impl ClientInner {
300 pub(crate) async fn socks_client(
301 &self,
302 proxy: &crate::proxy::ProxyConfig,
303 ) -> Result<crate::transport::TimeoutSocksClient> {
304 let key = crate::transport::socks::SocksRouteKey::from_proxy(proxy)?;
305 let mut clients = self.socks_clients.lock().await;
306 if let Some(client) = clients.get(&key) {
307 return Ok(client.clone());
308 }
309
310 let policy = self.config.http_version_policy;
311
312 let tls_config = if let Some(config) = self.config.tls_config.as_ref() {
313 config
314 .build_rustls_config()
315 .map_err(|e| Error::Tls(format!("failed to build SOCKS TLS config: {e}")))?
316 } else {
317 let roots = crate::tls::TlsConfig::fallback_root_store();
318 rustls::ClientConfig::builder()
319 .with_root_certificates(roots)
320 .with_no_client_auth()
321 };
322 let tls_config = configure_tls_alpn(
323 tls_config,
324 crate::http_version::HttpVersionPolicyEnabler::from_policy(policy),
325 );
326 let connector = crate::transport::socks::SocksConnector::new(
327 proxy.clone(),
328 Some(tokio_rustls::TlsConnector::from(Arc::new(tls_config))),
329 None,
330 );
331 let connector = crate::transport::connect_timeout::ConnectTimeout::new(
332 connector,
333 self.config
334 .timeout
335 .as_ref()
336 .and_then(|timeout| timeout.connect),
337 );
338 let mut builder =
339 hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
340 #[cfg(feature = "http2")]
341 if matches!(policy, crate::HttpVersionPolicy::Http2Only) {
342 builder.http2_only(true);
343 }
344 let client = builder.build(connector);
345 if clients.len() >= SOCKS_CLIENT_CACHE_MAX_ENTRIES {
346 evict_one(&mut clients);
347 }
348 clients.insert(key, client.clone());
349 Ok(client)
350 }
351}
352
353impl Client {
354 #[must_use]
356 pub fn new() -> Self {
357 Self::builder().build()
358 }
359
360 #[must_use]
362 pub fn builder() -> ClientBuilder {
363 ClientBuilder::new()
364 }
365
366 pub fn get(&self, url: &str) -> Result<RequestBuilder> {
372 self.request(Method::GET, url)
373 }
374
375 pub fn post(&self, url: &str) -> Result<RequestBuilder> {
381 self.request(Method::POST, url)
382 }
383
384 pub fn put(&self, url: &str) -> Result<RequestBuilder> {
390 self.request(Method::PUT, url)
391 }
392
393 pub fn patch(&self, url: &str) -> Result<RequestBuilder> {
399 self.request(Method::PATCH, url)
400 }
401
402 pub fn delete(&self, url: &str) -> Result<RequestBuilder> {
408 self.request(Method::DELETE, url)
409 }
410
411 pub fn head(&self, url: &str) -> Result<RequestBuilder> {
417 self.request(Method::HEAD, url)
418 }
419
420 pub fn options(&self, url: &str) -> Result<RequestBuilder> {
426 self.request(Method::OPTIONS, url)
427 }
428
429 pub fn request(&self, method: Method, url: &str) -> Result<RequestBuilder> {
435 let parsed = parse_url(url)?;
436 Ok(RequestBuilder::new(self.clone(), method, parsed))
437 }
438
439 #[must_use]
444 pub fn pool_metrics(&self) -> &PoolMetrics {
445 self.inner.pool.metrics()
446 }
447
448 #[must_use]
454 pub fn transport_metrics(&self) -> &crate::transport::metrics::TransportMetrics {
455 &self.inner.transport_metrics
456 }
457
458 #[cfg(feature = "cookies")]
462 #[must_use]
463 pub fn cookies(&self) -> &CookieJar {
464 &self.inner.config.cookie_jar
465 }
466
467 #[must_use]
469 pub(crate) fn config(&self) -> &ClientConfig {
470 &self.inner.config
471 }
472
473 pub(crate) async fn send(&self, request: Request) -> Result<Response> {
489 Box::pin(crate::pipeline::send_with_retry(self, request)).await
490 }
491
492 pub(crate) async fn send_single_request(
498 &self,
499 request: Request,
500 timeout: &Timeout,
501 ) -> Result<Response> {
502 crate::pipeline::send_single_request(&self.inner, request, timeout).await
503 }
504}
505
506impl Default for Client {
507 fn default() -> Self {
508 Self::new()
509 }
510}
511
512pub struct ClientBuilder {
514 default_headers: Headers,
515 user_agent: Option<String>,
516 pool_config: PoolConfig,
517 timeout: Option<Timeout>,
518 limits: Option<Limits>,
519 redirect: RedirectPolicy,
520 auth: Option<crate::auth::AuthScheme>,
521 #[cfg(feature = "cookies")]
522 cookie_jar: Option<CookieJar>,
523 automatic_decompression: Option<bool>,
524 max_decoded_body_size: Option<usize>,
525 max_decompression_ratio: Option<f64>,
526 #[cfg(feature = "proxy")]
527 proxy: Option<Proxy>,
528 #[cfg(feature = "proxy")]
529 environment_proxies: Vec<Proxy>,
530 tls_config: Option<crate::tls::TlsConfig>,
531 retry: Option<RetryPolicy>,
532 http_version_policy: HttpVersionPolicy,
533 direct_connector_config: Option<crate::transport::direct_connector::DirectConnectorConfig>,
535 uds_path: Option<String>,
537}
538
539impl ClientBuilder {
540 #[must_use]
542 pub fn new() -> Self {
543 Self {
544 default_headers: Headers::new(),
545 user_agent: None,
546 pool_config: PoolConfig::default(),
547 timeout: None,
548 limits: None,
549 redirect: RedirectPolicy::default(),
550 auth: None,
551 #[cfg(feature = "cookies")]
552 cookie_jar: None,
553 automatic_decompression: None,
554 max_decoded_body_size: None,
555 max_decompression_ratio: None,
556 #[cfg(feature = "proxy")]
557 proxy: None,
558 #[cfg(feature = "proxy")]
559 environment_proxies: Vec::new(),
560 tls_config: None,
561 retry: None,
562 http_version_policy: HttpVersionPolicy::default(),
563 direct_connector_config: None,
564 uds_path: None,
565 }
566 }
567
568 pub fn default_header(mut self, name: &str, value: &str) -> Result<Self> {
574 self.default_headers.insert(name, value)?;
575 Ok(self)
576 }
577
578 #[must_use]
582 pub fn default_headers(mut self, headers: Headers) -> Self {
583 self.default_headers = headers;
584 self
585 }
586
587 #[must_use]
589 pub fn user_agent(mut self, agent: &str) -> Self {
590 self.user_agent = Some(agent.to_owned());
591 self
592 }
593
594 #[must_use]
604 pub fn max_idle_connections(mut self, max: usize) -> Self {
605 self.pool_config.max_idle_connections = Some(max);
606 self
607 }
608
609 #[must_use]
611 pub fn max_idle_connections_per_host(mut self, max: usize) -> Self {
612 self.pool_config.max_idle_connections_per_host = Some(max);
613 self
614 }
615
616 #[must_use]
623 pub fn max_connections(mut self, max: usize) -> Self {
624 self.pool_config.max_connections = Some(max);
625 self
626 }
627
628 #[must_use]
632 pub fn max_connections_per_host(mut self, max: usize) -> Self {
633 self.pool_config.max_connections_per_host = Some(max);
634 self
635 }
636
637 #[must_use]
645 pub fn max_in_flight_requests(mut self, max: usize) -> Self {
646 self.pool_config.max_in_flight_requests = Some(max);
647 self
648 }
649
650 #[must_use]
655 pub fn max_in_flight_requests_per_origin(mut self, max: usize) -> Self {
656 self.pool_config.max_in_flight_requests_per_origin = Some(max);
657 self
658 }
659
660 #[must_use]
662 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
663 self.pool_config.idle_timeout = Some(timeout);
664 self
665 }
666
667 #[must_use]
669 pub fn timeout(mut self, timeout: Timeout) -> Self {
670 self.timeout = Some(timeout);
671 self
672 }
673
674 #[must_use]
682 pub fn merge_timeout(mut self, timeout: Timeout) -> Self {
683 let merged = match self.timeout {
684 Some(existing) => existing.merge(Some(timeout)),
685 None => timeout,
686 };
687 self.timeout = Some(merged);
688 self
689 }
690
691 #[must_use]
697 pub fn limits(mut self, limits: Limits) -> Self {
698 self.limits = Some(limits);
699 self
700 }
701
702 #[must_use]
704 pub fn follow_redirects(mut self, follow: bool) -> Self {
705 self.redirect.follow = follow;
706 self
707 }
708
709 #[must_use]
711 pub fn max_redirects(mut self, max: usize) -> Self {
712 self.redirect.max_redirects = max;
713 self
714 }
715
716 #[must_use]
718 pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
719 self.redirect = policy;
720 self
721 }
722
723 #[cfg(feature = "cookies")]
730 #[must_use]
731 pub fn cookie_jar(mut self, jar: CookieJar) -> Self {
732 self.cookie_jar = Some(jar);
733 self
734 }
735
736 #[must_use]
742 pub fn auth(mut self, auth: impl Into<crate::auth::AuthScheme>) -> Self {
743 self.auth = Some(auth.into());
744 self
745 }
746
747 #[cfg(feature = "proxy")]
752 #[must_use]
753 pub fn proxy(mut self, proxy: Proxy) -> Self {
754 self.proxy = Some(proxy);
755 self
756 }
757
758 #[cfg(feature = "proxy")]
760 #[must_use]
761 pub fn environment_proxy(mut self, proxy: Proxy) -> Self {
762 self.environment_proxies.push(proxy);
763 self
764 }
765
766 #[cfg(feature = "proxy")]
771 #[must_use]
772 pub fn no_proxy(mut self, no_proxy: crate::proxy::NoProxy) -> Self {
773 if let Some(proxy) = self.proxy.take() {
774 self.proxy = Some(proxy.no_proxy(no_proxy));
775 }
776 self
777 }
778
779 #[must_use]
785 pub fn tls_config(mut self, config: crate::tls::TlsConfig) -> Self {
786 self.tls_config = Some(config);
787 self
788 }
789
790 #[must_use]
793 pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
794 let config = self.tls_config.take().unwrap_or_default();
795 self.tls_config = Some(config.danger_accept_invalid_certs(accept));
796 self
797 }
798
799 #[must_use]
809 pub fn automatic_decompression(mut self, enabled: bool) -> Self {
810 self.automatic_decompression = Some(enabled);
811 self
812 }
813
814 #[must_use]
818 pub fn max_decoded_body_size(mut self, max: usize) -> Self {
819 self.max_decoded_body_size = Some(max);
820 self
821 }
822
823 #[must_use]
831 pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
832 assert!(
833 ratio.is_finite() && ratio > 0.0,
834 "max_decompression_ratio must be finite and positive, got {ratio}"
835 );
836 self.max_decompression_ratio = Some(ratio);
837 self
838 }
839
840 #[must_use]
846 pub fn retry(mut self, policy: RetryPolicy) -> Self {
847 self.retry = Some(policy);
848 self
849 }
850
851 #[must_use]
860 pub fn http_version_policy(mut self, policy: HttpVersionPolicy) -> Self {
861 self.http_version_policy = policy;
862 self
863 }
864
865 #[must_use]
872 pub fn local_address(mut self, addr: std::net::SocketAddr) -> Self {
873 let config = self.direct_connector_config.get_or_insert_with(|| {
874 crate::transport::direct_connector::DirectConnectorConfig {
875 local_address: None,
876 socket_options: Vec::new(),
877 }
878 });
879 config.local_address = Some(addr);
880 self
881 }
882
883 #[must_use]
890 pub fn socket_options(
891 mut self,
892 options: Vec<crate::transport::direct_connector::SocketOption>,
893 ) -> Self {
894 let config = self.direct_connector_config.get_or_insert_with(|| {
895 crate::transport::direct_connector::DirectConnectorConfig {
896 local_address: None,
897 socket_options: Vec::new(),
898 }
899 });
900 config.socket_options = options;
901 self
902 }
903
904 #[must_use]
913 pub fn uds_path(mut self, path: String) -> Self {
914 self.uds_path = Some(path);
915 self
916 }
917
918 #[must_use]
924 #[allow(clippy::too_many_lines)]
925 pub fn build(self) -> Client {
926 use crate::http_version::HttpVersionPolicyEnabler;
927 let enabler = HttpVersionPolicyEnabler::from_policy(self.http_version_policy);
928 let transport_metrics = Arc::new(crate::transport::metrics::TransportMetrics::new());
929
930 let mut pool_config = self.pool_config;
931 if let Some(limits) = self.limits {
932 let limits_config: PoolConfig = limits.into();
933 if limits_config.max_connections.is_some() {
934 pool_config.max_connections = limits_config.max_connections;
935 }
936 if limits_config.max_connections_per_host.is_some() {
937 pool_config.max_connections_per_host = limits_config.max_connections_per_host;
938 }
939 if limits_config.max_in_flight_requests.is_some() {
940 pool_config.max_in_flight_requests = limits_config.max_in_flight_requests;
941 }
942 if limits_config.max_in_flight_requests_per_origin.is_some() {
943 pool_config.max_in_flight_requests_per_origin =
944 limits_config.max_in_flight_requests_per_origin;
945 }
946 if limits_config.max_idle_connections.is_some() {
947 pool_config.max_idle_connections = limits_config.max_idle_connections;
948 }
949 if limits_config.max_idle_connections_per_host.is_some() {
950 pool_config.max_idle_connections_per_host =
951 limits_config.max_idle_connections_per_host;
952 }
953 if limits_config.idle_timeout.is_some() {
954 pool_config.idle_timeout = limits_config.idle_timeout;
955 }
956 }
957
958 #[cfg(feature = "cookies")]
959 let cookie_jar = self.cookie_jar.unwrap_or_default();
960
961 let automatic_decompression = self.automatic_decompression.unwrap_or(true);
962 let tls_config_result = self
963 .tls_config
964 .as_ref()
965 .map(crate::tls::TlsConfig::build_rustls_config);
966 let tls_config_error = tls_config_result.as_ref().and_then(|result| {
967 result
968 .as_ref()
969 .err()
970 .map(|error| format!("failed to build TLS config: {error}"))
971 });
972
973 let hyper_client = if matches!(
978 self.http_version_policy,
979 crate::HttpVersionPolicy::Http3Only
980 ) || tls_config_error.is_some()
981 {
982 None
983 } else {
984 let https = match tls_config_result {
985 Some(Ok(mut rc)) => {
986 rc.alpn_protocols.clear();
989 let builder = hyper_rustls::HttpsConnectorBuilder::new()
990 .with_tls_config(rc)
991 .https_or_http();
992 #[cfg(feature = "http2")]
993 {
994 match (enabler.enable_http1(), enabler.enable_http2()) {
995 (true, true) => builder.enable_http1().enable_http2().build(),
996 (true | false, false) => builder.enable_http1().build(),
997 (false, true) => builder.enable_http2().build(),
998 }
999 }
1000 #[cfg(not(feature = "http2"))]
1001 {
1002 let _ = enabler;
1003 builder.enable_http1().build()
1004 }
1005 }
1006 Some(Err(_)) | None => build_fallback_connector(enabler),
1007 };
1008
1009 let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1011 let https =
1012 crate::transport::connect_timeout::ConnectTimeout::new(https, connect_timeout);
1013
1014 let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1015 #[cfg(feature = "http2")]
1023 if !enabler.enable_http1() && enabler.enable_http2() {
1024 builder.http2_only(true);
1025 }
1026 if let Some(timeout) = pool_config.idle_timeout {
1027 builder.pool_idle_timeout(timeout);
1028 }
1029 if let Some(max_idle) = pool_config
1030 .max_idle_connections_per_host
1031 .or(pool_config.max_idle_connections)
1032 {
1033 builder.pool_max_idle_per_host(max_idle);
1034 }
1035 Some(builder.build(https))
1036 };
1037
1038 #[cfg(feature = "http3")]
1039 let h3_connector = if enabler.use_http3() {
1040 crate::transport::http3::H3Connector::with_metrics(
1041 self.tls_config.clone(),
1042 &pool_config,
1043 Some(transport_metrics.clone()),
1044 )
1045 .ok()
1046 } else {
1047 None
1048 };
1049
1050 let stored_direct_config = self.direct_connector_config.clone();
1054 let direct_client = if let Some(dc_config) = self.direct_connector_config {
1055 let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1056
1057 let tls_connector = match self.tls_config.as_ref() {
1059 Some(tls_config) => match tls_config.build_rustls_config() {
1060 Ok(rc) => Some(tokio_rustls::TlsConnector::from(Arc::new(
1061 configure_tls_alpn(
1062 rc,
1063 crate::http_version::HttpVersionPolicyEnabler::from_policy(
1064 self.http_version_policy,
1065 ),
1066 ),
1067 ))),
1068 Err(_) => None,
1069 },
1070 None => None,
1071 };
1072
1073 let direct_connector =
1074 crate::transport::direct_connector::DirectConnector::with_metrics(
1075 dc_config,
1076 tls_connector,
1077 transport_metrics.clone(),
1078 );
1079 let direct_connector = crate::transport::connect_timeout::ConnectTimeout::new(
1080 direct_connector,
1081 connect_timeout,
1082 );
1083
1084 let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1085 #[cfg(feature = "http2")]
1091 if !enabler.enable_http1() && enabler.enable_http2() {
1092 builder.http2_only(true);
1093 }
1094 if let Some(timeout) = pool_config.idle_timeout {
1095 builder.pool_idle_timeout(timeout);
1096 }
1097 if let Some(max_idle) = pool_config
1098 .max_idle_connections_per_host
1099 .or(pool_config.max_idle_connections)
1100 {
1101 builder.pool_max_idle_per_host(max_idle);
1102 }
1103 Some(builder.build(direct_connector))
1104 } else {
1105 None
1106 };
1107
1108 #[cfg(not(unix))]
1112 let _ = &self.uds_path;
1113
1114 #[cfg(unix)]
1115 let uds_client = self.uds_path.map(|path| {
1116 let tls_connector = self.tls_config.as_ref().and_then(|config| {
1117 config.build_rustls_config().ok().map(|rc| {
1118 tokio_rustls::TlsConnector::from(Arc::new(configure_tls_alpn(
1119 rc,
1120 crate::http_version::HttpVersionPolicyEnabler::from_policy(
1121 self.http_version_policy,
1122 ),
1123 )))
1124 })
1125 });
1126 let connector = crate::transport::uds::UdsConnector::with_metrics(
1127 path,
1128 tls_connector,
1129 transport_metrics.clone(),
1130 );
1131 let connector = crate::transport::connect_timeout::ConnectTimeout::new(
1132 connector,
1133 self.timeout.as_ref().and_then(|timeout| timeout.connect),
1134 );
1135 let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1136 #[cfg(feature = "http2")]
1140 if !enabler.enable_http1() && enabler.enable_http2() {
1141 builder.http2_only(true);
1142 }
1143 if let Some(timeout) = pool_config.idle_timeout {
1144 builder.pool_idle_timeout(timeout);
1145 }
1146 if let Some(max_idle) = pool_config
1147 .max_idle_connections_per_host
1148 .or(pool_config.max_idle_connections)
1149 {
1150 builder.pool_max_idle_per_host(max_idle);
1151 }
1152 builder.build(connector)
1153 });
1154
1155 let config = ClientConfig {
1156 default_headers: self.default_headers,
1157 user_agent: self.user_agent,
1158 timeout: self.timeout,
1159 redirect: self.redirect,
1160 auth: self.auth,
1161 #[cfg(feature = "cookies")]
1162 cookie_jar,
1163 automatic_decompression,
1164 max_decoded_body_size: self.max_decoded_body_size,
1165 max_decompression_ratio: self.max_decompression_ratio,
1166 #[cfg(feature = "proxy")]
1167 proxy: self.proxy,
1168 #[cfg(feature = "proxy")]
1169 environment_proxies: self.environment_proxies,
1170 #[cfg(any(feature = "proxy", feature = "http3"))]
1171 tls_config: self.tls_config,
1172 retry: self.retry,
1173 http_version_policy: self.http_version_policy,
1174 };
1175
1176 let pool = Pool::new(pool_config);
1177
1178 Client {
1179 inner: Arc::new(ClientInner {
1180 hyper_client,
1181 tls_config_error,
1182 direct_client,
1183 direct_connector_config: stored_direct_config,
1184 sni_clients: Mutex::new(HashMap::new()),
1185 #[cfg(unix)]
1186 uds_client,
1187 #[cfg(feature = "proxy")]
1188 socks_clients: Mutex::new(HashMap::new()),
1189 config,
1190 pool,
1191 transport_metrics,
1192 #[cfg(feature = "http3")]
1193 h3_connector,
1194 #[cfg(feature = "http3")]
1195 alt_svc_state: Arc::new(crate::transport::alt_svc::AltSvcState::new()),
1196 }),
1197 }
1198 }
1199}
1200
1201fn build_fallback_connector(enabler: crate::http_version::HttpVersionPolicyEnabler) -> Connector {
1206 let builder = match hyper_rustls::HttpsConnectorBuilder::new().with_native_roots() {
1207 Ok(b) => b,
1208 Err(_) => hyper_rustls::HttpsConnectorBuilder::new().with_webpki_roots(),
1209 };
1210 #[cfg(feature = "http2")]
1211 {
1212 match (enabler.enable_http1(), enabler.enable_http2()) {
1213 (true, true) => builder
1214 .https_or_http()
1215 .enable_http1()
1216 .enable_http2()
1217 .build(),
1218 (true | false, false) => builder.https_or_http().enable_http1().build(),
1219 (false, true) => builder.https_or_http().enable_http2().build(),
1220 }
1221 }
1222 #[cfg(not(feature = "http2"))]
1223 {
1224 let _ = enabler;
1225 builder.https_or_http().enable_http1().build()
1226 }
1227}
1228
1229impl Default for ClientBuilder {
1230 fn default() -> Self {
1231 Self::new()
1232 }
1233}
1234
1235fn parse_url(url_str: &str) -> Result<url::Url> {
1236 let url = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl(e.to_string()))?;
1241 if !url.username().is_empty() || url.password().is_some() {
1242 return Err(Error::InvalidUrl(
1245 "URL userinfo is not supported; configure authentication explicitly".into(),
1246 ));
1247 }
1248 match url.scheme() {
1249 "http" | "https" => Ok(url),
1250 other => Err(Error::Unsupported(format!(
1251 "URL scheme '{other}' is not supported; use http or https"
1252 ))),
1253 }
1254}
1255
1256#[cfg(test)]
1257mod tests {
1258 use super::*;
1259 #[cfg(feature = "proxy")]
1260 use crate::proxy::ProxyAuth;
1261 use bytes::Bytes;
1262
1263 #[test]
1264 fn client_constructs() {
1265 let _client = Client::new();
1266 }
1267
1268 #[test]
1269 fn client_config_debug_redacts_secrets() {
1270 let mut config = ClientConfig::default();
1271 config
1272 .default_headers
1273 .insert("authorization", "Bearer header-secret-token")
1274 .unwrap();
1275 #[cfg(feature = "cookies")]
1276 config
1277 .cookie_jar
1278 .set_default_cookie("session".to_owned(), "jar-secret-token".to_owned())
1279 .expect("valid test cookie");
1280 let debug = format!("{config:?}");
1281 assert!(
1282 !debug.contains("header-secret-token"),
1283 "ClientConfig Debug must not leak header secrets: {debug}"
1284 );
1285 #[cfg(feature = "cookies")]
1286 assert!(
1287 !debug.contains("jar-secret-token"),
1288 "ClientConfig Debug must not leak jar secrets: {debug}"
1289 );
1290 }
1291
1292 #[test]
1293 fn client_default() {
1294 let _client = Client::default();
1295 }
1296
1297 #[test]
1298 fn client_builder() {
1299 let _client = Client::builder().user_agent("test-agent").build();
1300 }
1301
1302 #[test]
1303 fn client_builder_merge_timeout_preserves_other_phases() {
1304 let client = Client::builder()
1307 .timeout(Timeout::from_secs(30))
1308 .merge_timeout(
1309 Timeout::builder()
1310 .connect(std::time::Duration::from_secs(5))
1311 .build(),
1312 )
1313 .merge_timeout(
1314 Timeout::builder()
1315 .read(std::time::Duration::from_secs(10))
1316 .build(),
1317 )
1318 .build();
1319
1320 let timeout = client.inner.config.timeout.expect("timeout configured");
1321 let d = |secs: u64| std::time::Duration::from_secs(secs);
1322 assert_eq!(timeout.connect, Some(d(5)), "last connect wins");
1323 assert_eq!(timeout.read, Some(d(10)), "last read wins");
1324 assert_eq!(
1325 timeout.write,
1326 Some(d(30)),
1327 "unset phases keep earlier values"
1328 );
1329 assert_eq!(timeout.pool, Some(d(30)));
1330 }
1331
1332 #[test]
1333 fn client_builder_merge_timeout_without_prior_config() {
1334 let client = Client::builder()
1335 .merge_timeout(
1336 Timeout::builder()
1337 .connect(std::time::Duration::from_secs(5))
1338 .build(),
1339 )
1340 .build();
1341
1342 let timeout = client.inner.config.timeout.expect("timeout configured");
1343 assert_eq!(timeout.connect, Some(std::time::Duration::from_secs(5)));
1344 assert_eq!(timeout.read, None);
1345 }
1346
1347 #[cfg(any(feature = "proxy", feature = "http3"))]
1348 #[test]
1349 fn client_builder_danger_accept_invalid_certs_preserves_tls_config() {
1350 let client = Client::builder()
1351 .tls_config(crate::tls::TlsConfig::builder().sni(false).build())
1352 .danger_accept_invalid_certs(true)
1353 .build();
1354 let tls = client
1355 .inner
1356 .config
1357 .tls_config
1358 .as_ref()
1359 .expect("TLS config should be retained");
1360 assert!(!tls.sni_enabled());
1361 assert!(!tls.verify_certificate());
1362 assert!(!tls.verify_hostname());
1363 }
1364
1365 #[test]
1366 fn tls_root_store_paths_construct() {
1367 if let Ok(builder) = hyper_rustls::HttpsConnectorBuilder::new().with_native_roots() {
1370 let _ = builder.https_or_http().enable_http1().build();
1371 }
1372 let enabler =
1373 crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1374 allow_http3: false,
1375 });
1376 let _ = build_fallback_connector(enabler);
1377 }
1378
1379 #[test]
1380 fn client_builder_http1_only() {
1381 let client = Client::builder()
1382 .http_version_policy(HttpVersionPolicy::Http1Only)
1383 .build();
1384 assert_eq!(
1385 client.inner.config.http_version_policy,
1386 HttpVersionPolicy::Http1Only
1387 );
1388 }
1389
1390 #[test]
1391 fn client_builder_http2_auto() {
1392 let client = Client::builder()
1393 .http_version_policy(HttpVersionPolicy::Auto { allow_http3: false })
1394 .build();
1395 assert_eq!(
1396 client.inner.config.http_version_policy,
1397 HttpVersionPolicy::Auto { allow_http3: false }
1398 );
1399 }
1400
1401 #[test]
1402 #[cfg(feature = "http2")]
1403 fn client_builder_http2_only() {
1404 let client = Client::builder()
1405 .http_version_policy(HttpVersionPolicy::Http2Only)
1406 .build();
1407 assert_eq!(
1408 client.inner.config.http_version_policy,
1409 HttpVersionPolicy::Http2Only
1410 );
1411 }
1412
1413 #[test]
1414 fn connector_builds_for_all_policies() {
1415 for policy in [
1416 HttpVersionPolicy::Http1Only,
1417 HttpVersionPolicy::Auto { allow_http3: false },
1418 #[cfg(feature = "http2")]
1419 HttpVersionPolicy::Http2Only,
1420 #[cfg(feature = "http3")]
1421 HttpVersionPolicy::Http3Only,
1422 ] {
1423 let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(policy);
1424 if !enabler.use_http3() {
1425 let _ = build_fallback_connector(enabler);
1426 }
1427 }
1428 }
1429
1430 #[cfg(feature = "http2")]
1431 #[test]
1432 fn custom_connector_alpn_matches_http_version_policy() {
1433 let config = rustls::ClientConfig::builder()
1434 .with_root_certificates(rustls::RootCertStore::empty())
1435 .with_no_client_auth();
1436 let h2_only = configure_tls_alpn(
1437 config.clone(),
1438 crate::http_version::HttpVersionPolicyEnabler::from_policy(
1439 HttpVersionPolicy::Http2Only,
1440 ),
1441 );
1442 assert_eq!(h2_only.alpn_protocols, vec![b"h2".to_vec()]);
1443
1444 let auto = configure_tls_alpn(
1445 config,
1446 crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1447 allow_http3: false,
1448 }),
1449 );
1450 assert_eq!(
1451 auto.alpn_protocols,
1452 vec![b"h2".to_vec(), b"http/1.1".to_vec()]
1453 );
1454 }
1455
1456 #[test]
1457 fn parse_valid_urls() {
1458 assert!(parse_url("https://example.com").is_ok());
1459 assert!(parse_url("http://localhost:8080").is_ok());
1460 }
1461
1462 #[test]
1463 fn parse_invalid_schemes() {
1464 assert!(parse_url("ftp://example.com").is_err());
1465 assert!(parse_url("file:///tmp/test").is_err());
1466 }
1467
1468 #[test]
1469 fn parse_invalid_urls() {
1470 assert!(parse_url("not a url").is_err());
1471 }
1472
1473 #[test]
1474 fn get_request_builder() {
1475 let client = Client::new();
1476 let builder = client.get("https://example.com").unwrap();
1477 let req = builder.build().unwrap();
1478 assert_eq!(*req.method(), Method::GET);
1479 }
1480
1481 #[test]
1482 fn apply_content_length_empty_body() {
1483 let headers = Headers::new();
1484 let body = crate::body::RequestBody::Empty;
1485 let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1486 assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "0");
1487 }
1488
1489 #[test]
1490 fn apply_content_length_bytes_body() {
1491 let headers = Headers::new();
1492 let body = crate::body::RequestBody::from(Bytes::from("hello"));
1493 let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1494 assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1495 }
1496
1497 #[test]
1498 fn apply_content_length_stream_known() {
1499 let headers = Headers::new();
1500 let stream = futures_util::stream::empty::<Result<Bytes>>();
1501 let body = crate::body::RequestBody::from_stream(stream, Some(7));
1502 let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1503 assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "7");
1504 }
1505
1506 #[test]
1507 fn apply_content_length_stream_unknown() {
1508 let headers = Headers::new();
1509 let stream = futures_util::stream::empty::<Result<Bytes>>();
1510 let body = crate::body::RequestBody::from_stream(stream, None);
1511 let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1512 assert!(out.get("content-length").is_none());
1513 }
1514
1515 #[test]
1516 fn apply_content_length_user_matches() {
1517 let mut headers = Headers::new();
1518 headers.insert("content-length", "5").unwrap();
1519 let body = crate::body::RequestBody::from(Bytes::from("hello"));
1520 let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1521 assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1522 }
1523
1524 #[test]
1525 fn apply_content_length_user_mismatch_errors() {
1526 let mut headers = Headers::new();
1527 headers.insert("content-length", "10").unwrap();
1528 let body = crate::body::RequestBody::from(Bytes::from("hello"));
1529 let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1530 assert_eq!(err.kind(), "request_build");
1531 }
1532
1533 #[test]
1534 fn apply_content_length_rejects_invalid_value() {
1535 let mut headers = Headers::new();
1536 headers.insert("content-length", "not-a-number").unwrap();
1537 let body = crate::body::RequestBody::from(Bytes::from("hello"));
1538 let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1539 assert_eq!(err.kind(), "invalid_header_value");
1540 }
1541
1542 #[test]
1543 fn apply_content_length_rejects_unknown_stream_override() {
1544 let mut headers = Headers::new();
1545 headers.insert("content-length", "5").unwrap();
1546 let stream = futures_util::stream::empty::<Result<Bytes>>();
1547 let body = crate::body::RequestBody::from_stream(stream, None);
1548 let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1549 assert_eq!(err.kind(), "request_build");
1550 }
1551
1552 #[test]
1553 fn parse_url_rejects_userinfo_without_echoing_credentials() {
1554 let err = parse_url("https://user:secret@example.com").unwrap_err();
1555 assert_eq!(err.kind(), "invalid_url");
1556 assert!(!err.to_string().contains("secret"));
1557 }
1558
1559 #[cfg(feature = "proxy")]
1560 #[tokio::test]
1561 async fn proxy_auth_conflict_with_header() {
1562 let proxy = Proxy::all("http://proxy.example:8080")
1563 .unwrap()
1564 .auth(ProxyAuth::basic("user", "pass").unwrap());
1565 let client = Client::builder().proxy(proxy).build();
1566 let request = client
1567 .get("http://destination.example")
1568 .unwrap()
1569 .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1570 .build()
1571 .unwrap();
1572 let err = client.send(request).await.unwrap_err();
1573 assert_eq!(err.kind(), "conflicting_auth");
1574 assert!(err.to_string().contains("Proxy-Authorization"));
1575 }
1576
1577 #[cfg(feature = "proxy")]
1578 #[tokio::test]
1579 async fn proxy_auth_no_conflict_without_header() {
1580 let proxy = Proxy::all("http://proxy.example:8080")
1581 .unwrap()
1582 .auth(ProxyAuth::basic("user", "pass").unwrap());
1583 let client = Client::builder().proxy(proxy).build();
1584 let request = client
1585 .get("http://destination.example")
1586 .unwrap()
1587 .build()
1588 .unwrap();
1589 let err = client.send(request).await.unwrap_err();
1590 assert_ne!(err.kind(), "conflicting_auth");
1591 }
1592
1593 #[cfg(feature = "proxy")]
1594 #[tokio::test]
1595 async fn proxy_auth_no_conflict_with_header_only() {
1596 let proxy = Proxy::all("http://proxy.example:8080").unwrap();
1597 let client = Client::builder().proxy(proxy).build();
1598 let request = client
1599 .get("http://destination.example")
1600 .unwrap()
1601 .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1602 .build()
1603 .unwrap();
1604 let err = client.send(request).await.unwrap_err();
1605 assert_ne!(err.kind(), "conflicting_auth");
1606 }
1607}