slinger/client.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
use std::collections::BTreeMap;
use std::fmt::{Debug, Formatter};
use std::io::{BufReader, Write};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Method, StatusCode};
#[cfg(feature = "tls")]
use native_tls::{Certificate, Identity};
#[cfg(feature = "tls")]
use openssl::x509::X509;
#[cfg(feature = "cookie")]
use crate::cookies;
use crate::errors::{new_io_error, Result};
use crate::proxy::Proxy;
use crate::record::{HTTPRecord, LocalPeerRecord, RedirectRecord};
use crate::redirect::{remove_sensitive_headers, Action, Policy};
use crate::response::{ResponseBuilder, ResponseConfig};
use crate::socket::Socket;
use crate::{Connector, ConnectorBuilder, Request, RequestBuilder, Response};
/// A `Client` to make Requests with.
///
/// The Client has various configuration values to tweak, but the defaults
/// are set to what is usually the most commonly desired value. To configure a
/// `Client`, use `Client::builder()`.
///
/// The `Client` holds a connection pool internally, so it is advised that
/// you create one and **reuse** it.
///
/// # Examples
///
/// ```rust
/// use slinger::Client;
/// #
/// # fn run() -> Result<(), slinger::Error> {
/// let client = Client::new();
/// let resp = client.get("http://httpbin.org/").send()?;
/// # Ok(())
/// # }
///
/// ```
#[derive(Clone, Debug)]
pub struct Client {
inner: ClientRef,
}
impl Default for Client {
fn default() -> Self {
Self::new()
}
}
impl Client {
/// Constructs a new `Client`.
///
/// # Panic
///
/// This method panics if TLS backend cannot be initialized, or the resolver
/// cannot load the system configuration.
///
/// Use `Client::builder()` if you wish to handle the failure as an `Error`
/// instead of panicking.
///
/// See docs
/// on [`slinger`][Client] for details.
pub fn new() -> Client {
ClientBuilder::new().build().expect("Client::new()")
}
/// Creates a `ClientBuilder` to configure a `Client`.
///
/// This is the same as `ClientBuilder::new()`.
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
/// Convenience method to make a `GET` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn get<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::GET, url)
}
/// Convenience method to make a `POST` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn post<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::POST, url)
}
/// Convenience method to make a `PUT` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn put<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::PUT, url)
}
/// Convenience method to make a `PATCH` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn patch<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::PATCH, url)
}
/// Convenience method to make a `DELETE` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn delete<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::DELETE, url)
}
/// Convenience method to make a `HEAD` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn head<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::HEAD, url)
}
/// Convenience method to make a `TRACE` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn trace<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::TRACE, url)
}
/// Convenience method to make a `CONNECT` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn connect<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::CONNECT, url)
}
/// Convenience method to make a `OPTIONS` request to a URL.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn options<U>(&self, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
self.request(Method::OPTIONS, url)
}
/// Start building a `Request` with the `Method` and `Uri`.
///
/// Returns a `RequestBuilder`, which will allow setting headers and
/// request body before sending.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn request<U>(&self, method: Method, url: U) -> RequestBuilder
where
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
RequestBuilder::new(
self.clone(),
http::request::Builder::new().method(method).uri(url),
)
}
/// Start building a `Request` with the `Method` and `Uri`.
///
/// Returns a `RequestBuilder`, which will allow setting headers and
/// request body before sending.
///
/// # Errors
///
/// This method fails whenever supplied `Uri` cannot be parsed.
pub fn raw<U, R>(&self, uri: U, raw: R, unsafe_raw: bool) -> RequestBuilder
where
Bytes: From<R>,
http::Uri: TryFrom<U>,
<http::Uri as TryFrom<U>>::Error: Into<http::Error>,
{
let mut builder = RequestBuilder::new(self.clone(), http::request::Builder::new().uri(uri));
builder = builder.raw(raw, unsafe_raw);
builder
}
/// Executes a `Request`.
///
/// A `Request` can be built manually with `Request::new()` or obtained
/// from a RequestBuilder with `RequestBuilder::build()`.
///
/// You should prefer to use the `RequestBuilder` and
/// `RequestBuilder::send()`.
///
/// # Errors
///
/// This method fails if there was an error while sending request,
/// or redirect limit was exhausted.
pub fn execute_request(&self, socket: &mut Socket, request: &Request) -> Result<Response> {
let raw: Bytes = request.to_raw();
#[cfg(feature = "tls")]
let mut certificate: Option<X509> = None;
#[cfg(feature = "tls")]
{
if let Some(x509) = socket.peer_certificate() {
certificate = Some(x509);
}
}
socket.write_all(&raw)?;
socket.flush()?;
let reader = BufReader::new(socket);
let mut irp =
ResponseBuilder::new(reader, ResponseConfig::new(request, self.inner.timeout)).build()?;
*irp.url_mut() = request.uri().clone();
#[cfg(feature = "tls")]
{
if let Some(cert) = certificate {
irp.extensions_mut().insert(cert);
}
}
Ok(irp)
}
/// Executes a `Request`.
///
/// A `Request` can be built manually with `Request::new()` or obtained
/// from a RequestBuilder with `RequestBuilder::build()`.
///
/// You should prefer to use the `RequestBuilder` and
/// `RequestBuilder::send()`.
///
/// # Errors
///
/// This method fails if there was an error while sending request,
/// or redirect limit was exhausted.
pub fn execute<R: Into<Request>>(&self, request: R) -> Result<Response> {
let mut records = vec![];
let mut request = request.into();
let mut cur_uri = request.uri().clone();
let mut uris = vec![];
let mut conn: BTreeMap<String, Socket> = BTreeMap::new();
// 连接一次,同一个主机地址下复用socket连接
let uniq_key = |u: &http::Uri| -> String {
let scheme = u.scheme_str().unwrap_or_default();
let host = u.host().unwrap_or_default();
let port = u.port_u16().unwrap_or_default();
format!("{}{}{}", scheme, host, port)
};
loop {
let mut record = HTTPRecord::default();
for (k, v) in self.inner.header.iter() {
// 内置优先级低于用户配置的
if request.headers().get(k).is_none() {
request.headers_mut().insert(k, v.clone());
}
}
// 设置cookie到请求头
#[cfg(feature = "cookie")]
{
if let Some(cookie_store) = self.inner.cookie_store.as_ref() {
if request.headers().get(http::header::COOKIE).is_none() {
add_cookie_header(&mut request, &**cookie_store);
}
}
}
record.record_request(&request);
let socket = conn
.entry(uniq_key(&cur_uri))
.or_insert(self.inner.connector.connect_with_uri(&cur_uri)?);
let mut response = self.execute_request(socket, &request)?;
response.extensions_mut().insert(request.clone());
if let (Ok(remote_addr), Ok(local_addr)) = (socket.peer_addr(), socket.local_addr()) {
response.extensions_mut().insert(LocalPeerRecord {
remote_addr,
local_addr,
});
};
if let Some(cv) = response.headers().get(http::header::CONNECTION) {
match cv.to_str().unwrap_or_default() {
"keep-alive" => {
if let Some(s) = conn.get_mut(&uniq_key(&cur_uri)) {
if s.peer_addr().is_err() {
*s = self.inner.connector.connect_with_uri(&cur_uri)?;
}
}
}
_ => {
conn.remove(&uniq_key(&cur_uri));
}
}
} else {
conn.remove(&uniq_key(&cur_uri));
}
// 原始请求不跳转
if request.raw_request().is_some() {
record.record_response(&response);
records.push(record);
break;
}
// 保存请求头的cookie
#[cfg(feature = "cookie")]
{
if let Some(ref cookie_store) = self.inner.cookie_store {
let mut cookies = cookies::extract_response_cookie_headers(response.headers()).peekable();
if cookies.peek().is_some() {
cookie_store.set_cookies(&mut cookies, request.uri());
}
}
}
// 根据状态码判断是否应该跳转,并清除一些请求头信息
// Determine whether to redirect on the status code and clear request header
let should_redirect = match response.status_code() {
StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER => {
for header in &[
http::header::TRANSFER_ENCODING,
http::header::CONTENT_ENCODING,
http::header::CONTENT_TYPE,
http::header::CONTENT_LENGTH,
] {
request.headers_mut().remove(header);
}
match request.method() {
&Method::GET | &Method::HEAD => {}
_ => {
*request.method_mut() = Method::GET;
}
}
true
}
StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => true,
_ => false,
};
let mut redirect_info = RedirectRecord {
should_redirect,
next: None,
};
// 如果要跳转,获取进入跳转策略流程
// 生成策略
uris.push(cur_uri.clone());
let action = self.inner.redirect_policy.check(&response, &uris);
match action {
Action::Follow(loc) => {
redirect_info.next = Some(loc.clone());
// 添加referer
if self.inner.referer {
if let Some(referer) = make_referer(&loc, &cur_uri) {
response
.headers_mut()
.insert(http::header::REFERER, referer);
}
}
cur_uri = loc;
*request.uri_mut() =
http::Uri::from_str(&cur_uri.to_string()).map_err(http::Error::from)?;
let mut headers = std::mem::replace(response.headers_mut(), HeaderMap::new());
remove_sensitive_headers(&mut headers, &cur_uri, uris.as_slice());
record.record_response(&response);
records.push(record);
continue;
}
Action::Stop(next) => {
redirect_info.next = Some(next.clone());
}
Action::None => {}
}
response.extensions_mut().insert(redirect_info);
record.record_response(&response);
records.push(record);
break;
}
for (_key, socket) in conn {
socket.shutdown(std::net::Shutdown::Both)?;
}
let mut last_response = records
.last()
.ok_or(new_io_error(
std::io::ErrorKind::NotFound,
"not found record",
))?
.response
.clone();
last_response.extensions_mut().insert(records);
Ok(last_response)
}
}
#[cfg(feature = "cookie")]
#[cfg_attr(docsrs, doc(cfg(feature = "cookie")))]
fn add_cookie_header(request: &mut Request, cookie_store: &dyn cookies::CookieStore) {
if let Some(header) = cookie_store.cookies(request.uri()) {
request.headers_mut().insert(http::header::COOKIE, header);
}
}
fn make_referer(next: &http::Uri, previous: &http::Uri) -> Option<HeaderValue> {
if next.scheme() == Some(&http::uri::Scheme::HTTP)
&& previous.scheme() == Some(&http::uri::Scheme::HTTPS)
{
return None;
}
let referer = previous.clone();
let mut builder = http::uri::Uri::builder();
if let Some(scheme) = referer.scheme_str() {
builder = builder.scheme(scheme);
}
if let Some(host) = referer.host() {
let mut host_port = host.to_string();
if let Some(port) = referer.port() {
host_port.push(':');
host_port.push_str(port.as_str());
};
builder = builder.authority(host_port);
};
if let Some(path) = referer.path_and_query() {
builder = builder.path_and_query(path.as_str());
}
HeaderValue::from_str(&builder.build().ok()?.to_string()).ok()
}
/// A `ClientBuilder` can be used to create a `Client` with custom configuration.
///
/// # Example
///
/// ```
/// # fn run() -> Result<(), slinger::Error> {
/// use std::time::Duration;
///
/// let client = slinger::Client::builder()
/// .timeout(Some(Duration::from_secs(10)))
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[must_use]
#[derive(Clone, Debug)]
pub struct ClientBuilder {
config: Config,
}
impl Default for ClientBuilder {
fn default() -> Self {
Self::new()
}
}
impl ClientBuilder {
/// Constructs a new `ClientBuilder`.
///
/// This is the same as `Client::builder()`.
pub fn new() -> ClientBuilder {
ClientBuilder {
config: Config::default(),
}
}
/// Returns a `Client` that uses this `ClientBuilder` configuration.
///
/// # Errors
///
/// This method fails if TLS backend cannot be initialized, or the resolver
/// cannot load the system configuration.
///
/// # Panics
///
/// See docs on
/// [`slinger::client`][Client] for details.
pub fn build(self) -> Result<Client> {
let config = self.config;
let mut connector_builder = ConnectorBuilder::default()
.proxy(config.proxy)
.read_timeout(config.read_timeout)
.connect_timeout(config.connect_timeout)
.write_timeout(config.timeout);
connector_builder = connector_builder.nodelay(config.nodelay);
#[cfg(feature = "tls")]
{
connector_builder = connector_builder
.hostname_verification(config.hostname_verification)
.certs_verification(config.certs_verification)
.certificate(config.root_certs)
.tls_sni(config.tls_sni)
.min_tls_version(config.min_tls_version)
.max_tls_version(config.max_tls_version);
if let Some(identity) = config.identity {
connector_builder = connector_builder.identity(identity);
}
}
let connector = connector_builder.build()?;
Ok(Client {
inner: ClientRef {
timeout: config.timeout,
#[cfg(feature = "cookie")]
cookie_store: config.cookie_store,
connector: Arc::new(connector),
redirect_policy: config.redirect_policy,
referer: config.referer,
header: config.headers,
},
})
}
// Higher-level options
/// Sets the `User-Agent` header to be used by this client.
///
/// # Example
///
/// ```rust
/// # use http::HeaderValue;
/// fn doc() -> Result<(), slinger::Error> {
/// let ua = HeaderValue::from_static("XX_UA");
/// let client = slinger::Client::builder()
/// .user_agent(ua)
/// .build()?;
/// let res = client.get("https://www.rust-lang.org").send()?;
/// # Ok(())
/// # }
/// ```
pub fn user_agent<V>(mut self, value: V) -> ClientBuilder
where
V: Into<HeaderValue>,
{
self
.config
.headers
.insert(http::header::USER_AGENT, value.into());
self
}
/// Sets the default headers for every request.
///
/// # Example
///
/// ```rust
/// use slinger::http::header;
/// # fn build_client() -> Result<(), slinger::Error> {
/// let mut headers = header::HeaderMap::new();
/// headers.insert("X-MY-HEADER", header::HeaderValue::from_static("value"));
/// headers.insert(header::AUTHORIZATION, header::HeaderValue::from_static("secret"));
///
/// // Consider marking security-sensitive headers with `set_sensitive`.
/// let mut auth_value = header::HeaderValue::from_static("secret");
/// auth_value.set_sensitive(true);
/// headers.insert(header::AUTHORIZATION, auth_value);
///
/// // get a client builder
/// let client = slinger::Client::builder()
/// .default_headers(headers)
/// .build()?;
/// let res = client.get("https://www.rust-lang.org").send()?;
/// # Ok(())
/// # }
/// ```
pub fn default_headers(mut self, headers: HeaderMap) -> ClientBuilder {
for (key, value) in headers.iter() {
self.config.headers.insert(key, value.clone());
}
self
}
// Redirect options
/// Set a `redirect::Policy` for this client.
///
/// Default will follow redirects up to a maximum of 10.
pub fn redirect(mut self, policy: Policy) -> ClientBuilder {
self.config.redirect_policy = policy;
self
}
/// Enable or disable automatic setting of the `Referer` header.
///
/// Default is `true`.
pub fn referer(mut self, enable: bool) -> ClientBuilder {
self.config.referer = enable;
self
}
// Proxy options
/// Add a `Proxy` to the list of proxies the `Client` will use.
///
/// # Note
///
/// Adding a proxy will disable the automatic usage of the "system" proxy.
pub fn proxy(mut self, proxy: Proxy) -> ClientBuilder {
self.config.proxy = Some(proxy);
self
}
// Timeout options
/// Set a timeout for connect, read and write operations of a `Client`.
///
/// Default is 30 seconds.
///
/// Pass `None` to disable timeout.
pub fn timeout(mut self, timeout: Option<Duration>) -> ClientBuilder {
self.config.timeout = timeout;
self
}
/// Set a timeout for only the connect phase of a `Client`.
///
/// Default is 10 seconds.
pub fn connect_timeout(mut self, timeout: Option<Duration>) -> ClientBuilder {
self.config.connect_timeout = timeout;
self
}
/// Set a timeout for only the read phase of a `Client`.
///
/// Default is 30 seconds.
pub fn read_timeout(mut self, timeout: Option<Duration>) -> ClientBuilder {
self.config.read_timeout = timeout;
self
}
// TCP options
/// Set whether sockets have `TCP_NODELAY` enabled.
///
/// Default is `true`.
pub fn tcp_nodelay(mut self, enabled: bool) -> ClientBuilder {
self.config.nodelay = enabled;
self
}
#[cfg(feature = "tls")]
// TLS options
/// Add a custom root certificate.
///
/// This allows connecting to a server that has a self-signed
/// certificate for example. This **does not** replace the existing
/// trusted store.
///
/// # Example
///
/// ```
/// # use std::fs::File;
/// # use std::io::Read;
/// # fn build_client() -> Result<(), Box<dyn std::error::Error>> {
/// // read a local binary DER encoded certificate
/// let der = std::fs::read("my-cert.der")?;
///
/// // create a certificate
/// let cert = slinger::native_tls::Certificate::from_der(&der)?;
///
/// // get a client builder
/// let client = slinger::Client::builder()
/// .add_root_certificate(cert)
/// .build()?;
/// # drop(client);
/// # Ok(())
/// # }
/// ```
///
/// # Optional
///
/// This requires the optional `tls`(-...)`
/// feature to be enabled.
pub fn add_root_certificate(mut self, cert: Certificate) -> ClientBuilder {
self.config.root_certs.push(cert);
self
}
#[cfg(feature = "tls")]
/// Sets the identity to be used for client certificate authentication.
///
/// # Optional
///
/// This requires the optional `tls`
pub fn identity(mut self, identity: Identity) -> ClientBuilder {
self.config.identity = Some(identity);
self
}
/// Controls the use of hostname verification.
///
/// Defaults to `false`.
///
/// # Warning
///
/// You should think very carefully before you use this method. If
/// hostname verification is not used, any valid certificate for any
/// site will be trusted for use from any other. This introduces a
/// significant vulnerability to man-in-the-middle attacks.
///
/// # Optional
///
/// This requires the optional `tls` feature to be enabled.
pub fn danger_accept_invalid_hostnames(mut self, accept_invalid_hostname: bool) -> ClientBuilder {
self.config.hostname_verification = !accept_invalid_hostname;
self
}
/// Controls the use of certificate validation.
///
/// Defaults to `false`.
///
/// # Warning
///
/// You should think very carefully before using this method. If
/// invalid certificates are trusted, *any* certificate for *any* site
/// will be trusted for use. This includes expired certificates. This
/// introduces significant vulnerabilities, and should only be used
/// as a last resort.
pub fn danger_accept_invalid_certs(mut self, accept_invalid_certs: bool) -> ClientBuilder {
self.config.certs_verification = !accept_invalid_certs;
self
}
/// Controls the use of TLS server name indication.
///
/// Defaults to `true`.
///
#[cfg(feature = "tls")]
pub fn tls_sni(mut self, tls_sni: bool) -> ClientBuilder {
self.config.tls_sni = tls_sni;
self
}
/// Enable a persistent cookie store for the client.
///
/// Cookies received in responses will be preserved and included in
/// additional requests.
///
/// By default, no cookie store is used. Enabling the cookies
/// # Optional
///
/// This requires the optional `cookie` feature to be enabled.
#[cfg(feature = "cookie")]
#[cfg_attr(docsrs, doc(cfg(feature = "cookie")))]
pub fn cookie_store(mut self, enable: bool) -> ClientBuilder {
if enable {
self.cookie_provider(Arc::new(cookies::Jar::default()))
} else {
self.config.cookie_store = None;
self
}
}
/// Set the persistent cookie store for the client.
///
/// Cookies received in responses will be passed to this store, and
/// additional requests will query this store for cookies.
///
/// By default, no cookie store is used.
///
/// # Optional
///
/// This requires the optional `cookies` feature to be enabled.
#[cfg(feature = "cookie")]
#[cfg_attr(docsrs, doc(cfg(feature = "cookie")))]
pub fn cookie_provider<C: cookies::CookieStore + 'static>(
mut self,
cookie_store: Arc<C>,
) -> ClientBuilder {
self.config.cookie_store = Some(cookie_store as _);
self
}
/// Set the minimum required TLS version for connections.
///
/// By default, the `native_tls::Protocol` default is used.
///
/// # Optional
///
/// This requires the optional `tls`
/// feature to be enabled.
#[cfg(feature = "tls")]
pub fn min_tls_version(mut self, version: Option<native_tls::Protocol>) -> ClientBuilder {
self.config.min_tls_version = version;
self
}
/// Set the maximum required TLS version for connections.
///
/// By default, the `native_tls::Protocol` default is used.
///
/// # Optional
///
/// This requires the optional `tls`
/// feature to be enabled.
#[cfg(feature = "tls")]
pub fn max_tls_version(mut self, version: Option<native_tls::Protocol>) -> ClientBuilder {
self.config.max_tls_version = version;
self
}
}
#[derive(Clone)]
struct Config {
timeout: Option<Duration>,
connect_timeout: Option<Duration>,
read_timeout: Option<Duration>,
headers: HeaderMap,
referer: bool,
proxy: Option<Proxy>,
nodelay: bool,
#[cfg(feature = "tls")]
root_certs: Vec<Certificate>,
#[cfg(feature = "tls")]
identity: Option<Identity>,
hostname_verification: bool,
certs_verification: bool,
#[cfg(feature = "tls")]
tls_sni: bool,
#[cfg(feature = "tls")]
min_tls_version: Option<native_tls::Protocol>,
#[cfg(feature = "tls")]
max_tls_version: Option<native_tls::Protocol>,
redirect_policy: Policy,
#[cfg(feature = "cookie")]
cookie_store: Option<Arc<dyn cookies::CookieStore>>,
}
impl Debug for Config {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Config")
.field("connect_timeout", &self.connect_timeout)
.field("headers", &self.headers)
.field("referer", &self.referer)
.field("proxy", &self.proxy)
.field("timeout", &self.timeout)
.field("nodelay", &self.nodelay)
.field("hostname_verification", &self.hostname_verification)
.field("certs_verification", &self.certs_verification)
.field("redirect_policy", &self.redirect_policy)
.finish()
}
}
impl Default for Config {
fn default() -> Self {
Self {
timeout: Some(Duration::from_secs(30)),
connect_timeout: Some(Duration::from_secs(10)),
read_timeout: Some(Duration::from_secs(30)),
headers: Default::default(),
referer: false,
proxy: None,
nodelay: false,
#[cfg(feature = "tls")]
root_certs: vec![],
#[cfg(feature = "tls")]
identity: None,
hostname_verification: false,
certs_verification: false,
#[cfg(feature = "tls")]
tls_sni: true,
#[cfg(feature = "tls")]
min_tls_version: None,
#[cfg(feature = "tls")]
max_tls_version: None,
redirect_policy: Policy::Limit(10),
#[cfg(feature = "cookie")]
cookie_store: None,
}
}
}
#[derive(Clone, Debug)]
struct ClientRef {
timeout: Option<Duration>,
#[cfg(feature = "cookie")]
cookie_store: Option<Arc<dyn cookies::CookieStore>>,
connector: Arc<Connector>,
redirect_policy: Policy,
referer: bool,
header: HeaderMap,
}