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
use futures_util::FutureExt;
use hyper::client::connect::{self, Connect};
#[cfg(feature = "tokio-runtime")]
use hyper::client::HttpConnector;
use rustls::{ClientConfig, Session};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::{fmt, io};
use tokio_rustls::TlsConnector;
use webpki::DNSNameRef;
use crate::stream::MaybeHttpsStream;
#[derive(Clone)]
pub struct HttpsConnector<T> {
http: T,
tls_config: Arc<ClientConfig>,
}
#[cfg(feature = "tokio-runtime")]
impl HttpsConnector<HttpConnector> {
pub fn new() -> Self {
let mut http = HttpConnector::new();
http.enforce_http(false);
let mut config = ClientConfig::new();
config
.root_store
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
config.ct_logs = Some(&ct_logs::LOGS);
HttpsConnector {
http,
tls_config: Arc::new(config),
}
}
}
impl<T> fmt::Debug for HttpsConnector<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("HttpsConnector").finish()
}
}
impl<T> From<(T, ClientConfig)> for HttpsConnector<T> {
fn from(args: (T, ClientConfig)) -> Self {
HttpsConnector {
http: args.0,
tls_config: Arc::new(args.1),
}
}
}
impl<T> From<(T, Arc<ClientConfig>)> for HttpsConnector<T> {
fn from(args: (T, Arc<ClientConfig>)) -> Self {
HttpsConnector {
http: args.0,
tls_config: args.1,
}
}
}
impl<T> Connect for HttpsConnector<T>
where
T: Connect<Error = io::Error>,
T::Transport: 'static,
T::Future: 'static,
{
type Transport = MaybeHttpsStream<T::Transport>;
type Error = io::Error;
type Future = Pin<
Box<
dyn Future<
Output = Result<
(MaybeHttpsStream<T::Transport>, connect::Connected),
io::Error,
>,
> + Send,
>,
>;
fn connect(&self, dst: connect::Destination) -> Self::Future {
let is_https = dst.scheme() == "https";
if !is_https {
let connecting_future = self.http.connect(dst);
let f = async move {
let (tcp, conn) = connecting_future.await?;
Ok((MaybeHttpsStream::Http(tcp), conn))
};
f.boxed()
} else {
let cfg = self.tls_config.clone();
let hostname = dst.host().to_string();
let connecting_future = self.http.connect(dst);
let f = async move {
let (tcp, conn) = connecting_future.await?;
let connector = TlsConnector::from(cfg);
let dnsname = DNSNameRef::try_from_ascii_str(&hostname)
.map_err(|_| io::Error::new(io::ErrorKind::Other, "invalid dnsname"))?;
let tls = connector
.connect(dnsname, tcp)
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let connected = if tls.get_ref().1.get_alpn_protocol() == Some(b"h2") {
conn.negotiated_h2()
} else {
conn
};
Ok((MaybeHttpsStream::Https(tls), connected))
};
f.boxed()
}
}
}