hyper_rustls/
connector.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::task::{Context, Poll};
5use std::{fmt, io};
6
7use hyper::{client::connect::Connection, service::Service, Uri};
8use tokio::io::{AsyncRead, AsyncWrite};
9use tokio_rustls::TlsConnector;
10
11use crate::stream::MaybeHttpsStream;
12
13pub(crate) mod builder;
14
15type BoxError = Box<dyn std::error::Error + Send + Sync>;
16
17/// A Connector for the `https` scheme.
18#[derive(Clone)]
19pub struct HttpsConnector<T> {
20    force_https: bool,
21    http: T,
22    tls_config: Arc<rustls::ClientConfig>,
23    override_server_name: Option<String>,
24}
25
26impl<T> HttpsConnector<T> {
27    /// Force the use of HTTPS when connecting.
28    ///
29    /// If a URL is not `https` when connecting, an error is returned.
30    pub fn enforce_https(&mut self) {
31        self.force_https = true;
32    }
33}
34
35impl<T> fmt::Debug for HttpsConnector<T> {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        f.debug_struct("HttpsConnector")
38            .field("force_https", &self.force_https)
39            .finish()
40    }
41}
42
43impl<H, C> From<(H, C)> for HttpsConnector<H>
44where
45    C: Into<Arc<rustls::ClientConfig>>,
46{
47    fn from((http, cfg): (H, C)) -> Self {
48        Self {
49            force_https: false,
50            http,
51            tls_config: cfg.into(),
52            override_server_name: None,
53        }
54    }
55}
56
57impl<T> Service<Uri> for HttpsConnector<T>
58where
59    T: Service<Uri>,
60    T::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static,
61    T::Future: Send + 'static,
62    T::Error: Into<BoxError>,
63{
64    type Response = MaybeHttpsStream<T::Response>;
65    type Error = BoxError;
66
67    #[allow(clippy::type_complexity)]
68    type Future =
69        Pin<Box<dyn Future<Output = Result<MaybeHttpsStream<T::Response>, BoxError>> + Send>>;
70
71    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
72        match self.http.poll_ready(cx) {
73            Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
74            Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
75            Poll::Pending => Poll::Pending,
76        }
77    }
78
79    fn call(&mut self, dst: Uri) -> Self::Future {
80        // dst.scheme() would need to derive Eq to be matchable;
81        // use an if cascade instead
82        if let Some(sch) = dst.scheme() {
83            if sch == &http::uri::Scheme::HTTP && !self.force_https {
84                let connecting_future = self.http.call(dst);
85
86                let f = async move {
87                    let tcp = connecting_future
88                        .await
89                        .map_err(Into::into)?;
90
91                    Ok(MaybeHttpsStream::Http(tcp))
92                };
93                Box::pin(f)
94            } else if sch == &http::uri::Scheme::HTTPS {
95                let cfg = self.tls_config.clone();
96                let mut hostname = match self.override_server_name.as_deref() {
97                    Some(h) => h,
98                    None => dst.host().unwrap_or_default(),
99                };
100
101                // Remove square brackets around IPv6 address.
102                if let Some(trimmed) = hostname
103                    .strip_prefix('[')
104                    .and_then(|h| h.strip_suffix(']'))
105                {
106                    hostname = trimmed;
107                }
108
109                let hostname = match rustls::ServerName::try_from(hostname) {
110                    Ok(dnsname) => dnsname,
111                    Err(_) => {
112                        let err = io::Error::new(io::ErrorKind::Other, "invalid dnsname");
113                        return Box::pin(async move { Err(Box::new(err).into()) });
114                    }
115                };
116                let connecting_future = self.http.call(dst);
117
118                let f = async move {
119                    let tcp = connecting_future
120                        .await
121                        .map_err(Into::into)?;
122                    let connector = TlsConnector::from(cfg);
123                    let tls = connector
124                        .connect(hostname, tcp)
125                        .await
126                        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
127                    Ok(MaybeHttpsStream::Https(tls))
128                };
129                Box::pin(f)
130            } else {
131                let err =
132                    io::Error::new(io::ErrorKind::Other, format!("Unsupported scheme {}", sch));
133                Box::pin(async move { Err(err.into()) })
134            }
135        } else {
136            let err = io::Error::new(io::ErrorKind::Other, "Missing scheme");
137            Box::pin(async move { Err(err.into()) })
138        }
139    }
140}