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
use urly::Url;
use crate::connect::{self, Connect as TcpConnect, Connector as TcpConnector};
use crate::service::{Identity, IntoService, Middleware, Pipeline, Service, Stack, apply_fn};
use crate::{SharedCfg, error::Error, io::IoBoxed};
use super::connector::Connector;
use super::error::{ClientError, ConnectError};
use super::pool::ConnectionPool;
use super::service::{ServiceRequest, ServiceResponse};
use super::{Client, ClientConfig, Connect, ConnectorPipeline, sender::Sender};
#[cfg(feature = "openssl")]
use tls_openssl::ssl::SslConnector as OpensslConnector;
#[cfg(feature = "rustls")]
use tls_rustls::ClientConfig as RustlsClientConfig;
/// An HTTP client builder.
///
/// This type configures connectors and middleware before constructing a
/// [`Client`].
#[derive(Debug)]
pub struct ClientBuilder<M = Identity> {
middleware: M,
svc: ConnectorPipeline,
secure_svc: Option<ConnectorPipeline>,
}
impl Default for ClientBuilder<Identity> {
fn default() -> Self {
Self::new()
}
}
impl ClientBuilder<Identity> {
#[must_use]
/// Creates a client builder with default connectors.
///
/// # TLS defaults
///
/// With the `openssl` feature enabled (it takes precedence over `rustls`),
/// HTTPS connections verify the peer certificate against OpenSSL's default
/// trust store (the system roots) and check that it matches the request
/// host. With only the `rustls` feature, peers are verified against the
/// bundled `webpki-roots`. Without either feature, HTTPS is unavailable.
///
/// To trust private roots, or to skip verification for testing, pass your
/// own configuration to `openssl()`, `rustls()` or
/// [`secure_connector`](Self::secure_connector).
pub fn new() -> Self {
let svc = ConnectorPipeline::new(
apply_fn(TcpConnector::new(), async move |msg: Connect, svc| {
svc.call(TcpConnect::new(msg.uri).set_addr(msg.addr)).await
})
.map(IoBoxed::from)
.map_err(|e| e.map(ConnectError::from)),
);
let builder = ClientBuilder {
svc,
secure_svc: None,
middleware: Identity,
};
#[cfg(feature = "openssl")]
{
use tls_openssl::ssl::SslMethod;
let mut ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
let _ = ssl
.set_alpn_protos(b"\x02h2\x08http/1.1")
.map_err(|e| log::error!("Cannot set ALPN protocol: {e:?}"));
builder.openssl(ssl.build())
}
#[cfg(all(not(feature = "openssl"), feature = "rustls"))]
{
use tls_rustls::RootCertStore;
let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
let cert_store = webpki_roots::TLS_SERVER_ROOTS
.iter()
.cloned()
.collect::<RootCertStore>();
let mut config = RustlsClientConfig::builder()
.with_root_certificates(cert_store)
.with_no_client_auth();
config.alpn_protocols = protos;
builder.rustls(config)
}
#[cfg(not(any(feature = "openssl", feature = "rustls")))]
{
builder
}
}
}
impl<M> ClientBuilder<M> {
#[must_use]
#[cfg(feature = "openssl")]
/// Uses an OpenSSL connector for secure connections.
///
/// The connector's verification settings are used as given. Hostname
/// verification follows the connector's `configure()` defaults, so it is
/// enabled unless `set_verify(SslVerifyMode::NONE)` disables verification
/// altogether.
pub fn openssl(self, config: OpensslConnector) -> Self {
use crate::connect::openssl::SslConnector;
self.secure_connector(SslConnector::new(config))
}
#[must_use]
#[cfg(feature = "rustls")]
/// Uses a rustls connector for secure connections.
pub fn rustls(self, config: RustlsClientConfig) -> Self {
use crate::connect::rustls::TlsConnector;
self.secure_connector(TlsConnector::new(config))
}
#[must_use]
/// Uses a custom connector for unsecured connections.
pub fn connector<T>(mut self, f: impl IntoService<T, SharedCfg, TcpConnect<Url>>) -> Self
where
T: Service<SharedCfg, TcpConnect<Url>, Error = Error<connect::ConnectError>> + 'static,
IoBoxed: From<T::Res>,
{
self.svc = ConnectorPipeline::new(
apply_fn(f.into_service(), async move |msg: Connect, svc| {
svc.call(TcpConnect::new(msg.uri).set_addr(msg.addr)).await
})
.map(IoBoxed::from)
.map_err(|e| e.map(ConnectError::from)),
);
self
}
#[must_use]
/// Uses a custom connector for secure connections.
pub fn secure_connector<T>(mut self, f: impl IntoService<T, SharedCfg, TcpConnect<Url>>) -> Self
where
T: Service<SharedCfg, TcpConnect<Url>, Error = Error<connect::ConnectError>> + 'static,
IoBoxed: From<T::Res>,
{
self.secure_svc = Some(ConnectorPipeline::new(
apply_fn(f.into_service(), async move |msg: Connect, svc| {
svc.call(TcpConnect::new(msg.uri).set_addr(msg.addr)).await
})
.map(IoBoxed::from)
.map_err(|e| e.map(ConnectError::from)),
));
self
}
#[must_use]
/// Applies middleware to the client request service.
///
/// Middleware can inspect or modify every request and response.
///
/// ```rust
/// use ntex::client::{Client, ServiceRequest};
/// use ntex::service::{fn_layer, cfg::SharedCfg};
///
/// #[ntex::main]
/// async fn main() {
/// let client = Client::builder()
/// .middleware(fn_layer(
/// async move |mut req: ServiceRequest, svc| {
/// println!("{:?}", req.head().uri);
/// svc.call(req).await
/// }
/// ))
/// .build(SharedCfg::default());
/// }
/// ```
pub fn middleware<U>(self, mw: U) -> ClientBuilder<Stack<U, M>> {
ClientBuilder {
middleware: Stack::new(mw, self.middleware),
svc: self.svc,
secure_svc: self.secure_svc,
}
}
/// Builds the [`Client`] using the supplied shared configuration.
///
/// Add a [`ClientConfig`] to [`SharedCfg`] to customize client behavior:
///
/// ```rust
/// use ntex::SharedCfg;
/// use ntex::client::{Client, ClientConfig};
/// use ntex::time::Millis;
///
/// #[ntex::main]
/// async fn main() {
/// let cfg = SharedCfg::new("HTTP-CLIENT")
/// .add(
/// ClientConfig::new()
/// .set_response_timeout(Millis(10_000))
/// .set_response_payload_limit(1024 * 1024),
/// )
/// .build();
///
/// let _client = Client::builder().build(cfg);
/// }
/// ```
pub fn build(self, cfg: impl Into<SharedCfg>) -> Client
where
M: Middleware<Sender, SharedCfg>,
M::Service: Service<SharedCfg, ServiceRequest, Res = ServiceResponse, Error = Error<ClientError>>
+ 'static,
{
let cfg = cfg.into();
let config = cfg.get::<ClientConfig>();
let connector = Connector {
tcp_pool: ConnectionPool::new(self.svc, config.clone()),
ssl_pool: self
.secure_svc
.map(|svc| ConnectionPool::new(svc, config.clone())),
};
let svc = self.middleware.create(&cfg, Sender::new(connector));
Client::with_service(config, Pipeline::new(cfg, svc))
}
}