ureq/
lib.rs

1//!<div align="center">
2//!  <!-- Version -->
3//!  <a href="https://crates.io/crates/ureq">
4//!    <img src="https://img.shields.io/crates/v/ureq.svg?style=flat-square"
5//!    alt="Crates.io version" />
6//!  </a>
7//!  <!-- Docs -->
8//!  <a href="https://docs.rs/ureq">
9//!    <img src="https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square"
10//!      alt="docs.rs docs" />
11//!  </a>
12//!  <!-- Downloads -->
13//!  <a href="https://crates.io/crates/ureq">
14//!    <img src="https://img.shields.io/crates/d/ureq.svg?style=flat-square"
15//!      alt="Crates.io downloads" />
16//!  </a>
17//!</div>
18//!
19//! A simple, safe HTTP client.
20//!
21//! Ureq's first priority is being easy for you to use. It's great for
22//! anyone who wants a low-overhead HTTP client that just gets the job done. Works
23//! very well with HTTP APIs. Its features include cookies, JSON, HTTP proxies,
24//! HTTPS, charset decoding, and is based on the API of the `http` crate.
25//!
26//! Ureq is in pure Rust for safety and ease of understanding. It avoids using
27//! `unsafe` directly. It uses blocking I/O instead of async I/O, because that keeps
28//! the API simple and keeps dependencies to a minimum. For TLS, ureq uses
29//! rustls or native-tls.
30//!
31//! See the [changelog] for details of recent releases.
32//!
33//! [changelog]: https://github.com/algesten/ureq/blob/main/CHANGELOG.md
34//!
35//! # Usage
36//!
37//! In its simplest form, ureq looks like this:
38//!
39//! ```rust
40//! let body: String = ureq::get("http://example.com")
41//!     .header("Example-Header", "header value")
42//!     .call()?
43//!     .body_mut()
44//!     .read_to_string()?;
45//! # Ok::<(), ureq::Error>(())
46//! ```
47//!
48//! For more involved tasks, you'll want to create an [`Agent`]. An Agent
49//! holds a connection pool for reuse, and a cookie store if you use the
50//! **cookies** feature. An Agent can be cheaply cloned due to internal
51//! [`Arc`] and all clones of an Agent share state among each other. Creating
52//! an Agent also allows setting options like the TLS configuration.
53//!
54//! ```rust
55//! # fn no_run() -> Result<(), ureq::Error> {
56//! use ureq::Agent;
57//! use std::time::Duration;
58//!
59//! let mut config = Agent::config_builder()
60//!     .timeout_global(Some(Duration::from_secs(5)))
61//!     .build();
62//!
63//! let agent: Agent = config.into();
64//!
65//! let body: String = agent.get("http://example.com/page")
66//!     .call()?
67//!     .body_mut()
68//!     .read_to_string()?;
69//!
70//! // Reuses the connection from previous request.
71//! let response: String = agent.put("http://example.com/upload")
72//!     .header("Authorization", "example-token")
73//!     .send("some body data")?
74//!     .body_mut()
75//!     .read_to_string()?;
76//! # Ok(())}
77//! ```
78//!
79//! ## JSON
80//!
81//! Ureq supports sending and receiving json, if you enable the **json** feature:
82//!
83//! ```rust
84//! # #[cfg(feature = "json")]
85//! # fn no_run() -> Result<(), ureq::Error> {
86//! use serde::{Serialize, Deserialize};
87//!
88//! #[derive(Serialize)]
89//! struct MySendBody {
90//!    thing: String,
91//! }
92//!
93//! #[derive(Deserialize)]
94//! struct MyRecvBody {
95//!    other: String,
96//! }
97//!
98//! let send_body = MySendBody { thing: "yo".to_string() };
99//!
100//! // Requires the `json` feature enabled.
101//! let recv_body = ureq::post("http://example.com/post/ingest")
102//!     .header("X-My-Header", "Secret")
103//!     .send_json(&send_body)?
104//!     .body_mut()
105//!     .read_json::<MyRecvBody>()?;
106//! # Ok(())}
107//! ```
108//!
109//! ## Error handling
110//!
111//! ureq returns errors via `Result<T, ureq::Error>`. That includes I/O errors,
112//! protocol errors. By default, also HTTP status code errors (when the
113//! server responded 4xx or 5xx) results in [`Error`].
114//!
115//! This behavior can be turned off via [`http_status_as_error()`]
116//!
117//! ```rust
118//! use ureq::Error;
119//!
120//! # fn no_run() -> Result<(), ureq::Error> {
121//! match ureq::get("http://mypage.example.com/").call() {
122//!     Ok(response) => { /* it worked */},
123//!     Err(Error::StatusCode(code)) => {
124//!         /* the server returned an unexpected status
125//!            code (such as 400, 500 etc) */
126//!     }
127//!     Err(_) => { /* some kind of io/transport/etc error */ }
128//! }
129//! # Ok(())}
130//! ```
131//!
132//! # Features
133//!
134//! To enable a minimal dependency tree, some features are off by default.
135//! You can control them when including ureq as a dependency.
136//!
137//! `ureq = { version = "3", features = ["socks-proxy", "charset"] }`
138//!
139//! The default enabled features are: **rustls** and **gzip**.
140//!
141//! * **rustls** enables the rustls TLS implementation. This is the default for the the crate level
142//!   convenience calls (`ureq::get` etc). It currently uses `ring` as the TLS provider.
143//! * **native-tls** enables the native tls backend for TLS. Due to the risk of diamond dependencies
144//!   accidentally switching on an unwanted TLS implementation, `native-tls` is never picked up as
145//!   a default or used by the crate level convenience calls (`ureq::get` etc) – it must be configured
146//!   on the agent
147//! * **platform-verifier** enables verifying the server certificates using a method native to the
148//!   platform ureq is executing on. See [rustls-platform-verifier] crate
149//! * **socks-proxy** enables proxy config using the `socks4://`, `socks4a://`, `socks5://`
150//!   and `socks://` (equal to `socks5://`) prefix
151//! * **cookies** enables cookies
152//! * **gzip** enables requests of gzip-compressed responses and decompresses them
153//! * **brotli** enables requests brotli-compressed responses and decompresses them
154//! * **charset** enables interpreting the charset part of the Content-Type header
155//!   (e.g.  `Content-Type: text/plain; charset=iso-8859-1`). Without this, the
156//!   library defaults to Rust's built in `utf-8`
157//! * **json** enables JSON sending and receiving via serde_json
158//!
159//! ### Unstable
160//!
161//! These features are unstable and might change in a minor version.
162//!
163//! * **rustls-no-provider** Enables rustls, but does not enable any [`CryptoProvider`] such as `ring`.
164//!   Providers other than the default (currently `ring`) are never picked up from feature flags alone.
165//!   It must be configured on the agent.
166//!
167//! * **vendored** compiles and statically links to a copy of non-Rust vendors (e.g. OpenSSL from `native-tls`)
168//!
169//! # TLS (https)
170//!
171//! ## rustls
172//!
173//! By default, ureq uses [`rustls` crate] with the `ring` cryptographic provider.
174//! As of Sep 2024, the `ring` provider has a higher chance of compiling successfully. If the user
175//! installs another process [default provider], that choice is respected.
176//!
177//! ureq does not guarantee to default to ring indefinitely. `rustls` as a feature flag will always
178//! work, but the specific crypto backend might change in a minor version.
179//!
180//! ```
181//! # #[cfg(feature = "rustls")]
182//! # {
183//! // This uses rustls
184//! ureq::get("https://www.google.com/").call().unwrap();
185//! # } Ok::<_, ureq::Error>(())
186//! ```
187//!
188//! ### rustls without ring
189//!
190//! ureq never changes TLS backend from feature flags alone. It is possible to compile ureq
191//! without ring, but it requires specific feature flags and configuring the [`Agent`].
192//!
193//! Since rustls is not semver 1.x, this requires non-semver-guaranteed API. I.e. ureq might
194//! change this behavior without a major version bump.
195//!
196//! Read more at [`TlsConfigBuilder::unversioned_rustls_crypto_provider`][crate::tls::TlsConfigBuilder::unversioned_rustls_crypto_provider].
197//!
198//! ## native-tls
199//!
200//! As an alternative, ureq ships with [`native-tls`] as a TLS provider. This must be
201//! enabled using the **native-tls** feature. Due to the risk of diamond dependencies
202//! accidentally switching on an unwanted TLS implementation, `native-tls` is never picked
203//! up as a default or used by the crate level convenience calls (`ureq::get` etc) – it
204//! must be configured on the agent.
205//!
206//! ```
207//! # #[cfg(feature = "native-tls")]
208//! # {
209//! use ureq::config::Config;
210//! use ureq::tls::{TlsConfig, TlsProvider};
211//!
212//! let mut config = Config::builder()
213//!     .tls_config(
214//!         TlsConfig::builder()
215//!             // requires the native-tls feature
216//!             .provider(TlsProvider::NativeTls)
217//!             .build()
218//!     )
219//!     .build();
220//!
221//! let agent = config.new_agent();
222//!
223//! agent.get("https://www.google.com/").call().unwrap();
224//! # } Ok::<_, ureq::Error>(())
225//! ```
226//!
227//! ## Root certificates
228//!
229//! ### webpki-roots
230//!
231//! By default, ureq uses Mozilla's root certificates via the [webpki-roots] crate. This is a static
232//! bundle of root certificates that do not update automatically. It also circumvents whatever root
233//! certificates are installed on the host running ureq, which might be a good or a bad thing depending
234//! on your perspective. There is also no mechanism for [SCT], [CRL]s or other revocations.
235//! To maintain a "fresh" list of root certs, you need to bump the ureq dependency from time to time.
236//!
237//! The main reason for chosing this as the default is to minimize the number of dependencies. More
238//! details about this decision can be found at [PR 818].
239//!
240//! If your use case for ureq is talking to a limited number of servers with high trust, the
241//! default setting is likely sufficient. If you use ureq with a high number of servers, or servers
242//! you don't trust, we recommend using the platform verifier (see below).
243//!
244//! ### platform-verifier
245//!
246//! The [rustls-platform-verifier] crate provides access to natively checking the certificate via your OS.
247//! To use this verifier, you need to enable it using feature flag **platform-verifier** as well as
248//! configure an agent to use it.
249//!
250//! ```
251//! # #[cfg(all(feature = "rustls", feature="platform-verifier"))]
252//! # {
253//! use ureq::Agent;
254//! use ureq::tls::{TlsConfig, RootCerts};
255//!
256//! let agent = Agent::config_builder()
257//!     .tls_config(
258//!         TlsConfig::builder()
259//!             .root_certs(RootCerts::PlatformVerifier)
260//!             .build()
261//!     )
262//!     .build()
263//!     .new_agent();
264//!
265//! let response = agent.get("https://httpbin.org/get").call()?;
266//! # } Ok::<_, ureq::Error>(())
267//! ```
268//!
269//! Setting `RootCerts::PlatformVerifier` together with `TlsProvider::NativeTls` means
270//! also native-tls will use the OS roots instead of [webpki-roots] crate. Whether that
271//! results in a config that has CRLs and revocations is up to whatever native-tls links to.
272//!
273//! # JSON
274//!
275//! By enabling the **json** feature, the library supports serde json.
276//!
277//! This is enabled by default.
278//!
279//! * [`request.send_json()`] send body as json.
280//! * [`body.read_json()`] transform response to json.
281//!
282//! # Sending body data
283//!
284//! HTTP/1.1 has two ways of transfering body data. Either of a known size with
285//! the `Content-Length` HTTP header, or unknown size with the
286//! `Transfer-Encoding: chunked` header. ureq supports both and will use the
287//! appropriate method depending on which body is being sent.
288//!
289//! ureq has a [`AsSendBody`] trait that is implemented for many well known types
290//! of data that we might want to send. The request body can thus be anything
291//! from a `String` to a `File`, see below.
292//!
293//! ## Content-Length
294//!
295//! The library will send a `Content-Length` header on requests with bodies of
296//! known size, in other words, if the body to send is one of:
297//!
298//! * `&[u8]`
299//! * `&[u8; N]`
300//! * `&str`
301//! * `String`
302//! * `&String`
303//! * `Vec<u8>`
304//! * `&Vec<u8>)`
305//! * [`SendBody::from_json()`] (implicitly via [`request.send_json()`])
306//!
307//! ## Transfer-Encoding: chunked
308//!
309//! ureq will send a `Transfer-Encoding: chunked` header on requests where the body
310//! is of unknown size. The body is automatically converted to an [`std::io::Read`]
311//! when the type is one of:
312//!
313//! * `File`
314//! * `&File`
315//! * `TcpStream`
316//! * `&TcpStream`
317//! * `Stdin`
318//! * `UnixStream` (not on windows)
319//!
320//! ### From readers
321//!
322//! The chunked method also applies for bodies constructed via:
323//!
324//! * [`SendBody::from_reader()`]
325//! * [`SendBody::from_owned_reader()`]
326//!
327//! ## Proxying a response body
328//!
329//! As a special case, when ureq sends a [`Body`] from a previous http call, the
330//! use of `Content-Length` or `chunked` depends on situation. For input such as
331//! gzip decoding (**gzip** feature) or charset transformation (**charset** feature),
332//! the output body might not match the input, which means ureq is forced to use
333//! the `chunked` method.
334//!
335//! * `Response<Body>`
336//!
337//! ## Sending form data
338//!
339//! [`request.send_form()`] provides a way to send `application/x-www-form-urlencoded`
340//! encoded data. The key/values provided will be URL encoded.
341//!
342//! ## Overriding
343//!
344//! If you set your own Content-Length or Transfer-Encoding header before
345//! sending the body, ureq will respect that header by not overriding it,
346//! and by encoding the body or not, as indicated by the headers you set.
347//!
348//! ```
349//! let resp = ureq::put("https://httpbin.org/put")
350//!     .header("Transfer-Encoding", "chunked")
351//!     .send("Hello world")?;
352//! # Ok::<_, ureq::Error>(())
353//! ```
354//!
355//! # Character encoding
356//!
357//! By enabling the **charset** feature, the library supports receiving other
358//! character sets than `utf-8`.
359//!
360//! For [`Body::read_to_string()`] we read the header like:
361//!
362//! `Content-Type: text/plain; charset=iso-8859-1`
363//!
364//! and if it contains a charset specification, we try to decode the body using that
365//! encoding. In the absence of, or failing to interpret the charset, we fall back on `utf-8`.
366//!
367//! Currently ureq does not provide a way to encode when sending request bodies.
368//!
369//! ## Lossy utf-8
370//!
371//! When reading text bodies (with a `Content-Type` starting `text/` as in `text/plain`,
372//! `text/html`, etc), ureq can ensure the body is possible to read as a `String` also if
373//! it contains characters that are not valid for utf-8. Invalid characters are replaced
374//! with a question mark `?` (NOT the utf-8 replacement character).
375//!
376//! For [`Body::read_to_string()`] this is turned on by default, but it can be disabled
377//! and conversely for [`Body::as_reader()`] it is not enabled, but can be.
378//!
379//! To precisely configure the behavior use [`Body::with_config()`].
380//!
381//! # Proxying
382//!
383//! ureq supports two kinds of proxies,  [`HTTP`] ([`CONNECT`]), [`SOCKS4`]/[`SOCKS5`],
384//! the former is always available while the latter must be enabled using the feature
385//! **socks-proxy**.
386//!
387//! Proxies settings are configured on an [`Agent`]. All request sent through the agent will be proxied.
388//!
389//! ## Example using HTTP
390//!
391//! ```rust
392//! use ureq::{Agent, Proxy};
393//! # fn no_run() -> std::result::Result<(), ureq::Error> {
394//! // Configure an http connect proxy.
395//! let proxy = Proxy::new("http://user:password@cool.proxy:9090")?;
396//! let agent: Agent = Agent::config_builder()
397//!     .proxy(Some(proxy))
398//!     .build()
399//!     .into();
400//!
401//! // This is proxied.
402//! let resp = agent.get("http://cool.server").call()?;
403//! # Ok(())}
404//! # fn main() {}
405//! ```
406//!
407//! ## Example using SOCKS5
408//!
409//! ```rust
410//! use ureq::{Agent, Proxy};
411//! # #[cfg(feature = "socks-proxy")]
412//! # fn no_run() -> std::result::Result<(), ureq::Error> {
413//! // Configure a SOCKS proxy.
414//! let proxy = Proxy::new("socks5://user:password@cool.proxy:9090")?;
415//! let agent: Agent = Agent::config_builder()
416//!     .proxy(Some(proxy))
417//!     .build()
418//!     .into();
419//!
420//! // This is proxied.
421//! let resp = agent.get("http://cool.server").call()?;
422//! # Ok(())}
423//! ```
424//!
425//! # Log levels
426//!
427//! ureq uses the log crate. These are the definitions of the log levels, however we
428//! do not guarantee anything for dependencies such as `http` and `rustls`.
429//!
430//! * `ERROR` - nothing
431//! * `WARN` - if we detect a user configuration problem.
432//! * `INFO` - nothing
433//! * `DEBUG` - uri, state changes, transport, resolver and selected request/response headers
434//! * `TRACE` - wire level debug. NOT REDACTED!
435//!
436//! The request/response headers on DEBUG levels are allow-listed to only include headers that
437//! are considered safe. The code has the [allow list](https://github.com/algesten/ureq/blob/81127cfc38516903330dc1b9c618122372f8dc29/src/util.rs#L184-L198).
438//!
439//! # Versioning
440//!
441//! ## Semver and `unversioned`
442//!
443//! ureq follows semver. From ureq 3.x we strive to have a much closer adherence to semver than 2.x.
444//! The main mistake in 2.x was to re-export crates that were not yet semver 1.0. In ureq 3.x TLS and
445//! cookie configuration is shimmed using our own types.
446//!
447//! ureq 3.x is trying out two new traits that had no equivalent in 2.x, [`Transport`] and [`Resolver`].
448//! These allow the user write their own bespoke transports and (DNS name) resolver. The API:s for
449//! these parts are not yet solidified. They live under the [`unversioned`] module, and do not
450//! follow semver. See module doc for more info.
451//!
452//! ## Breaking changes in dependencies
453//!
454//! ureq relies on non-semver 1.x crates such as `rustls` and `native-tls`. Some scenarios, such
455//! as configuring `rustls` to not use `ring`, a user of ureq might need to interact with these
456//! crates directly instead of going via ureq's provided API.
457//!
458//! Such changes can break when ureq updates dependencies. This is not considered a breaking change
459//! for ureq and will not be reflected by a major version bump.
460//!
461//! We strive to mark ureq's API with the word "unversioned" to identify places where this risk arises.
462//!
463//! ## Minimum Supported Rust Version (MSRV)
464//!
465//! From time to time we will need to update our minimum supported Rust version (MSRV). This is not
466//! something we do lightly; our ambition is to be as conservative with MSRV as possible.
467//!
468//! * For some dependencies, we will opt for pinning the version of the dep instead
469//!   of bumping our MSRV.
470//! * For important dependencies, like the TLS libraries, we cannot hold back our MSRV if they change.
471//! * We do not consider MSRV changes to be breaking for the purposes of semver.
472//! * We will not make MSRV changes in patch releases.
473//! * MSRV changes will get their own minor release, and not be co-mingled with other changes.
474//!
475//! [`HTTP`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Proxy_servers_and_tunneling#http_tunneling
476//! [`CONNECT`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT
477//! [`SOCKS4`]: https://en.wikipedia.org/wiki/SOCKS#SOCKS4
478//! [`SOCKS5`]: https://en.wikipedia.org/wiki/SOCKS#SOCKS5
479//! [`rustls` crate]: https://crates.io/crates/rustls
480//! [default provider]: https://docs.rs/rustls/latest/rustls/crypto/struct.CryptoProvider.html#method.install_default
481//! [`native-tls`]: https://crates.io/crates/native-tls
482//! [rustls-platform-verifier]: https://crates.io/crates/rustls-platform-verifier
483//! [webpki-roots]: https://crates.io/crates/webpki-roots
484//! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
485//! [`Agent`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Agent.html
486//! [`Error`]: https://docs.rs/ureq/3.0.0-rc4/ureq/enum.Error.html
487//! [`http_status_as_error()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/config/struct.ConfigBuilder.html#method.http_status_as_error
488//! [SCT]: https://en.wikipedia.org/wiki/Certificate_Transparency
489//! [CRL]: https://en.wikipedia.org/wiki/Certificate_revocation_list
490//! [PR818]: https://github.com/algesten/ureq/pull/818
491//! [`request.send_json()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.RequestBuilder.html#method.send_json
492//! [`body.read_json()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.read_json
493//! [`AsSendBody`]: https://docs.rs/ureq/3.0.0-rc4/ureq/trait.AsSendBody.html
494//! [`SendBody::from_json()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.SendBody.html#method.from_json
495//! [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
496//! [`SendBody::from_reader()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.SendBody.html#method.from_reader
497//! [`SendBody::from_owned_reader()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.SendBody.html#method.from_owned_reader
498//! [`Body`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html
499//! [`request.send_form()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.RequestBuilder.html#method.send_form
500//! [`Body::read_to_string()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.read_to_string
501//! [`Body::as_reader()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.as_reader
502//! [`Body::with_config()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.with_config
503//! [`Transport`]: https://docs.rs/ureq/3.0.0-rc4/ureq/unversioned/transport/trait.Transport.html
504//! [`Resolver`]: https://docs.rs/ureq/3.0.0-rc4/ureq/unversioned/resolver/trait.Resolver.html
505//! [`unversioned`]: https://docs.rs/ureq/3.0.0-rc4/ureq/unversioned/index.html
506//! [`CryptoProvider`]: https://docs.rs/rustls/latest/rustls/crypto/struct.CryptoProvider.html
507
508#![forbid(unsafe_code)]
509#![warn(clippy::all)]
510#![deny(missing_docs)]
511// I don't think elided lifetimes help in understanding the code.
512#![allow(clippy::needless_lifetimes)]
513
514#[macro_use]
515extern crate log;
516
517use std::convert::TryFrom;
518
519/// Re-exported http-crate.
520pub use ureq_proto::http;
521
522pub use body::{Body, BodyBuilder, BodyReader, BodyWithConfig};
523use http::Method;
524use http::{Request, Response, Uri};
525pub use proxy::{Proxy, ProxyBuilder, ProxyProtocol};
526pub use request::RequestBuilder;
527use request::{WithBody, WithoutBody};
528pub use request_ext::RequestExt;
529pub use response::ResponseExt;
530pub use send_body::AsSendBody;
531
532mod agent;
533mod body;
534pub mod config;
535mod connect;
536mod error;
537mod pool;
538mod proxy;
539mod query;
540mod request;
541mod response;
542mod run;
543mod send_body;
544mod timings;
545mod util;
546
547pub mod unversioned;
548use unversioned::resolver;
549use unversioned::transport;
550
551pub mod middleware;
552
553#[cfg(feature = "_tls")]
554pub mod tls;
555
556#[cfg(feature = "cookies")]
557mod cookies;
558mod request_ext;
559
560#[cfg(feature = "cookies")]
561pub use cookies::{Cookie, CookieJar};
562
563pub use agent::Agent;
564pub use error::Error;
565pub use send_body::SendBody;
566pub use timings::Timeout;
567
568/// Typestate variables.
569pub mod typestate {
570    pub use super::request::WithBody;
571    pub use super::request::WithoutBody;
572
573    pub use super::config::typestate::AgentScope;
574    pub use super::config::typestate::HttpCrateScope;
575    pub use super::config::typestate::RequestScope;
576}
577
578/// Run a [`http::Request<impl AsSendBody>`].
579pub fn run(request: Request<impl AsSendBody>) -> Result<Response<Body>, Error> {
580    let agent = Agent::new_with_defaults();
581    agent.run(request)
582}
583
584/// A new [Agent] with default configuration
585///
586/// Agents are used to hold configuration and keep state between requests.
587pub fn agent() -> Agent {
588    Agent::new_with_defaults()
589}
590
591/// Make a GET request.
592///
593/// Run on a use-once [`Agent`].
594#[must_use]
595pub fn get<T>(uri: T) -> RequestBuilder<WithoutBody>
596where
597    Uri: TryFrom<T>,
598    <Uri as TryFrom<T>>::Error: Into<http::Error>,
599{
600    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::GET, uri)
601}
602
603/// Make a POST request.
604///
605/// Run on a use-once [`Agent`].
606#[must_use]
607pub fn post<T>(uri: T) -> RequestBuilder<WithBody>
608where
609    Uri: TryFrom<T>,
610    <Uri as TryFrom<T>>::Error: Into<http::Error>,
611{
612    RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::POST, uri)
613}
614
615/// Make a PUT request.
616///
617/// Run on a use-once [`Agent`].
618#[must_use]
619pub fn put<T>(uri: T) -> RequestBuilder<WithBody>
620where
621    Uri: TryFrom<T>,
622    <Uri as TryFrom<T>>::Error: Into<http::Error>,
623{
624    RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::PUT, uri)
625}
626
627/// Make a DELETE request.
628///
629/// Run on a use-once [`Agent`].
630#[must_use]
631pub fn delete<T>(uri: T) -> RequestBuilder<WithoutBody>
632where
633    Uri: TryFrom<T>,
634    <Uri as TryFrom<T>>::Error: Into<http::Error>,
635{
636    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::DELETE, uri)
637}
638
639/// Make a HEAD request.
640///
641/// Run on a use-once [`Agent`].
642#[must_use]
643pub fn head<T>(uri: T) -> RequestBuilder<WithoutBody>
644where
645    Uri: TryFrom<T>,
646    <Uri as TryFrom<T>>::Error: Into<http::Error>,
647{
648    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::HEAD, uri)
649}
650
651/// Make an OPTIONS request.
652///
653/// Run on a use-once [`Agent`].
654#[must_use]
655pub fn options<T>(uri: T) -> RequestBuilder<WithoutBody>
656where
657    Uri: TryFrom<T>,
658    <Uri as TryFrom<T>>::Error: Into<http::Error>,
659{
660    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::OPTIONS, uri)
661}
662
663/// Make a CONNECT request.
664///
665/// Run on a use-once [`Agent`].
666#[must_use]
667pub fn connect<T>(uri: T) -> RequestBuilder<WithoutBody>
668where
669    Uri: TryFrom<T>,
670    <Uri as TryFrom<T>>::Error: Into<http::Error>,
671{
672    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::CONNECT, uri)
673}
674
675/// Make a PATCH request.
676///
677/// Run on a use-once [`Agent`].
678#[must_use]
679pub fn patch<T>(uri: T) -> RequestBuilder<WithBody>
680where
681    Uri: TryFrom<T>,
682    <Uri as TryFrom<T>>::Error: Into<http::Error>,
683{
684    RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::PATCH, uri)
685}
686
687/// Make a TRACE request.
688///
689/// Run on a use-once [`Agent`].
690#[must_use]
691pub fn trace<T>(uri: T) -> RequestBuilder<WithoutBody>
692where
693    Uri: TryFrom<T>,
694    <Uri as TryFrom<T>>::Error: Into<http::Error>,
695{
696    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::TRACE, uri)
697}
698
699#[cfg(test)]
700pub(crate) mod test {
701    use std::{io, sync::OnceLock};
702
703    use assert_no_alloc::AllocDisabler;
704    use config::{Config, ConfigBuilder};
705    use typestate::AgentScope;
706
707    use super::*;
708
709    #[global_allocator]
710    // Some tests checks that we are not allocating
711    static A: AllocDisabler = AllocDisabler;
712
713    pub fn init_test_log() {
714        static INIT_LOG: OnceLock<()> = OnceLock::new();
715        INIT_LOG.get_or_init(env_logger::init);
716    }
717
718    #[test]
719    fn connect_http_google() {
720        init_test_log();
721        let agent = Agent::new_with_defaults();
722
723        let res = agent.get("http://www.google.com/").call().unwrap();
724        assert_eq!(
725            "text/html;charset=ISO-8859-1",
726            res.headers()
727                .get("content-type")
728                .unwrap()
729                .to_str()
730                .unwrap()
731                .replace("; ", ";")
732        );
733        assert_eq!(res.body().mime_type(), Some("text/html"));
734    }
735
736    #[test]
737    #[cfg(feature = "rustls")]
738    fn connect_https_google_rustls() {
739        init_test_log();
740        use config::Config;
741
742        use crate::tls::{TlsConfig, TlsProvider};
743
744        let agent: Agent = Config::builder()
745            .tls_config(TlsConfig::builder().provider(TlsProvider::Rustls).build())
746            .build()
747            .into();
748
749        let res = agent.get("https://www.google.com/").call().unwrap();
750        assert_eq!(
751            "text/html;charset=ISO-8859-1",
752            res.headers()
753                .get("content-type")
754                .unwrap()
755                .to_str()
756                .unwrap()
757                .replace("; ", ";")
758        );
759        assert_eq!(res.body().mime_type(), Some("text/html"));
760    }
761
762    #[test]
763    #[cfg(feature = "native-tls")]
764    fn connect_https_google_native_tls_simple() {
765        init_test_log();
766        use config::Config;
767
768        use crate::tls::{TlsConfig, TlsProvider};
769
770        let agent: Agent = Config::builder()
771            .tls_config(
772                TlsConfig::builder()
773                    .provider(TlsProvider::NativeTls)
774                    .build(),
775            )
776            .build()
777            .into();
778
779        let mut res = agent.get("https://www.google.com/").call().unwrap();
780
781        assert_eq!(
782            "text/html;charset=ISO-8859-1",
783            res.headers()
784                .get("content-type")
785                .unwrap()
786                .to_str()
787                .unwrap()
788                .replace("; ", ";")
789        );
790        assert_eq!(res.body().mime_type(), Some("text/html"));
791        res.body_mut().read_to_string().unwrap();
792    }
793
794    #[test]
795    #[cfg(feature = "rustls")]
796    fn connect_https_google_rustls_webpki() {
797        init_test_log();
798        use crate::tls::{RootCerts, TlsConfig, TlsProvider};
799        use config::Config;
800
801        let agent: Agent = Config::builder()
802            .tls_config(
803                TlsConfig::builder()
804                    .provider(TlsProvider::Rustls)
805                    .root_certs(RootCerts::WebPki)
806                    .build(),
807            )
808            .build()
809            .into();
810
811        agent.get("https://www.google.com/").call().unwrap();
812    }
813
814    #[test]
815    #[cfg(feature = "native-tls")]
816    fn connect_https_google_native_tls_webpki() {
817        init_test_log();
818        use crate::tls::{RootCerts, TlsConfig, TlsProvider};
819        use config::Config;
820
821        let agent: Agent = Config::builder()
822            .tls_config(
823                TlsConfig::builder()
824                    .provider(TlsProvider::NativeTls)
825                    .root_certs(RootCerts::WebPki)
826                    .build(),
827            )
828            .build()
829            .into();
830
831        agent.get("https://www.google.com/").call().unwrap();
832    }
833
834    #[test]
835    #[cfg(feature = "rustls")]
836    fn connect_https_google_noverif() {
837        init_test_log();
838        use crate::tls::{TlsConfig, TlsProvider};
839
840        let agent: Agent = Config::builder()
841            .tls_config(
842                TlsConfig::builder()
843                    .provider(TlsProvider::Rustls)
844                    .disable_verification(true)
845                    .build(),
846            )
847            .build()
848            .into();
849
850        let res = agent.get("https://www.google.com/").call().unwrap();
851        assert_eq!(
852            "text/html;charset=ISO-8859-1",
853            res.headers()
854                .get("content-type")
855                .unwrap()
856                .to_str()
857                .unwrap()
858                .replace("; ", ";")
859        );
860        assert_eq!(res.body().mime_type(), Some("text/html"));
861    }
862
863    #[test]
864    fn simple_put_content_len() {
865        init_test_log();
866        let mut res = put("http://httpbin.org/put").send(&[0_u8; 100]).unwrap();
867        res.body_mut().read_to_string().unwrap();
868    }
869
870    #[test]
871    fn simple_put_chunked() {
872        init_test_log();
873        let mut res = put("http://httpbin.org/put")
874            // override default behavior
875            .header("transfer-encoding", "chunked")
876            .send(&[0_u8; 100])
877            .unwrap();
878        res.body_mut().read_to_string().unwrap();
879    }
880
881    #[test]
882    fn simple_get() {
883        init_test_log();
884        let mut res = get("http://httpbin.org/get").call().unwrap();
885        res.body_mut().read_to_string().unwrap();
886    }
887
888    #[test]
889    fn simple_head() {
890        init_test_log();
891        let mut res = head("http://httpbin.org/get").call().unwrap();
892        res.body_mut().read_to_string().unwrap();
893    }
894
895    #[test]
896    fn redirect_no_follow() {
897        init_test_log();
898        let agent: Agent = Config::builder().max_redirects(0).build().into();
899        let mut res = agent
900            .get("http://httpbin.org/redirect-to?url=%2Fget")
901            .call()
902            .unwrap();
903        let txt = res.body_mut().read_to_string().unwrap();
904        #[cfg(feature = "_test")]
905        assert_eq!(txt, "You've been redirected");
906        #[cfg(not(feature = "_test"))]
907        assert_eq!(txt, "");
908    }
909
910    #[test]
911    fn redirect_max_with_error() {
912        init_test_log();
913        let agent: Agent = Config::builder().max_redirects(3).build().into();
914        let res = agent
915            .get(
916                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
917                url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
918            )
919            .call();
920        let err = res.unwrap_err();
921        assert_eq!(err.to_string(), "too many redirects");
922    }
923
924    #[test]
925    fn redirect_max_without_error() {
926        init_test_log();
927        let agent: Agent = Config::builder()
928            .max_redirects(3)
929            .max_redirects_will_error(false)
930            .build()
931            .into();
932        let res = agent
933            .get(
934                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
935                url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
936            )
937            .call()
938            .unwrap();
939        assert_eq!(res.status(), 302);
940    }
941
942    #[test]
943    fn redirect_follow() {
944        init_test_log();
945        let res = get("http://httpbin.org/redirect-to?url=%2Fget")
946            .call()
947            .unwrap();
948        let response_uri = res.get_uri();
949        assert_eq!(response_uri.path(), "/get")
950    }
951
952    #[test]
953    fn redirect_history_none() {
954        init_test_log();
955        let res = get("http://httpbin.org/redirect-to?url=%2Fget")
956            .call()
957            .unwrap();
958        let redirect_history = res.get_redirect_history();
959        assert_eq!(redirect_history, None)
960    }
961
962    #[test]
963    fn redirect_history_some() {
964        init_test_log();
965        let agent: Agent = Config::builder()
966            .max_redirects(3)
967            .max_redirects_will_error(false)
968            .save_redirect_history(true)
969            .build()
970            .into();
971        let res = agent
972            .get("http://httpbin.org/redirect-to?url=%2Fget")
973            .call()
974            .unwrap();
975        let redirect_history = res.get_redirect_history();
976        assert_eq!(
977            redirect_history,
978            Some(
979                vec![
980                    "http://httpbin.org/redirect-to?url=%2Fget".parse().unwrap(),
981                    "http://httpbin.org/get".parse().unwrap()
982                ]
983                .as_ref()
984            )
985        );
986        let res = agent
987            .get(
988                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
989                url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
990            )
991            .call()
992            .unwrap();
993        let redirect_history = res.get_redirect_history();
994        assert_eq!(
995            redirect_history,
996            Some(vec![
997                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3Furl%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D".parse().unwrap(),
998                "http://httpbin.org/redirect-to?url=/redirect-to?url=%2Fredirect-to%3Furl%3D".parse().unwrap(),
999                "http://httpbin.org/redirect-to?url=/redirect-to?url=".parse().unwrap(),
1000                "http://httpbin.org/redirect-to?url=".parse().unwrap(),
1001            ].as_ref())
1002        );
1003        let res = agent.get("https://www.google.com/").call().unwrap();
1004        let redirect_history = res.get_redirect_history();
1005        assert_eq!(
1006            redirect_history,
1007            Some(vec!["https://www.google.com/".parse().unwrap()].as_ref())
1008        );
1009    }
1010
1011    #[test]
1012    fn connect_https_invalid_name() {
1013        let result = get("https://example.com{REQUEST_URI}/").call();
1014        let err = result.unwrap_err();
1015        assert!(matches!(err, Error::Http(_)));
1016        assert_eq!(err.to_string(), "http: invalid uri character");
1017    }
1018
1019    #[test]
1020    fn post_big_body_chunked() {
1021        init_test_log();
1022        // https://github.com/algesten/ureq/issues/879
1023        let mut data = io::Cursor::new(vec![42; 153_600]);
1024        post("http://httpbin.org/post")
1025            .content_type("application/octet-stream")
1026            .send(SendBody::from_reader(&mut data))
1027            .expect("to send correctly");
1028    }
1029
1030    #[test]
1031    #[cfg(not(feature = "_test"))]
1032    fn username_password_from_uri() {
1033        init_test_log();
1034        let mut res = get("https://martin:secret@httpbin.org/get").call().unwrap();
1035        let body = res.body_mut().read_to_string().unwrap();
1036        assert!(body.contains("Basic bWFydGluOnNlY3JldA=="));
1037    }
1038
1039    #[test]
1040    #[cfg(all(feature = "cookies", feature = "_test"))]
1041    fn store_response_cookies() {
1042        let agent = Agent::new_with_defaults();
1043        let _ = agent.get("https://www.google.com").call().unwrap();
1044
1045        let mut all: Vec<_> = agent
1046            .cookie_jar_lock()
1047            .iter()
1048            .map(|c| c.name().to_string())
1049            .collect();
1050
1051        all.sort();
1052
1053        assert_eq!(all, ["AEC", "__Secure-ENID"])
1054    }
1055
1056    #[test]
1057    #[cfg(all(feature = "cookies", feature = "_test"))]
1058    fn send_request_cookies() {
1059        init_test_log();
1060
1061        let agent = Agent::new_with_defaults();
1062        let uri = Uri::from_static("http://cookie.test/cookie-test");
1063        let uri2 = Uri::from_static("http://cookie2.test/cookie-test");
1064
1065        let mut jar = agent.cookie_jar_lock();
1066        jar.insert(Cookie::parse("a=1", &uri).unwrap(), &uri)
1067            .unwrap();
1068        jar.insert(Cookie::parse("b=2", &uri).unwrap(), &uri)
1069            .unwrap();
1070        jar.insert(Cookie::parse("c=3", &uri2).unwrap(), &uri2)
1071            .unwrap();
1072
1073        jar.release();
1074
1075        let _ = agent.get("http://cookie.test/cookie-test").call().unwrap();
1076    }
1077
1078    #[test]
1079    #[cfg(all(feature = "_test", not(feature = "cookies")))]
1080    fn partial_redirect_when_following() {
1081        init_test_log();
1082        // this should work because we follow the redirect and go to /get
1083        get("http://my-host.com/partial-redirect").call().unwrap();
1084    }
1085
1086    #[test]
1087    #[cfg(feature = "_test")]
1088    fn partial_redirect_when_not_following() {
1089        init_test_log();
1090        // this should fail because we are not following redirects, and the
1091        // response is partial before the server is hanging up
1092        get("http://my-host.com/partial-redirect")
1093            .config()
1094            .max_redirects(0)
1095            .build()
1096            .call()
1097            .unwrap_err();
1098    }
1099
1100    #[test]
1101    #[cfg(feature = "_test")]
1102    fn http_connect_proxy() {
1103        init_test_log();
1104
1105        let proxy = Proxy::new("http://my_proxy:1234/connect-proxy").unwrap();
1106
1107        let agent = Agent::config_builder()
1108            .proxy(Some(proxy))
1109            .build()
1110            .new_agent();
1111
1112        let mut res = agent.get("http://httpbin.org/get").call().unwrap();
1113        res.body_mut().read_to_string().unwrap();
1114    }
1115
1116    #[test]
1117    fn ensure_reasonable_stack_sizes() {
1118        macro_rules! ensure {
1119            ($type:ty, $size:tt) => {
1120                let sz = std::mem::size_of::<$type>();
1121                // println!("{}: {}", stringify!($type), sz);
1122                assert!(
1123                    sz <= $size,
1124                    "Stack size of {} is too big {} > {}",
1125                    stringify!($type),
1126                    sz,
1127                    $size
1128                );
1129            };
1130        }
1131
1132        ensure!(RequestBuilder<WithoutBody>, 400); // 304
1133        ensure!(Agent, 100); // 32
1134        ensure!(Config, 400); // 320
1135        ensure!(ConfigBuilder<AgentScope>, 400); // 320
1136        ensure!(Response<Body>, 250); // 136
1137        ensure!(Body, 50); // 24
1138    }
1139
1140    #[test]
1141    #[cfg(feature = "_test")]
1142    fn limit_max_response_header_size() {
1143        init_test_log();
1144        let err = get("http://httpbin.org/get")
1145            .config()
1146            .max_response_header_size(5)
1147            .build()
1148            .call()
1149            .unwrap_err();
1150        assert!(matches!(err, Error::LargeResponseHeader(65, 5)));
1151    }
1152
1153    #[test]
1154    #[cfg(feature = "_test")]
1155    fn propfind_with_body() {
1156        init_test_log();
1157
1158        // https://github.com/algesten/ureq/issues/1034
1159        let request = http::Request::builder()
1160            .method("PROPFIND")
1161            .uri("https://www.google.com/")
1162            .body("Some really cool body")
1163            .unwrap();
1164
1165        let _ = Agent::config_builder()
1166            .allow_non_standard_methods(true)
1167            .build()
1168            .new_agent()
1169            .run(request)
1170            .unwrap();
1171    }
1172
1173    #[test]
1174    #[cfg(feature = "_test")]
1175    fn non_standard_method() {
1176        init_test_log();
1177        let method = Method::from_bytes(b"FNORD").unwrap();
1178
1179        let req = Request::builder()
1180            .method(method)
1181            .uri("http://httpbin.org/fnord")
1182            .body(())
1183            .unwrap();
1184
1185        let agent = Agent::new_with_defaults();
1186
1187        let req = agent
1188            .configure_request(req)
1189            .allow_non_standard_methods(true)
1190            .build();
1191
1192        agent.run(req).unwrap();
1193    }
1194
1195    #[test]
1196    #[cfg(feature = "_test")]
1197    fn chunk_abort() {
1198        init_test_log();
1199        let mut res = get("http://my-fine-server/1chunk-abort").call().unwrap();
1200        let body = res.body_mut().read_to_string().unwrap();
1201        assert_eq!(body, "OK");
1202        let mut res = get("http://my-fine-server/2chunk-abort").call().unwrap();
1203        let body = res.body_mut().read_to_string().unwrap();
1204        assert_eq!(body, "OK");
1205        let mut res = get("http://my-fine-server/3chunk-abort").call().unwrap();
1206        let body = res.body_mut().read_to_string().unwrap();
1207        assert_eq!(body, "OK");
1208        let mut res = get("http://my-fine-server/4chunk-abort").call().unwrap();
1209        let body = res.body_mut().read_to_string().unwrap();
1210        assert_eq!(body, "OK");
1211    }
1212
1213    // This doesn't need to run, just compile.
1214    fn _ensure_send_sync() {
1215        fn is_send(_t: impl Send) {}
1216        fn is_sync(_t: impl Sync) {}
1217
1218        // Agent
1219        is_send(Agent::new_with_defaults());
1220        is_sync(Agent::new_with_defaults());
1221
1222        // ResponseBuilder
1223        is_send(get("https://example.test"));
1224        is_sync(get("https://example.test"));
1225
1226        let data = vec![0_u8, 1, 2, 3, 4];
1227
1228        // Response<Body> via ResponseBuilder
1229        is_send(post("https://example.test").send(&data));
1230        is_sync(post("https://example.test").send(&data));
1231
1232        // Request<impl AsBody>
1233        is_send(Request::post("https://yaz").body(&data).unwrap());
1234        is_sync(Request::post("https://yaz").body(&data).unwrap());
1235
1236        // Response<Body> via Agent::run
1237        is_send(run(Request::post("https://yaz").body(&data).unwrap()));
1238        is_sync(run(Request::post("https://yaz").body(&data).unwrap()));
1239
1240        // Response<BodyReader<'a>>
1241        let mut response = post("https://yaz").send(&data).unwrap();
1242        let shared_reader = response.body_mut().as_reader();
1243        is_send(shared_reader);
1244        let shared_reader = response.body_mut().as_reader();
1245        is_sync(shared_reader);
1246
1247        // Response<BodyReader<'static>>
1248        let response = post("https://yaz").send(&data).unwrap();
1249        let owned_reader = response.into_parts().1.into_reader();
1250        is_send(owned_reader);
1251        let response = post("https://yaz").send(&data).unwrap();
1252        let owned_reader = response.into_parts().1.into_reader();
1253        is_sync(owned_reader);
1254
1255        let err = Error::HostNotFound;
1256        is_send(err);
1257        let err = Error::HostNotFound;
1258        is_sync(err);
1259    }
1260}