Debian Codegraph @

src/client.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #![allow(unreachable_code, clippy::needless_return)]
2
3 use crate::io::{decode_response, encode_request, BUFFER_CAPACITY};
4 use crate::model::header::{
5 InvalidHeaderValue, ACCEPT_ENCODING, CONNECTION, LOCATION, RANGE, USER_AGENT,
6 };
7 use crate::model::uri::Scheme;
8 use crate::model::{Body, HeaderValue, Method, Request, Response, StatusCode, Uri};
9 use crate::utils::{invalid_data_error, invalid_input_error};
10 use http::Version;
11 #[cfg(feature = "native-tls")]
12 use native_tls::TlsConnector;
13 #[cfg(all(
14 any(feature = "rustls-aws-lc-webpki", feature = "rustls-ring-webpki"),
15 not(feature = "native-tls"),
16 not(feature = "rustls-aws-lc-native"),
17 not(feature = "rustls-ring-native"),
18 ))]
19 use rustls::RootCertStore;
20 #[cfg(all(
21 any(
22 feature = "rustls-aws-lc-webpki",
23 feature = "rustls-ring-webpki",
24 feature = "rustls-aws-lc-native",
25 feature = "rustls-ring-native"
26 ),
27 not(feature = "native-tls")
28 ))]
29 use rustls::{ClientConfig, ClientConnection, StreamOwned};
30 #[cfg(all(
31 any(
32 feature = "rustls-aws-lc-webpki",
33 feature = "rustls-ring-webpki",
34 feature = "rustls-aws-lc-native",
35 feature = "rustls-ring-native"
36 ),
37 not(feature = "native-tls")
38 ))]
39 use rustls_pki_types::ServerName;
40 #[cfg(all(
41 any(feature = "rustls-aws-lc-native", feature = "rustls-ring-native"),
42 not(feature = "native-tls")
43 ))]
44 use rustls_platform_verifier::ConfigVerifierExt;
45 use std::io::{BufReader, BufWriter, Error, ErrorKind, Result};
46 use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
47 #[cfg(all(
48 any(
49 feature = "rustls-aws-lc-webpki",
50 feature = "rustls-ring-webpki",
51 feature = "rustls-aws-lc-native",
52 feature = "rustls-ring-native"
53 ),
54 not(feature = "native-tls")
55 ))]
56 use std::sync::Arc;
57 #[cfg(any(
58 feature = "rustls-aws-lc-webpki",
59 feature = "rustls-ring-webpki",
60 feature = "rustls-aws-lc-native",
61 feature = "rustls-ring-native",
62 feature = "native-tls"
63 ))]
64 use std::sync::OnceLock;
65 use std::time::Duration;
66 use url::Url;
67 #[cfg(all(
68 any(feature = "rustls-aws-lc-webpki", feature = "rustls-ring-webpki"),
69 not(feature = "native-tls"),
70 not(feature = "rustls-aws-lc-native"),
71 not(feature = "rustls-ring-native"),
72 ))]
73 use webpki_roots::TLS_SERVER_ROOTS;
74
75 /// An HTTP client.
76 ///
77 /// It aims at following the basic concepts of the [Web Fetch standard](https://fetch.spec.whatwg.org/) without the bits specific to web browsers (context, CORS...).
78 ///
79 /// HTTPS is supported behind the disabled by default features.
80 /// To enable it you need to enable one of the following features:
81 ///
82 /// * `native-tls` to use the current system native implementation.
83 /// * `rustls-ring-webpki` to use [Rustls](https://github.com/rustls/rustls) with
84 /// the [Ring](https://github.com/briansmith/ring) cryptographic library and
85 /// the [Common CA Database](https://www.ccadb.org/).
86 /// * `rustls-ring-native` to use [Rustls](https://github.com/rustls/rustls) with
87 /// the [Ring](https://github.com/briansmith/ring) cryptographic library and the host certificates.
88 /// * `rustls-aws-lc-webpki` to use [Rustls](https://github.com/rustls/rustls) with
89 /// the [AWS Libcrypto for Rust](https://github.com/aws/aws-lc-rs) and
90 /// the [Common CA Database](https://www.ccadb.org/).
91 /// * `rustls-aws-lc-native` to use [Rustls](https://github.com/rustls/rustls) with
92 /// the [AWS Libcrypto for Rust](https://github.com/aws/aws-lc-rs) and the host certificates.
93 ///
94 /// If the `flate2` feature is enabled, the client will automatically decode `gzip` and `deflate` content-encodings.
95 ///
96 /// The client does not follow redirections by default. Use [`Client::with_redirection_limit`] to set a limit to the number of consecutive redirections the server should follow.
97 ///
98 /// Missing: HSTS support, authentication and keep alive.
99 ///
100 /// ```
101 /// use http::header::CONTENT_TYPE;
102 /// use oxhttp::model::{Body, HeaderName, Method, Request, StatusCode};
103 /// use oxhttp::Client;
104 /// use std::io::Read;
105 ///
106 /// let client = Client::new();
107 /// let response = client.request(
108 /// Request::builder()
109 /// .uri("http://example.com")
110 /// .body(Body::empty())?,
111 /// )?;
112 /// assert_eq!(response.status(), StatusCode::OK);
113 /// assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
114 /// let body = response.into_body().to_string()?;
115 /// # Result::<_,Box<dyn std::error::Error>>::Ok(())
116 /// ```
117 #[derive(Default)]
118 pub struct Client {
119 timeout: Option<Duration>,
120 user_agent: Option<HeaderValue>,
121 redirection_limit: usize,
122 }
123
124 impl Client {
125 #[inline]
126 pub fn new() -> Self {
127 Self::default()
128 }
129
130 /// Sets the global timeout value (applies to both read, write and connection).
131 #[inline]
132 pub fn with_global_timeout(mut self, timeout: Duration) -> Self {
133 self.timeout = Some(timeout);
134 self
135 }
136
137 /// Sets the default value for the [`User-Agent`](https://httpwg.org/http-core/draft-ietf-httpbis-semantics-latest.html#field.user-agent) header.
138 #[inline]
139 pub fn with_user_agent(
140 mut self,
141 user_agent: impl Into<String>,
142 ) -> std::result::Result<Self, InvalidHeaderValue> {
143 self.user_agent = Some(HeaderValue::try_from(user_agent.into())?);
144 Ok(self)
145 }
146
147 /// Sets the number of time a redirection should be followed.
148 /// By default the redirections are not followed (limit = 0).
149 #[inline]
150 pub fn with_redirection_limit(mut self, limit: usize) -> Self {
151 self.redirection_limit = limit;
152 self
153 }
154
155 pub fn request(&self, request: Request<impl Into<Body>>) -> Result<Response<Body>> {
156 let mut request = request.map(Into::into);
157 // Loops the number of allowed redirections + 1
158 for _ in 0..(self.redirection_limit + 1) {
159 let previous_method = request.method().clone();
160 let response = self.single_request(&mut request)?;
161 let Some(location) = response.headers().get(LOCATION) else {
162 return Ok(response);
163 };
164 let mut request_builder = Request::builder();
165 request_builder = request_builder.method(match response.status() {
166 StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER => {
167 if previous_method == Method::HEAD {
168 Method::HEAD
169 } else {
170 Method::GET
171 }
172 }
173 StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT
174 if previous_method.is_safe() =>
175 {
176 previous_method
177 }
178 _ => return Ok(response),
179 });
180 let location = location.to_str().map_err(invalid_data_error)?;
181 request_builder = request_builder.uri(join_urls(request.uri(), location)?);
182 for (header_name, header_value) in request.headers() {
183 request_builder = request_builder.header(header_name, header_value);
184 }
185 request = request_builder.body(Body::empty()).map_err(|e| {
186 invalid_input_error(format!(
187 "Failure when trying to build the redirected request: {e}"
188 ))
189 })?;
190 }
191 Err(Error::other(format!(
192 "The server requested too many redirects ({}). The latest redirection target is {}",
193 self.redirection_limit + 1,
194 request.uri()
195 )))
196 }
197
198 fn single_request(&self, request: &mut Request<Body>) -> Result<Response<Body>> {
199 // Additional headers
200 {
201 let request_version = request.version();
202 let headers = request.headers_mut();
203 if request_version >= Version::HTTP_11 {
204 headers.insert(CONNECTION, HeaderValue::from_static("close"));
205 }
206 if let Some(user_agent) = &self.user_agent {
207 headers
208 .entry(USER_AGENT)
209 .or_insert_with(|| user_agent.clone());
210 }
211 if cfg!(feature = "flate2") && !headers.contains_key(RANGE) {
212 headers
213 .entry(ACCEPT_ENCODING)
214 .or_insert_with(|| HeaderValue::from_static("gzip,deflate"));
215 }
216 }
217
218 #[cfg(any(
219 feature = "rustls-aws-lc-webpki",
220 feature = "rustls-ring-webpki",
221 feature = "rustls-aws-lc-native",
222 feature = "rustls-ring-native",
223 feature = "native-tls"
224 ))]
225 let host = request
226 .uri()
227 .host()
228 .ok_or_else(|| invalid_input_error("No host provided"))?;
229
230 let scheme = request.uri().scheme().ok_or_else(|| {
231 invalid_input_error(format!("A URI scheme must be set, found {}", request.uri()))
232 })?;
233
234 if *scheme == Scheme::HTTP {
235 let addresses = get_and_validate_socket_addresses(request.uri(), 80)?;
236 let stream = self.connect(&addresses)?;
237 let stream =
238 encode_request(request, BufWriter::with_capacity(BUFFER_CAPACITY, stream))?
239 .into_inner()
240 .map_err(|e| e.into_error())?;
241 return decode_response(BufReader::with_capacity(BUFFER_CAPACITY, stream));
242 }
243
244 #[cfg(feature = "native-tls")]
245 if *scheme == Scheme::HTTPS {
246 static TLS_CONNECTOR: OnceLock<TlsConnector> = OnceLock::new();
247
248 let addresses = get_and_validate_socket_addresses(request.uri(), 443)?;
249 let stream = self.connect(&addresses)?;
250 let stream = TLS_CONNECTOR
251 .get_or_init(|| match TlsConnector::new() {
252 Ok(connector) => connector,
253 Err(e) => panic!("Error while loading TLS configuration: {}", e), // TODO: use get_or_try_init
254 })
255 .connect(host, stream)
256 .map_err(Error::other)?;
257 let stream =
258 encode_request(request, BufWriter::with_capacity(BUFFER_CAPACITY, stream))?
259 .into_inner()
260 .map_err(|e| e.into_error())?;
261 return decode_response(BufReader::with_capacity(BUFFER_CAPACITY, stream));
262 }
263 #[cfg(all(
264 any(
265 feature = "rustls-aws-lc-webpki",
266 feature = "rustls-ring-webpki",
267 feature = "rustls-aws-lc-native",
268 feature = "rustls-ring-native"
269 ),
270 not(feature = "native-tls")
271 ))]
272 if *scheme == Scheme::HTTPS {
273 static RUSTLS_CONFIG: OnceLock<Arc<ClientConfig>> = OnceLock::new();
274
275 // TODO: use get_or_try_init
276 #[cfg(any(feature = "rustls-aws-lc-native", feature = "rustls-ring-native"))]
277 let rustls_config = RUSTLS_CONFIG.get_or_init(|| {
278 Arc::new(
279 ClientConfig::with_platform_verifier()
280 .expect("Failed to load the certificate needed to build TLS configuration"),
281 )
282 });
283 #[cfg(all(
284 any(feature = "rustls-aws-lc-webpki", feature = "rustls-ring-webpki"),
285 not(feature = "rustls-aws-lc-native"),
286 not(feature = "rustls-ring-native")
287 ))]
288 let rustls_config = RUSTLS_CONFIG.get_or_init(|| {
289 Arc::new(
290 ClientConfig::builder()
291 .with_root_certificates(RootCertStore {
292 roots: TLS_SERVER_ROOTS.to_vec(),
293 })
294 .with_no_client_auth(),
295 )
296 });
297 let addresses = get_and_validate_socket_addresses(request.uri(), 443)?;
298 let dns_name = ServerName::try_from(host)
299 .map_err(invalid_input_error)?
300 .to_owned();
301 let connection =
302 ClientConnection::new(Arc::clone(rustls_config), dns_name).map_err(Error::other)?;
303 let stream = StreamOwned::new(connection, self.connect(&addresses)?);
304 let stream =
305 encode_request(request, BufWriter::with_capacity(BUFFER_CAPACITY, stream))?
306 .into_inner()
307 .map_err(|e| e.into_error())?;
308 return decode_response(BufReader::with_capacity(BUFFER_CAPACITY, stream));
309 }
310
311 #[cfg(not(any(
312 feature = "rustls-aws-lc-webpki",
313 feature = "rustls-ring-webpki",
314 feature = "rustls-aws-lc-native",
315 feature = "rustls-ring-native",
316 feature = "native-tls"
317 )))]
318 if *scheme == Scheme::HTTPS {
319 return Err(invalid_input_error("HTTPS is not supported by the client. You should enable the `native-tls` or `rustls` feature of the `oxhttp` crate"));
320 }
321
322 Err(invalid_input_error(format!(
323 "Not supported URL scheme: {scheme}"
324 )))
325 }
326
327 fn connect(&self, addresses: &[SocketAddr]) -> Result<TcpStream> {
328 let stream = if let Some(timeout) = self.timeout {
329 Self::connect_timeout(addresses, timeout)
330 } else {
331 TcpStream::connect(addresses)
332 }?;
333 stream.set_read_timeout(self.timeout)?;
334 stream.set_write_timeout(self.timeout)?;
335 stream.set_nodelay(true)?;
336 Ok(stream)
337 }
338
339 fn connect_timeout(addresses: &[SocketAddr], timeout: Duration) -> Result<TcpStream> {
340 let mut error = Error::new(
341 ErrorKind::InvalidInput,
342 "Not able to resolve the provide addresses",
343 );
344 for address in addresses {
345 match TcpStream::connect_timeout(address, timeout) {
346 Ok(stream) => return Ok(stream),
347 Err(e) => error = e,
348 }
349 }
350 Err(error)
351 }
352 }
353
354 // Bad ports https://fetch.spec.whatwg.org/#bad-port
355 // Should be sorted
356 const BAD_PORTS: [u16; 80] = [
357 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102,
358 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
359 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
360 995, 1719, 1720, 1723, 2049, 3659, 4045, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,
361 6697, 10080,
362 ];
363
364 fn get_and_validate_socket_addresses(uri: &Uri, default_port: u16) -> Result<Vec<SocketAddr>> {
365 let host = uri
366 .host()
367 .ok_or_else(|| invalid_input_error(format!("No host in request URL {uri}")))?;
368 let port = uri.port_u16().unwrap_or(default_port);
369 let addresses = (host, port).to_socket_addrs()?.collect::<Vec<_>>();
370 for address in &addresses {
371 if BAD_PORTS.binary_search(&address.port()).is_ok() {
372 return Err(invalid_input_error(format!(
373 "The port {} is not allowed for HTTP(S) because it is dedicated to an other use",
374 address.port()
375 )));
376 }
377 }
378 Ok(addresses)
379 }
380
381 fn join_urls(base: &Uri, relative: &str) -> Result<Uri> {
382 Uri::try_from(
383 Url::parse(&base.to_string())
384 .map_err(|e| {
385 Error::new(
386 ErrorKind::InvalidInput,
387 format!("Invalid base URL '{base}': {e}"),
388 )
389 })?
390 .join(relative)
391 .map_err(|e| {
392 Error::new(
393 ErrorKind::InvalidData,
394 format!("Invalid location header URL '{relative}': {e}"),
395 )
396 })?
397 .to_string(),
398 )
399 .map_err(|e| {
400 Error::new(
401 ErrorKind::InvalidData,
402 format!("Invalid location header URL '{relative}': {e}"),
403 )
404 })
405 }
406
407 #[cfg(test)]
408 mod tests {
409 use super::*;
410 use crate::model::header::CONTENT_TYPE;
411
412 #[test]
413 fn test_http_get_ok() -> Result<()> {
414 let client = Client::new();
415 let response = client.request(
416 Request::builder()
417 .uri("http://example.com")
418 .body(())
419 .unwrap(),
420 )?;
421 assert_eq!(response.status(), StatusCode::OK);
422 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
423 let body = response.into_body().to_string()?;
424 assert!(body.contains("<html"));
425 Ok(())
426 }
427
428 #[test]
429 fn test_http_get_ok_with_user_agent_and_timeout() -> Result<()> {
430 let client = Client::new()
431 .with_user_agent("OxHTTP/1.0")
432 .unwrap()
433 .with_global_timeout(Duration::from_secs(5));
434 let response = client.request(
435 Request::builder()
436 .uri("http://example.com")
437 .body(())
438 .unwrap(),
439 )?;
440 assert_eq!(response.status(), StatusCode::OK);
441 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
442 Ok(())
443 }
444
445 #[test]
446 fn test_http_get_ok_explicit_port() -> Result<()> {
447 let client = Client::new();
448 let response = client.request(
449 Request::builder()
450 .uri("http://example.com:80")
451 .body(())
452 .unwrap(),
453 )?;
454 assert_eq!(response.status(), StatusCode::OK);
455 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
456 Ok(())
457 }
458
459 #[test]
460 fn test_http_wrong_port() {
461 let client = Client::new();
462 assert!(client
463 .request(
464 Request::builder()
465 .uri("http://example.com:22")
466 .body(())
467 .unwrap(),
468 )
469 .is_err());
470 }
471
472 #[cfg(any(
473 feature = "rustls-aws-lc-webpki",
474 feature = "rustls-ring-webpki",
475 feature = "rustls-aws-lc-native",
476 feature = "rustls-ring-native",
477 feature = "native-tls"
478 ))]
479 #[test]
480 fn test_https_get_ok() -> Result<()> {
481 let client = Client::new();
482 let response = client.request(
483 Request::builder()
484 .uri("https://example.com")
485 .body(())
486 .unwrap(),
487 )?;
488 assert_eq!(response.status(), StatusCode::OK);
489 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
490 Ok(())
491 }
492
493 #[cfg(not(any(
494 feature = "rustls-aws-lc-webpki",
495 feature = "rustls-ring-webpki",
496 feature = "rustls-aws-lc-native",
497 feature = "rustls-ring-native",
498 feature = "native-tls"
499 )))]
500 #[test]
501 fn test_https_get_err() {
502 let client = Client::new();
503 assert!(client
504 .request(
505 Request::builder()
506 .uri("https://example.com")
507 .body(())
508 .unwrap()
509 )
510 .is_err());
511 }
512
513 #[test]
514 fn test_http_get_not_found() -> Result<()> {
515 let client = Client::new();
516 let response = client.request(
517 Request::builder()
518 .uri("http://example.com/not_existing")
519 .body(())
520 .unwrap(),
521 )?;
522 assert!(matches!(
523 response.status(),
524 StatusCode::NOT_FOUND | StatusCode::INTERNAL_SERVER_ERROR
525 ));
526 Ok(())
527 }
528
529 #[test]
530 fn test_file_get_error() {
531 let client = Client::new();
532 assert!(client
533 .request(
534 Request::builder()
535 .uri("file://example.com/not_existing")
536 .body(())
537 .unwrap(),
538 )
539 .is_err());
540 }
541
542 #[cfg(any(
543 feature = "rustls-aws-lc-webpki",
544 feature = "rustls-ring-webpki",
545 feature = "rustls-aws-lc-native",
546 feature = "rustls-ring-native",
547 feature = "native-tls"
548 ))]
549 #[test]
550 fn test_redirection() -> Result<()> {
551 let client = Client::new()
552 .with_redirection_limit(5)
553 .with_user_agent("OxHTTP/1.0")
554 .unwrap();
555 let response = client.request(
556 Request::builder()
557 .uri("http://wikipedia.org")
558 .body(())
559 .unwrap(),
560 )?;
561 assert_eq!(response.status(), StatusCode::OK);
562 Ok(())
563 }
564 }