Debian Codegraph @

src/client.rs

raw symbols ◀ ▶ SCIP
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 /// ```no_run
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 #[ignore]
414 fn test_http_get_ok() -> Result<()> {
415 let client = Client::new();
416 let response = client.request(
417 Request::builder()
418 .uri("http://example.com")
419 .body(())
420 .unwrap(),
421 )?;
422 assert_eq!(response.status(), StatusCode::OK);
423 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
424 let body = response.into_body().to_string()?;
425 assert!(body.contains("<html"));
426 Ok(())
427 }
428
429 #[test]
•430 #[ignore]
431 fn test_http_get_ok_with_user_agent_and_timeout() -> Result<()> {
432 let client = Client::new()
433 .with_user_agent("OxHTTP/1.0")
434 .unwrap()
435 .with_global_timeout(Duration::from_secs(5));
436 let response = client.request(
437 Request::builder()
438 .uri("http://example.com")
439 .body(())
440 .unwrap(),
441 )?;
442 assert_eq!(response.status(), StatusCode::OK);
443 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
444 Ok(())
445 }
446
447 #[test]
•448 #[ignore]
449 fn test_http_get_ok_explicit_port() -> Result<()> {
450 let client = Client::new();
451 let response = client.request(
452 Request::builder()
453 .uri("http://example.com:80")
454 .body(())
455 .unwrap(),
456 )?;
457 assert_eq!(response.status(), StatusCode::OK);
458 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
459 Ok(())
460 }
461
462 #[test]
•463 #[ignore]
464 fn test_http_wrong_port() {
465 let client = Client::new();
466 assert!(client
467 .request(
468 Request::builder()
469 .uri("http://example.com:22")
470 .body(())
471 .unwrap(),
472 )
473 .is_err());
474 }
475
476 #[cfg(any(
477 feature = "rustls-aws-lc-webpki",
478 feature = "rustls-ring-webpki",
479 feature = "rustls-aws-lc-native",
480 feature = "rustls-ring-native",
481 feature = "native-tls"
482 ))]
483 #[test]
•484 #[ignore]
485 fn test_https_get_ok() -> Result<()> {
486 let client = Client::new();
487 let response = client.request(
488 Request::builder()
489 .uri("https://example.com")
490 .body(())
491 .unwrap(),
492 )?;
493 assert_eq!(response.status(), StatusCode::OK);
494 assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html");
495 Ok(())
496 }
497
498 #[cfg(not(any(
499 feature = "rustls-aws-lc-webpki",
500 feature = "rustls-ring-webpki",
501 feature = "rustls-aws-lc-native",
502 feature = "rustls-ring-native",
503 feature = "native-tls"
504 )))]
505 #[test]
•506 #[ignore]
507 fn test_https_get_err() {
508 let client = Client::new();
509 assert!(client
510 .request(
511 Request::builder()
512 .uri("https://example.com")
513 .body(())
514 .unwrap()
515 )
516 .is_err());
517 }
518
519 #[test]
•520 #[ignore]
521 fn test_http_get_not_found() -> Result<()> {
522 let client = Client::new();
523 let response = client.request(
524 Request::builder()
525 .uri("http://example.com/not_existing")
526 .body(())
527 .unwrap(),
528 )?;
529 assert!(matches!(
530 response.status(),
531 StatusCode::NOT_FOUND | StatusCode::INTERNAL_SERVER_ERROR
532 ));
533 Ok(())
534 }
535
536 #[test]
537 fn test_file_get_error() {
538 let client = Client::new();
539 assert!(client
540 .request(
541 Request::builder()
542 .uri("file://example.com/not_existing")
543 .body(())
544 .unwrap(),
545 )
546 .is_err());
547 }
548
549 #[cfg(any(
550 feature = "rustls-aws-lc-webpki",
551 feature = "rustls-ring-webpki",
552 feature = "rustls-aws-lc-native",
553 feature = "rustls-ring-native",
554 feature = "native-tls"
555 ))]
556 #[test]
•557 #[ignore]
558 fn test_redirection() -> Result<()> {
559 let client = Client::new()
560 .with_redirection_limit(5)
561 .with_user_agent("OxHTTP/1.0")
562 .unwrap();
563 let response = client.request(
564 Request::builder()
565 .uri("http://wikipedia.org")
566 .body(())
567 .unwrap(),
568 )?;
569 assert_eq!(response.status(), StatusCode::OK);
570 Ok(())
571 }
572 }