[go: up one dir, main page]

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;
526pub use request::RequestBuilder;
527use request::{WithBody, WithoutBody};
528pub use response::ResponseExt;
529pub use send_body::AsSendBody;
530
531mod agent;
532mod body;
533pub mod config;
534mod error;
535mod pool;
536mod proxy;
537mod query;
538mod request;
539mod response;
540mod run;
541mod send_body;
542mod timings;
543mod util;
544
545pub mod unversioned;
546use unversioned::resolver;
547use unversioned::transport;
548
549pub mod middleware;
550
551#[cfg(feature = "_tls")]
552pub mod tls;
553
554#[cfg(feature = "cookies")]
555mod cookies;
556#[cfg(feature = "cookies")]
557pub use cookies::{Cookie, CookieJar};
558
559pub use agent::Agent;
560pub use error::Error;
561pub use send_body::SendBody;
562pub use timings::Timeout;
563
564/// Typestate variables.
565pub mod typestate {
566    pub use super::request::WithBody;
567    pub use super::request::WithoutBody;
568
569    pub use super::config::typestate::AgentScope;
570    pub use super::config::typestate::HttpCrateScope;
571    pub use super::config::typestate::RequestScope;
572}
573
574/// Run a [`http::Request<impl AsSendBody>`].
575pub fn run(request: Request<impl AsSendBody>) -> Result<Response<Body>, Error> {
576    let agent = Agent::new_with_defaults();
577    agent.run(request)
578}
579
580/// A new [Agent] with default configuration
581///
582/// Agents are used to hold configuration and keep state between requests.
583pub fn agent() -> Agent {
584    Agent::new_with_defaults()
585}
586
587/// Make a GET request.
588///
589/// Run on a use-once [`Agent`].
590#[must_use]
591pub fn get<T>(uri: T) -> RequestBuilder<WithoutBody>
592where
593    Uri: TryFrom<T>,
594    <Uri as TryFrom<T>>::Error: Into<http::Error>,
595{
596    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::GET, uri)
597}
598
599/// Make a POST request.
600///
601/// Run on a use-once [`Agent`].
602#[must_use]
603pub fn post<T>(uri: T) -> RequestBuilder<WithBody>
604where
605    Uri: TryFrom<T>,
606    <Uri as TryFrom<T>>::Error: Into<http::Error>,
607{
608    RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::POST, uri)
609}
610
611/// Make a PUT request.
612///
613/// Run on a use-once [`Agent`].
614#[must_use]
615pub fn put<T>(uri: T) -> RequestBuilder<WithBody>
616where
617    Uri: TryFrom<T>,
618    <Uri as TryFrom<T>>::Error: Into<http::Error>,
619{
620    RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::PUT, uri)
621}
622
623/// Make a DELETE request.
624///
625/// Run on a use-once [`Agent`].
626#[must_use]
627pub fn delete<T>(uri: T) -> RequestBuilder<WithoutBody>
628where
629    Uri: TryFrom<T>,
630    <Uri as TryFrom<T>>::Error: Into<http::Error>,
631{
632    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::DELETE, uri)
633}
634
635/// Make a HEAD request.
636///
637/// Run on a use-once [`Agent`].
638#[must_use]
639pub fn head<T>(uri: T) -> RequestBuilder<WithoutBody>
640where
641    Uri: TryFrom<T>,
642    <Uri as TryFrom<T>>::Error: Into<http::Error>,
643{
644    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::HEAD, uri)
645}
646
647/// Make an OPTIONS request.
648///
649/// Run on a use-once [`Agent`].
650#[must_use]
651pub fn options<T>(uri: T) -> RequestBuilder<WithoutBody>
652where
653    Uri: TryFrom<T>,
654    <Uri as TryFrom<T>>::Error: Into<http::Error>,
655{
656    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::OPTIONS, uri)
657}
658
659/// Make a CONNECT request.
660///
661/// Run on a use-once [`Agent`].
662#[must_use]
663pub fn connect<T>(uri: T) -> RequestBuilder<WithoutBody>
664where
665    Uri: TryFrom<T>,
666    <Uri as TryFrom<T>>::Error: Into<http::Error>,
667{
668    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::CONNECT, uri)
669}
670
671/// Make a PATCH request.
672///
673/// Run on a use-once [`Agent`].
674#[must_use]
675pub fn patch<T>(uri: T) -> RequestBuilder<WithBody>
676where
677    Uri: TryFrom<T>,
678    <Uri as TryFrom<T>>::Error: Into<http::Error>,
679{
680    RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::PATCH, uri)
681}
682
683/// Make a TRACE request.
684///
685/// Run on a use-once [`Agent`].
686#[must_use]
687pub fn trace<T>(uri: T) -> RequestBuilder<WithoutBody>
688where
689    Uri: TryFrom<T>,
690    <Uri as TryFrom<T>>::Error: Into<http::Error>,
691{
692    RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::TRACE, uri)
693}
694
695#[cfg(test)]
696pub(crate) mod test {
697    use std::{io, sync::OnceLock};
698
699    use assert_no_alloc::AllocDisabler;
700    use config::{Config, ConfigBuilder};
701    use typestate::AgentScope;
702
703    use super::*;
704
705    #[global_allocator]
706    // Some tests checks that we are not allocating
707    static A: AllocDisabler = AllocDisabler;
708
709    pub fn init_test_log() {
710        static INIT_LOG: OnceLock<()> = OnceLock::new();
711        INIT_LOG.get_or_init(|| env_logger::init());
712    }
713
714    #[test]
715    fn connect_http_google() {
716        init_test_log();
717        let agent = Agent::new_with_defaults();
718
719        let res = agent.get("http://www.google.com/").call().unwrap();
720        assert_eq!(
721            "text/html;charset=ISO-8859-1",
722            res.headers()
723                .get("content-type")
724                .unwrap()
725                .to_str()
726                .unwrap()
727                .replace("; ", ";")
728        );
729        assert_eq!(res.body().mime_type(), Some("text/html"));
730    }
731
732    #[test]
733    #[cfg(feature = "rustls")]
734    fn connect_https_google_rustls() {
735        init_test_log();
736        use config::Config;
737
738        use crate::tls::{TlsConfig, TlsProvider};
739
740        let agent: Agent = Config::builder()
741            .tls_config(TlsConfig::builder().provider(TlsProvider::Rustls).build())
742            .build()
743            .into();
744
745        let res = agent.get("https://www.google.com/").call().unwrap();
746        assert_eq!(
747            "text/html;charset=ISO-8859-1",
748            res.headers()
749                .get("content-type")
750                .unwrap()
751                .to_str()
752                .unwrap()
753                .replace("; ", ";")
754        );
755        assert_eq!(res.body().mime_type(), Some("text/html"));
756    }
757
758    #[test]
759    #[cfg(feature = "native-tls")]
760    fn connect_https_google_native_tls_simple() {
761        init_test_log();
762        use config::Config;
763
764        use crate::tls::{TlsConfig, TlsProvider};
765
766        let agent: Agent = Config::builder()
767            .tls_config(
768                TlsConfig::builder()
769                    .provider(TlsProvider::NativeTls)
770                    .build(),
771            )
772            .build()
773            .into();
774
775        let mut res = agent.get("https://www.google.com/").call().unwrap();
776
777        assert_eq!(
778            "text/html;charset=ISO-8859-1",
779            res.headers()
780                .get("content-type")
781                .unwrap()
782                .to_str()
783                .unwrap()
784                .replace("; ", ";")
785        );
786        assert_eq!(res.body().mime_type(), Some("text/html"));
787        res.body_mut().read_to_string().unwrap();
788    }
789
790    #[test]
791    #[cfg(feature = "rustls")]
792    fn connect_https_google_rustls_webpki() {
793        init_test_log();
794        use crate::tls::{RootCerts, TlsConfig, TlsProvider};
795        use config::Config;
796
797        let agent: Agent = Config::builder()
798            .tls_config(
799                TlsConfig::builder()
800                    .provider(TlsProvider::Rustls)
801                    .root_certs(RootCerts::WebPki)
802                    .build(),
803            )
804            .build()
805            .into();
806
807        agent.get("https://www.google.com/").call().unwrap();
808    }
809
810    #[test]
811    #[cfg(feature = "native-tls")]
812    fn connect_https_google_native_tls_webpki() {
813        init_test_log();
814        use crate::tls::{RootCerts, TlsConfig, TlsProvider};
815        use config::Config;
816
817        let agent: Agent = Config::builder()
818            .tls_config(
819                TlsConfig::builder()
820                    .provider(TlsProvider::NativeTls)
821                    .root_certs(RootCerts::WebPki)
822                    .build(),
823            )
824            .build()
825            .into();
826
827        agent.get("https://www.google.com/").call().unwrap();
828    }
829
830    #[test]
831    #[cfg(feature = "rustls")]
832    fn connect_https_google_noverif() {
833        init_test_log();
834        use crate::tls::{TlsConfig, TlsProvider};
835
836        let agent: Agent = Config::builder()
837            .tls_config(
838                TlsConfig::builder()
839                    .provider(TlsProvider::Rustls)
840                    .disable_verification(true)
841                    .build(),
842            )
843            .build()
844            .into();
845
846        let res = agent.get("https://www.google.com/").call().unwrap();
847        assert_eq!(
848            "text/html;charset=ISO-8859-1",
849            res.headers()
850                .get("content-type")
851                .unwrap()
852                .to_str()
853                .unwrap()
854                .replace("; ", ";")
855        );
856        assert_eq!(res.body().mime_type(), Some("text/html"));
857    }
858
859    #[test]
860    fn simple_put_content_len() {
861        init_test_log();
862        let mut res = put("http://httpbin.org/put").send(&[0_u8; 100]).unwrap();
863        res.body_mut().read_to_string().unwrap();
864    }
865
866    #[test]
867    fn simple_put_chunked() {
868        init_test_log();
869        let mut res = put("http://httpbin.org/put")
870            // override default behavior
871            .header("transfer-encoding", "chunked")
872            .send(&[0_u8; 100])
873            .unwrap();
874        res.body_mut().read_to_string().unwrap();
875    }
876
877    #[test]
878    fn simple_get() {
879        init_test_log();
880        let mut res = get("http://httpbin.org/get").call().unwrap();
881        res.body_mut().read_to_string().unwrap();
882    }
883
884    #[test]
885    fn simple_head() {
886        init_test_log();
887        let mut res = head("http://httpbin.org/get").call().unwrap();
888        res.body_mut().read_to_string().unwrap();
889    }
890
891    #[test]
892    fn redirect_no_follow() {
893        init_test_log();
894        let agent: Agent = Config::builder().max_redirects(0).build().into();
895        let mut res = agent
896            .get("http://httpbin.org/redirect-to?url=%2Fget")
897            .call()
898            .unwrap();
899        let txt = res.body_mut().read_to_string().unwrap();
900        #[cfg(feature = "_test")]
901        assert_eq!(txt, "You've been redirected");
902        #[cfg(not(feature = "_test"))]
903        assert_eq!(txt, "");
904    }
905
906    #[test]
907    fn redirect_max_with_error() {
908        init_test_log();
909        let agent: Agent = Config::builder().max_redirects(3).build().into();
910        let res = agent
911            .get(
912                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
913                url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
914            )
915            .call();
916        let err = res.unwrap_err();
917        assert_eq!(err.to_string(), "too many redirects");
918    }
919
920    #[test]
921    fn redirect_max_without_error() {
922        init_test_log();
923        let agent: Agent = Config::builder()
924            .max_redirects(3)
925            .max_redirects_will_error(false)
926            .build()
927            .into();
928        let res = agent
929            .get(
930                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
931                url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
932            )
933            .call()
934            .unwrap();
935        assert_eq!(res.status(), 302);
936    }
937
938    #[test]
939    fn redirect_follow() {
940        init_test_log();
941        let res = get("http://httpbin.org/redirect-to?url=%2Fget")
942            .call()
943            .unwrap();
944        let response_uri = res.get_uri();
945        assert_eq!(response_uri.path(), "/get")
946    }
947
948    #[test]
949    fn redirect_history_none() {
950        init_test_log();
951        let res = get("http://httpbin.org/redirect-to?url=%2Fget")
952            .call()
953            .unwrap();
954        let redirect_history = res.get_redirect_history();
955        assert_eq!(redirect_history, None)
956    }
957
958    #[test]
959    fn redirect_history_some() {
960        init_test_log();
961        let agent: Agent = Config::builder()
962            .max_redirects(3)
963            .max_redirects_will_error(false)
964            .save_redirect_history(true)
965            .build()
966            .into();
967        let res = agent
968            .get("http://httpbin.org/redirect-to?url=%2Fget")
969            .call()
970            .unwrap();
971        let redirect_history = res.get_redirect_history();
972        assert_eq!(
973            redirect_history,
974            Some(
975                vec![
976                    "http://httpbin.org/redirect-to?url=%2Fget".parse().unwrap(),
977                    "http://httpbin.org/get".parse().unwrap()
978                ]
979                .as_ref()
980            )
981        );
982        let res = agent
983            .get(
984                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
985                url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
986            )
987            .call()
988            .unwrap();
989        let redirect_history = res.get_redirect_history();
990        assert_eq!(
991            redirect_history,
992            Some(vec![
993                "http://httpbin.org/redirect-to?url=%2Fredirect-to%3Furl%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D".parse().unwrap(),
994                "http://httpbin.org/redirect-to?url=/redirect-to?url=%2Fredirect-to%3Furl%3D".parse().unwrap(),
995                "http://httpbin.org/redirect-to?url=/redirect-to?url=".parse().unwrap(),
996                "http://httpbin.org/redirect-to?url=".parse().unwrap(),
997            ].as_ref())
998        );
999        let res = agent.get("https://www.google.com/").call().unwrap();
1000        let redirect_history = res.get_redirect_history();
1001        assert_eq!(
1002            redirect_history,
1003            Some(vec!["https://www.google.com/".parse().unwrap()].as_ref())
1004        );
1005    }
1006
1007    #[test]
1008    fn connect_https_invalid_name() {
1009        let result = get("https://example.com{REQUEST_URI}/").call();
1010        let err = result.unwrap_err();
1011        assert!(matches!(err, Error::Http(_)));
1012        assert_eq!(err.to_string(), "http: invalid uri character");
1013    }
1014
1015    #[test]
1016    fn post_big_body_chunked() {
1017        // https://github.com/algesten/ureq/issues/879
1018        let mut data = io::Cursor::new(vec![42; 153_600]);
1019        post("http://httpbin.org/post")
1020            .content_type("application/octet-stream")
1021            .send(SendBody::from_reader(&mut data))
1022            .expect("to send correctly");
1023    }
1024
1025    #[test]
1026    #[cfg(not(feature = "_test"))]
1027    fn username_password_from_uri() {
1028        init_test_log();
1029        let mut res = get("https://martin:secret@httpbin.org/get").call().unwrap();
1030        let body = res.body_mut().read_to_string().unwrap();
1031        assert!(body.contains("Basic bWFydGluOnNlY3JldA=="));
1032    }
1033
1034    #[test]
1035    #[cfg(all(feature = "cookies", feature = "_test"))]
1036    fn store_response_cookies() {
1037        let agent = Agent::new_with_defaults();
1038        let _ = agent.get("https://www.google.com").call().unwrap();
1039
1040        let mut all: Vec<_> = agent
1041            .cookie_jar_lock()
1042            .iter()
1043            .map(|c| c.name().to_string())
1044            .collect();
1045
1046        all.sort();
1047
1048        assert_eq!(all, ["AEC", "__Secure-ENID"])
1049    }
1050
1051    #[test]
1052    #[cfg(all(feature = "cookies", feature = "_test"))]
1053    fn send_request_cookies() {
1054        init_test_log();
1055
1056        let agent = Agent::new_with_defaults();
1057        let uri = Uri::from_static("http://cookie.test/cookie-test");
1058        let uri2 = Uri::from_static("http://cookie2.test/cookie-test");
1059
1060        let mut jar = agent.cookie_jar_lock();
1061        jar.insert(Cookie::parse("a=1", &uri).unwrap(), &uri)
1062            .unwrap();
1063        jar.insert(Cookie::parse("b=2", &uri).unwrap(), &uri)
1064            .unwrap();
1065        jar.insert(Cookie::parse("c=3", &uri2).unwrap(), &uri2)
1066            .unwrap();
1067
1068        jar.release();
1069
1070        let _ = agent.get("http://cookie.test/cookie-test").call().unwrap();
1071    }
1072
1073    #[test]
1074    #[cfg(all(feature = "_test", not(feature = "cookies")))]
1075    fn partial_redirect_when_following() {
1076        init_test_log();
1077        // this should work because we follow the redirect and go to /get
1078        get("http://my-host.com/partial-redirect").call().unwrap();
1079    }
1080
1081    #[test]
1082    #[cfg(feature = "_test")]
1083    fn partial_redirect_when_not_following() {
1084        init_test_log();
1085        // this should fail because we are not following redirects, and the
1086        // response is partial before the server is hanging up
1087        get("http://my-host.com/partial-redirect")
1088            .config()
1089            .max_redirects(0)
1090            .build()
1091            .call()
1092            .unwrap_err();
1093    }
1094
1095    #[test]
1096    #[cfg(feature = "_test")]
1097    fn http_connect_proxy() {
1098        init_test_log();
1099
1100        let proxy = Proxy::new("http://my_proxy:1234/connect-proxy").unwrap();
1101
1102        let agent = Agent::config_builder()
1103            .proxy(Some(proxy))
1104            .build()
1105            .new_agent();
1106
1107        let mut res = agent.get("http://httpbin.org/get").call().unwrap();
1108        res.body_mut().read_to_string().unwrap();
1109    }
1110
1111    #[test]
1112    fn ensure_reasonable_stack_sizes() {
1113        macro_rules! ensure {
1114            ($type:ty, $size:tt) => {
1115                let sz = std::mem::size_of::<$type>();
1116                // println!("{}: {}", stringify!($type), sz);
1117                assert!(
1118                    sz <= $size,
1119                    "Stack size of {} is too big {} > {}",
1120                    stringify!($type),
1121                    sz,
1122                    $size
1123                );
1124            };
1125        }
1126
1127        ensure!(RequestBuilder<WithoutBody>, 400); // 288
1128        ensure!(Agent, 100); // 32
1129        ensure!(Config, 400); // 320
1130        ensure!(ConfigBuilder<AgentScope>, 400); // 320
1131        ensure!(Response<Body>, 800); // 760
1132        ensure!(Body, 700); // 648
1133    }
1134
1135    #[test]
1136    fn limit_max_response_header_size() {
1137        init_test_log();
1138        let err = get("http://httpbin.org/get")
1139            .config()
1140            .max_response_header_size(5)
1141            .build()
1142            .call()
1143            .unwrap_err();
1144        assert!(matches!(err, Error::LargeResponseHeader(65, 5)));
1145    }
1146
1147    #[test]
1148    fn propfind_with_body() {
1149        init_test_log();
1150
1151        // https://github.com/algesten/ureq/issues/1034
1152        let request = http::Request::builder()
1153            .method("PROPFIND")
1154            .uri("https://www.google.com/")
1155            .body("Some really cool body")
1156            .unwrap();
1157
1158        let _ = Agent::config_builder()
1159            .allow_non_standard_methods(true)
1160            .build()
1161            .new_agent()
1162            .run(request)
1163            .unwrap();
1164    }
1165
1166    #[test]
1167    #[cfg(feature = "_test")]
1168    fn non_standard_method() {
1169        init_test_log();
1170        let method = Method::from_bytes(b"FNORD").unwrap();
1171
1172        let req = Request::builder()
1173            .method(method)
1174            .uri("http://httpbin.org/fnord")
1175            .body(())
1176            .unwrap();
1177
1178        let agent = Agent::new_with_defaults();
1179
1180        let req = agent
1181            .configure_request(req)
1182            .allow_non_standard_methods(true)
1183            .build();
1184
1185        agent.run(req).unwrap();
1186    }
1187
1188    // This doesn't need to run, just compile.
1189    fn _ensure_send_sync() {
1190        fn is_send(_t: impl Send) {}
1191        fn is_sync(_t: impl Sync) {}
1192
1193        // Agent
1194        is_send(Agent::new_with_defaults());
1195        is_sync(Agent::new_with_defaults());
1196
1197        // ResponseBuilder
1198        is_send(get("https://example.test"));
1199        is_sync(get("https://example.test"));
1200
1201        let data = vec![0_u8, 1, 2, 3, 4];
1202
1203        // Response<Body> via ResponseBuilder
1204        is_send(post("https://example.test").send(&data));
1205        is_sync(post("https://example.test").send(&data));
1206
1207        // Request<impl AsBody>
1208        is_send(Request::post("https://yaz").body(&data).unwrap());
1209        is_sync(Request::post("https://yaz").body(&data).unwrap());
1210
1211        // Response<Body> via Agent::run
1212        is_send(run(Request::post("https://yaz").body(&data).unwrap()));
1213        is_sync(run(Request::post("https://yaz").body(&data).unwrap()));
1214
1215        // Response<BodyReader<'a>>
1216        let mut response = post("https://yaz").send(&data).unwrap();
1217        let shared_reader = response.body_mut().as_reader();
1218        is_send(shared_reader);
1219        let shared_reader = response.body_mut().as_reader();
1220        is_sync(shared_reader);
1221
1222        // Response<BodyReader<'static>>
1223        let response = post("https://yaz").send(&data).unwrap();
1224        let owned_reader = response.into_parts().1.into_reader();
1225        is_send(owned_reader);
1226        let response = post("https://yaz").send(&data).unwrap();
1227        let owned_reader = response.into_parts().1.into_reader();
1228        is_sync(owned_reader);
1229
1230        let err = Error::HostNotFound;
1231        is_send(err);
1232        let err = Error::HostNotFound;
1233        is_sync(err);
1234    }
1235}