1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
//! [`ClientBuilder`] and related HTTP/2 configuration types.
//!
//! Extracted from `lib.rs` to keep individual source files under the 2 000-line
//! policy limit. All public items are re-exported from the crate root so the
//! external API is unchanged.
use http::{HeaderMap, HeaderValue, Uri};
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::Client as HyperClient;
use hyper_util::rt::TokioExecutor;
use oxihttp_core::OxiHttpError;
use std::sync::Arc;
use std::time::Duration;
use crate::middleware::ClientMiddleware;
use crate::proxy::{ProxyConnector, ProxyKind};
use crate::redirect::RedirectPolicy;
use crate::resolver::BoxResolver;
use crate::retry::RetryPolicy;
#[cfg(feature = "socks")]
use crate::proxy::Socks5Connector;
#[cfg(feature = "tls")]
use crate::connector::OxiHttpsConnector;
#[cfg(feature = "tls")]
use crate::tls;
// Re-export the Client struct and type aliases so build methods can reference them.
use super::Client;
#[cfg(feature = "tls")]
use super::TlsRebuildConfig;
// ---------------------------------------------------------------------------
// Http2Settings
// ---------------------------------------------------------------------------
/// HTTP/2 connection settings for the client.
#[derive(Debug, Clone, Default)]
pub struct Http2Settings {
/// Initial window size for stream-level flow control (bytes).
pub initial_stream_window_size: Option<u32>,
/// Initial window size for connection-level flow control (bytes).
pub initial_connection_window_size: Option<u32>,
/// Enable adaptive flow control (overrides window size settings when set).
pub adaptive_window: Option<bool>,
/// Interval for HTTP/2 PING keep-alive frames.
pub keep_alive_interval: Option<std::time::Duration>,
/// Timeout for acknowledgement of keep-alive PING before closing.
pub keep_alive_timeout: Option<std::time::Duration>,
/// Maximum HTTP/2 frame size (bytes).
pub max_frame_size: Option<u32>,
/// Maximum number of concurrent locally-reset streams.
pub max_concurrent_reset_streams: Option<usize>,
/// Maximum write buffer size per HTTP/2 stream (bytes).
pub max_send_buf_size: Option<usize>,
}
// ---------------------------------------------------------------------------
// apply_http2_settings — shared helper for all client build paths
// ---------------------------------------------------------------------------
pub(crate) fn apply_http2_settings(
builder: &mut hyper_util::client::legacy::Builder,
settings: &Http2Settings,
) {
if let Some(sz) = settings.initial_stream_window_size {
builder.http2_initial_stream_window_size(sz);
}
if let Some(sz) = settings.initial_connection_window_size {
builder.http2_initial_connection_window_size(sz);
}
if let Some(adaptive) = settings.adaptive_window {
builder.http2_adaptive_window(adaptive);
}
if let Some(interval) = settings.keep_alive_interval {
builder.http2_keep_alive_interval(interval);
}
if let Some(timeout) = settings.keep_alive_timeout {
builder.http2_keep_alive_timeout(timeout);
}
if let Some(sz) = settings.max_frame_size {
builder.http2_max_frame_size(sz);
}
if let Some(n) = settings.max_concurrent_reset_streams {
builder.http2_max_concurrent_reset_streams(n);
}
if let Some(sz) = settings.max_send_buf_size {
builder.http2_max_send_buf_size(sz);
}
}
// ---------------------------------------------------------------------------
// ClientBuilder
// ---------------------------------------------------------------------------
/// A builder for constructing a `Client` with custom configuration.
pub struct ClientBuilder {
pub(super) pool_max_idle_per_host: Option<usize>,
pub(super) pool_idle_timeout: Option<Duration>,
pub(super) connect_timeout: Option<Duration>,
pub(super) read_timeout: Option<Duration>,
pub(super) redirect_policy: RedirectPolicy,
pub(super) retry_policy: Option<RetryPolicy>,
pub(super) default_headers: HeaderMap,
pub(super) user_agent: Option<String>,
pub(super) decompression: bool,
/// Middleware interceptors applied to every request/response.
pub(super) middleware: Vec<Arc<dyn ClientMiddleware>>,
/// Optional proxy configuration.
pub(super) proxy: Option<ProxyKind>,
/// Optional shared cookie jar for automatic cookie management.
pub(super) cookie_jar: Option<Arc<std::sync::Mutex<oxihttp_core::CookieJar>>>,
/// HTTP/2 tuning settings (applied to all build paths that support H2).
pub(super) http2_settings: Option<Http2Settings>,
/// TCP_NODELAY setting for all outgoing connections.
pub(super) tcp_nodelay: Option<bool>,
/// TCP keepalive idle time for all outgoing connections.
pub(super) tcp_keepalive: Option<Duration>,
/// Custom DNS resolver (used with build_with_resolver / build_https_with_resolver).
pub(super) resolver: Option<Arc<dyn crate::resolver::DnsResolver>>,
// TLS options (only active when `tls` feature is enabled)
#[cfg(feature = "tls")]
pub(super) trusted_certs_der: Vec<Vec<u8>>,
#[cfg(feature = "tls")]
pub(super) alpn: Vec<String>,
#[cfg(feature = "tls")]
pub(super) accept_invalid_certs: bool,
#[cfg(feature = "tls")]
pub(super) use_webpki_roots: bool,
/// Optional path for SSLKEYLOGFILE-style key logging (development/debugging only).
#[cfg(feature = "tls")]
pub(super) key_log_path: Option<std::path::PathBuf>,
/// Enable TLS 1.3 0-RTT early data (HTTP fast-open) for subsequent requests.
#[cfg(feature = "tls")]
pub(super) early_data: bool,
/// Optional custom server-certificate verifier. When `Some`, takes
/// precedence over `accept_invalid_certs` and all trust-store settings.
#[cfg(feature = "tls")]
pub(super) custom_cert_verifier:
Option<std::sync::Arc<dyn rustls::client::danger::ServerCertVerifier>>,
}
impl ClientBuilder {
/// Create a new `ClientBuilder` with default settings.
pub fn new() -> Self {
Self {
pool_max_idle_per_host: None,
pool_idle_timeout: None,
connect_timeout: None,
read_timeout: None,
redirect_policy: RedirectPolicy::default(),
retry_policy: None,
default_headers: HeaderMap::new(),
user_agent: None,
decompression: false,
middleware: Vec::new(),
proxy: None,
cookie_jar: None,
http2_settings: None,
tcp_nodelay: None,
tcp_keepalive: None,
resolver: None,
#[cfg(feature = "tls")]
trusted_certs_der: Vec::new(),
#[cfg(feature = "tls")]
alpn: Vec::new(),
#[cfg(feature = "tls")]
accept_invalid_certs: false,
#[cfg(feature = "tls")]
use_webpki_roots: false,
#[cfg(feature = "tls")]
key_log_path: None,
#[cfg(feature = "tls")]
early_data: false,
#[cfg(feature = "tls")]
custom_cert_verifier: None,
}
}
/// Set the maximum number of idle connections per host in the pool.
pub fn pool_max_idle_per_host(mut self, n: usize) -> Self {
self.pool_max_idle_per_host = Some(n);
self
}
/// Set the idle timeout for pooled connections.
pub fn pool_idle_timeout(mut self, duration: Duration) -> Self {
self.pool_idle_timeout = Some(duration);
self
}
/// Set the TCP connect timeout.
pub fn connect_timeout(mut self, duration: Duration) -> Self {
self.connect_timeout = Some(duration);
self
}
/// Set the response read timeout.
pub fn read_timeout(mut self, duration: Duration) -> Self {
self.read_timeout = Some(duration);
self
}
/// Set the redirect policy.
pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
self.redirect_policy = policy;
self
}
/// Set the retry policy.
pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
self.retry_policy = Some(policy);
self
}
/// Set default headers to include on every request.
pub fn default_headers(mut self, headers: HeaderMap) -> Self {
self.default_headers = headers;
self
}
/// Set the User-Agent header for all requests.
pub fn user_agent(mut self, agent: impl Into<String>) -> Self {
self.user_agent = Some(agent.into());
self
}
/// Enable or disable automatic response decompression.
///
/// When enabled the client adds `Accept-Encoding: gzip, deflate` to
/// outgoing requests and transparently decompresses the response body
/// based on the `Content-Encoding` header (requires `decompression`
/// feature).
pub fn with_decompression(mut self, enabled: bool) -> Self {
self.decompression = enabled;
self
}
// --- middleware --------------------------------------------------------
/// Register a request/response middleware interceptor.
///
/// Middleware is invoked in registration order: `before_request` fires
/// in FIFO order before the first network attempt; `after_response` fires
/// in FIFO order after a successful final response.
///
/// Multiple calls to this method append to the middleware stack.
///
/// # Example
///
/// ```rust,no_run
/// use oxihttp_client::{Client, middleware::LoggingMiddleware};
///
/// let client = Client::builder()
/// .with_middleware(LoggingMiddleware::new("api"))
/// .build()
/// .expect("client build");
/// ```
pub fn with_middleware<M: ClientMiddleware + 'static>(mut self, m: M) -> Self {
self.middleware.push(Arc::new(m));
self
}
/// Alias for [`ClientBuilder::with_middleware`].
///
/// Provided so that callers familiar with the `tower::Layer` terminology
/// can use the same name. This does **not** accept a `tower::Layer`; for
/// a full tower `Service` composition see the `tower_compat` module docs.
pub fn with_layer<M: ClientMiddleware + 'static>(self, m: M) -> Self {
self.with_middleware(m)
}
// --- cookie jar builder methods ------------------------------------------
/// Configure the client to use the given shared cookie jar for automatic cookie management.
pub fn with_cookie_jar(mut self, jar: Arc<std::sync::Mutex<oxihttp_core::CookieJar>>) -> Self {
self.cookie_jar = Some(jar);
self
}
/// Configure the client to create and use a fresh cookie jar automatically.
pub fn with_new_cookie_jar(mut self) -> Self {
self.cookie_jar = Some(Arc::new(std::sync::Mutex::new(
oxihttp_core::CookieJar::new(),
)));
self
}
// --- HTTP/2 and TCP tuning builder methods --------------------------------
/// Set HTTP/2 connection tuning parameters.
pub fn with_http2_settings(mut self, settings: Http2Settings) -> Self {
self.http2_settings = Some(settings);
self
}
/// Enable or disable `TCP_NODELAY` on all outgoing connections.
pub fn with_tcp_nodelay(mut self, nodelay: bool) -> Self {
self.tcp_nodelay = Some(nodelay);
self
}
/// Set the TCP keepalive idle time for all outgoing connections.
pub fn with_tcp_keepalive(mut self, duration: Duration) -> Self {
self.tcp_keepalive = Some(duration);
self
}
// --- custom DNS resolver builder methods ---------------------------------
/// Set a custom DNS resolver for all connections made by this client.
///
/// After calling this, use [`ClientBuilder::build_with_resolver`] (plain HTTP)
/// or [`ClientBuilder::build_https_with_resolver`] (TLS) to construct the client.
pub fn with_resolver<R: crate::resolver::DnsResolver>(mut self, r: R) -> Self {
self.resolver = Some(Arc::new(r));
self
}
// --- proxy builder methods -----------------------------------------------
/// Route all requests through an HTTP CONNECT proxy.
///
/// Call `build_proxy()` (plain HTTP target) or `build_proxy_https()` (HTTPS
/// target, requires `tls` feature) after setting this.
pub fn with_http_proxy(mut self, uri: Uri) -> Self {
self.proxy = Some(ProxyKind::HttpConnect(uri));
self
}
/// Route all requests through a SOCKS5 proxy.
///
/// Call `build_socks5_proxy()` (plain HTTP) or `build_socks5_proxy_https()`
/// (HTTPS, requires `tls` feature) after setting this.
#[cfg(feature = "socks")]
pub fn with_socks5_proxy(mut self, uri: Uri) -> Self {
self.proxy = Some(ProxyKind::Socks5(uri));
self
}
/// Build a plain-HTTP `Client` routed through an HTTP CONNECT proxy.
///
/// `with_http_proxy()` must have been called before this.
pub fn build_proxy(self) -> Result<Client<ProxyConnector>, OxiHttpError> {
let proxy_uri = match self.proxy.as_ref() {
Some(ProxyKind::HttpConnect(u)) => u.clone(),
#[cfg(feature = "socks")]
Some(ProxyKind::Socks5(_)) => {
return Err(OxiHttpError::ConnectionPool(
"SOCKS5 proxy configured; use build_socks5_proxy() instead".into(),
))
}
None => {
return Err(OxiHttpError::ConnectionPool(
"no proxy configured; call with_http_proxy() first".into(),
))
}
};
let connector = ProxyConnector::new(proxy_uri, self.connect_timeout);
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(dur) = self.pool_idle_timeout {
builder.pool_idle_timeout(dur);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
let inner = builder.build(connector);
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
Ok(Client {
inner,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar.clone(),
#[cfg(feature = "tls")]
tls_rebuild: None,
})
}
/// Build a plain-HTTP `Client` routed through a SOCKS5 proxy.
///
/// `with_socks5_proxy()` must have been called before this.
#[cfg(feature = "socks")]
pub fn build_socks5_proxy(self) -> Result<Client<Socks5Connector>, OxiHttpError> {
let proxy_uri = match self.proxy.as_ref() {
Some(ProxyKind::Socks5(u)) => u.clone(),
Some(ProxyKind::HttpConnect(_)) => {
return Err(OxiHttpError::ConnectionPool(
"HTTP CONNECT proxy configured; use build_proxy() instead".into(),
))
}
None => {
return Err(OxiHttpError::ConnectionPool(
"no proxy configured; call with_socks5_proxy() first".into(),
))
}
};
let connector = Socks5Connector::new(proxy_uri, self.connect_timeout);
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(dur) = self.pool_idle_timeout {
builder.pool_idle_timeout(dur);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
let inner = builder.build(connector);
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
Ok(Client {
inner,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar.clone(),
#[cfg(feature = "tls")]
tls_rebuild: None,
})
}
/// Build a TLS-capable `Client` that tunnels HTTPS through an HTTP CONNECT proxy.
///
/// `with_http_proxy()` must have been called before this.
///
/// The resulting client handles both `http://` and `https://` URIs.
#[cfg(feature = "tls")]
pub fn build_proxy_https(
self,
) -> Result<Client<OxiHttpsConnector<ProxyConnector>>, OxiHttpError> {
let proxy_uri = match self.proxy.as_ref() {
Some(ProxyKind::HttpConnect(u)) => u.clone(),
#[cfg(feature = "socks")]
Some(ProxyKind::Socks5(_)) => {
return Err(OxiHttpError::ConnectionPool(
"SOCKS5 proxy configured; use build_socks5_proxy_https() instead".into(),
))
}
None => {
return Err(OxiHttpError::ConnectionPool(
"no proxy configured; call with_http_proxy() first".into(),
))
}
};
let tls_connector = self.build_tls_connector_inner()?;
let http_connector = ProxyConnector::new(proxy_uri, self.connect_timeout);
let https_connector = OxiHttpsConnector::new(http_connector, tls_connector);
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(dur) = self.pool_idle_timeout {
builder.pool_idle_timeout(dur);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
let inner = builder.build(https_connector);
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
Ok(Client {
inner,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar.clone(),
#[cfg(feature = "tls")]
tls_rebuild: None,
})
}
/// Build a TLS-capable `Client` that tunnels HTTPS through a SOCKS5 proxy.
///
/// `with_socks5_proxy()` must have been called before this.
///
/// The resulting client handles both `http://` and `https://` URIs.
#[cfg(all(feature = "tls", feature = "socks"))]
pub fn build_socks5_proxy_https(
self,
) -> Result<Client<OxiHttpsConnector<Socks5Connector>>, OxiHttpError> {
let proxy_uri = match self.proxy.as_ref() {
Some(ProxyKind::Socks5(u)) => u.clone(),
Some(ProxyKind::HttpConnect(_)) => {
return Err(OxiHttpError::ConnectionPool(
"HTTP CONNECT proxy configured; use build_proxy_https() instead".into(),
))
}
None => {
return Err(OxiHttpError::ConnectionPool(
"no proxy configured; call with_socks5_proxy() first".into(),
))
}
};
let tls_connector = self.build_tls_connector_inner()?;
let socks_connector = Socks5Connector::new(proxy_uri, self.connect_timeout);
let https_connector = OxiHttpsConnector::new(socks_connector, tls_connector);
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(dur) = self.pool_idle_timeout {
builder.pool_idle_timeout(dur);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
let inner = builder.build(https_connector);
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
Ok(Client {
inner,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar.clone(),
#[cfg(feature = "tls")]
tls_rebuild: None,
})
}
// --- TLS-specific builder methods (feature-gated) -----------------------
/// Enable TLS with the Mozilla CA bundle (webpki-roots) as the trust store.
///
/// Required to be called (or `with_webpki_roots` / `with_trusted_cert_der`)
/// before `build_https()` returns a usable client for real HTTPS endpoints.
#[cfg(feature = "tls")]
pub fn with_tls(mut self) -> Self {
self.use_webpki_roots = true;
self
}
/// Trust the Mozilla CA bundle (webpki-roots).
#[cfg(feature = "tls")]
pub fn with_webpki_roots(mut self) -> Self {
self.use_webpki_roots = true;
self
}
/// Trust an additional DER-encoded CA certificate.
///
/// Can be called multiple times to add several trusted roots.
#[cfg(feature = "tls")]
pub fn with_trusted_cert_der(mut self, der: Vec<u8>) -> Self {
self.trusted_certs_der.push(der);
self
}
/// Set ALPN protocols to advertise (e.g. `&["h2", "http/1.1"]`).
#[cfg(feature = "tls")]
pub fn with_alpn(mut self, protocols: &[&str]) -> Self {
self.alpn = protocols.iter().map(|s| s.to_string()).collect();
self
}
/// **DANGER**: Accept any server certificate, including self-signed ones.
///
/// For testing only — disables all certificate verification.
#[cfg(feature = "tls")]
pub fn with_danger_accept_invalid_certs(mut self) -> Self {
self.accept_invalid_certs = true;
self
}
/// Write TLS session secrets to `path` in NSS key-log format (SSLKEYLOGFILE).
///
/// The file is created/appended to on every TLS handshake. Use this for
/// decrypting captured HTTPS traffic in Wireshark or mitmproxy during
/// development. **Do not enable in production.**
#[cfg(feature = "tls")]
pub fn with_key_log_file(mut self, path: std::path::PathBuf) -> Self {
self.key_log_path = Some(path);
self
}
/// Enable TLS 1.3 0-RTT early data (HTTP fast-open) for subsequent requests.
///
/// Only effective if a prior connection stored a session ticket and the server
/// indicated `max_early_data_size > 0`. Safe to call on any builder; ignored
/// if 0-RTT is not available.
///
/// # Security
/// Early data is NOT protected against replay attacks — see RFC 8446 §8.
/// Only enable for idempotent requests (GET, HEAD, etc.).
#[cfg(feature = "tls")]
pub fn with_early_data(mut self) -> Self {
self.early_data = true;
self
}
/// **DANGER**: Enable or disable certificate verification via a boolean flag.
///
/// This is an alias for [`with_danger_accept_invalid_certs`](Self::with_danger_accept_invalid_certs)
/// that accepts an explicit `bool` parameter, matching the API style of
/// reqwest's `danger_accept_invalid_certs`.
///
/// # Security
///
/// Passing `true` disables **all** TLS certificate verification, making HTTPS
/// connections trivially vulnerable to man-in-the-middle attacks. Only use
/// in tests or isolated local environments.
///
/// # Example
///
/// ```rust,no_run
/// # fn example() -> Result<(), oxihttp_core::OxiHttpError> {
/// use oxihttp_client::Client;
///
/// // Mirror reqwest's API: danger_accept_invalid_certs(true)
/// let client = Client::builder()
/// .danger_accept_invalid_certs(true)
/// .build_https()?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "tls")]
pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
self.accept_invalid_certs = accept;
self
}
/// Inject a custom server-certificate verifier.
///
/// The supplied `verifier` replaces the default trust-store verification
/// for all TLS connections made by the built client. When a custom verifier
/// is present it takes precedence over:
/// - `with_trusted_cert_der` / `with_webpki_roots`
/// - `danger_accept_invalid_certs` / `with_danger_accept_invalid_certs`
///
/// This enables certificate pinning, custom CA hierarchies, or completely
/// bespoke verification logic without forking the library.
///
/// # Security
///
/// The security of the resulting client depends entirely on the supplied
/// verifier. Injecting a verifier that accepts any certificate (e.g.
/// [`crate::tls::DangerousNoVerification`]) disables authentication;
/// see that type's documentation for details.
///
/// # Example
///
/// ```rust,no_run
/// # fn example() -> Result<(), oxihttp_core::OxiHttpError> {
/// use std::sync::Arc;
/// use oxihttp_client::{Client, tls::DangerousNoVerification};
///
/// // Inject the "accept-everything" verifier (for tests only).
/// let provider = oxitls::pure_provider();
/// let verifier = Arc::new(DangerousNoVerification::new(provider));
///
/// let client = Client::builder()
/// .with_custom_cert_verifier(verifier)
/// .build_https()?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "tls")]
pub fn with_custom_cert_verifier(
mut self,
verifier: std::sync::Arc<dyn rustls::client::danger::ServerCertVerifier>,
) -> Self {
self.custom_cert_verifier = Some(verifier);
self
}
// --- internal TLS connector helper (feature-gated) ----------------------
/// Choose the appropriate TLS connector builder depending on whether a
/// custom verifier has been injected. This keeps the dispatch in one place
/// so all `build_*` variants stay consistent.
#[cfg(feature = "tls")]
fn build_tls_connector_inner(&self) -> Result<tokio_rustls::TlsConnector, OxiHttpError> {
if let Some(ref verifier) = self.custom_cert_verifier {
tls::build_tls_connector_with_verifier(
std::sync::Arc::clone(verifier),
&self.alpn,
self.early_data,
)
} else {
tls::build_tls_connector(
&self.trusted_certs_der,
&self.alpn,
self.accept_invalid_certs,
self.use_webpki_roots,
self.key_log_path.clone(),
self.early_data,
)
}
}
// --- build() — plain HTTP -----------------------------------------------
/// Build a plain HTTP `Client` (no TLS).
pub fn build(self) -> Result<Client, OxiHttpError> {
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(dur) = self.pool_idle_timeout {
builder.pool_idle_timeout(dur);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
// Use an explicit HttpConnector so TCP options can be applied.
let mut http = HttpConnector::new();
http.enforce_http(false);
if let Some(dur) = self.connect_timeout {
http.set_connect_timeout(Some(dur));
}
if let Some(nodelay) = self.tcp_nodelay {
http.set_nodelay(nodelay);
}
if let Some(ka) = self.tcp_keepalive {
http.set_keepalive(Some(ka));
}
let inner = builder.build(http);
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
Ok(Client {
inner,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar.clone(),
#[cfg(feature = "tls")]
tls_rebuild: None,
})
}
// --- build_https() — TLS-capable client ---------------------------------
/// Build a TLS-capable `HttpsClient` (alias for `Client<OxiHttpsConnector<HttpConnector>>`).
///
/// The resulting client handles both `http://` and `https://` URIs.
#[cfg(feature = "tls")]
pub fn build_https(self) -> Result<super::HttpsClient, OxiHttpError> {
let connector = self.build_tls_connector_inner()?;
let mut http = HttpConnector::new();
// Allow the inner connector to accept https:// URIs so that the
// OxiHttpsConnector can extract the host/port and then upgrade the TCP
// stream to TLS. Without this flag, HttpConnector rejects any URI
// whose scheme is not "http".
http.enforce_http(false);
if let Some(dur) = self.connect_timeout {
http.set_connect_timeout(Some(dur));
}
if let Some(nodelay) = self.tcp_nodelay {
http.set_nodelay(nodelay);
}
if let Some(ka) = self.tcp_keepalive {
http.set_keepalive(Some(ka));
}
let https_connector = OxiHttpsConnector::new(http, connector);
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(dur) = self.pool_idle_timeout {
builder.pool_idle_timeout(dur);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
let inner = builder.build(https_connector);
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
let tls_rebuild = Arc::new(TlsRebuildConfig {
trusted_certs_der: self.trusted_certs_der.clone(),
alpn: self.alpn.clone(),
accept_invalid_certs: self.accept_invalid_certs,
use_webpki_roots: self.use_webpki_roots,
key_log_path: self.key_log_path.clone(),
early_data: self.early_data,
connect_timeout: self.connect_timeout,
tcp_nodelay: self.tcp_nodelay,
tcp_keepalive: self.tcp_keepalive,
http2_settings: self.http2_settings.clone(),
pool_max_idle_per_host: self.pool_max_idle_per_host,
pool_idle_timeout: self.pool_idle_timeout,
custom_cert_verifier: self.custom_cert_verifier,
});
Ok(Client {
inner,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar.clone(),
tls_rebuild: Some(tls_rebuild),
})
}
// --- build_with_resolver / build_https_with_resolver ---------------------
/// Build a plain HTTP `Client` using a custom DNS resolver.
///
/// [`ClientBuilder::with_resolver`] must be called before this.
pub fn build_with_resolver(self) -> Result<super::ResolverClient, OxiHttpError> {
let resolver = self.resolver.ok_or_else(|| {
OxiHttpError::Dns("with_resolver must be called before build_with_resolver".into())
})?;
let mut http = HttpConnector::new_with_resolver(BoxResolver(resolver));
http.enforce_http(false);
if let Some(dur) = self.connect_timeout {
http.set_connect_timeout(Some(dur));
}
if let Some(nodelay) = self.tcp_nodelay {
http.set_nodelay(nodelay);
}
if let Some(ka) = self.tcp_keepalive {
http.set_keepalive(Some(ka));
}
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(d) = self.pool_idle_timeout {
builder.pool_idle_timeout(d);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
Ok(Client {
inner: builder.build(http),
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar,
#[cfg(feature = "tls")]
tls_rebuild: None,
})
}
/// Build a TLS-capable `Client` using a custom DNS resolver.
///
/// [`ClientBuilder::with_resolver`] must be called before this.
/// The resulting client handles both `http://` and `https://` URIs.
#[cfg(feature = "tls")]
pub fn build_https_with_resolver(self) -> Result<super::ResolverHttpsClient, OxiHttpError> {
// Build the TLS connector first (while `self` is still whole), then
// extract the resolver field. Reversing the order would cause a
// partial-move conflict because `ok_or_else` consumes `self.resolver`.
let tls_connector = self.build_tls_connector_inner()?;
let resolver = self.resolver.ok_or_else(|| {
OxiHttpError::Dns(
"with_resolver must be called before build_https_with_resolver".into(),
)
})?;
let mut http = HttpConnector::new_with_resolver(BoxResolver(resolver));
http.enforce_http(false);
if let Some(dur) = self.connect_timeout {
http.set_connect_timeout(Some(dur));
}
if let Some(nodelay) = self.tcp_nodelay {
http.set_nodelay(nodelay);
}
if let Some(ka) = self.tcp_keepalive {
http.set_keepalive(Some(ka));
}
let connector = crate::connector::OxiHttpsConnector::new(http, tls_connector);
let mut builder = HyperClient::builder(TokioExecutor::new());
if let Some(n) = self.pool_max_idle_per_host {
builder.pool_max_idle_per_host(n);
}
if let Some(d) = self.pool_idle_timeout {
builder.pool_idle_timeout(d);
}
if let Some(ref h2) = self.http2_settings {
apply_http2_settings(&mut builder, h2);
}
let mut default_headers = self.default_headers;
if let Some(agent) = &self.user_agent {
if let Ok(val) = HeaderValue::from_str(agent) {
default_headers.insert(http::header::USER_AGENT, val);
}
}
Ok(Client {
inner: builder.build(connector),
connect_timeout: self.connect_timeout,
read_timeout: self.read_timeout,
redirect_policy: self.redirect_policy,
retry_policy: self.retry_policy,
default_headers,
decompression: self.decompression,
middleware: self.middleware,
cookie_jar: self.cookie_jar,
#[cfg(feature = "tls")]
tls_rebuild: None,
})
}
}
impl Default for ClientBuilder {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for ClientBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClientBuilder")
.field("pool_max_idle_per_host", &self.pool_max_idle_per_host)
.field("pool_idle_timeout", &self.pool_idle_timeout)
.field("connect_timeout", &self.connect_timeout)
.field("read_timeout", &self.read_timeout)
.field("redirect_policy", &self.redirect_policy)
.field("retry_policy", &self.retry_policy)
.field("decompression", &self.decompression)
.field("user_agent", &self.user_agent)
.field("tcp_nodelay", &self.tcp_nodelay)
.field("tcp_keepalive", &self.tcp_keepalive)
.finish_non_exhaustive()
}
}