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
use hyper::{client::connect::Connection, service::Service, Uri};
use rustls::ClientConfig;
use std::{
fmt,
future::Future,
io,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_rustls::TlsConnector;
use webpki::DNSNameRef;
use super::MaybeHttpsStream;
use crate::{new_trust_dns_http_connector, TrustDnsHttpConnector};
type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Clone)]
pub struct HttpsConnector<T> {
force_https: bool,
http: T,
tls_config: Arc<ClientConfig>,
}
impl HttpsConnector<TrustDnsHttpConnector> {
#[cfg(feature = "rustls-native")]
#[must_use]
pub fn with_native_roots() -> Self {
let mut config = ClientConfig::new();
config.root_store = match rustls_native_certs::load_native_certs() {
Ok(store) => store,
Err((Some(store), err)) => {
log::warn!("Could not load all certificates: {:?}", err);
store
}
Err((None, err)) => Err(err).expect("cannot access native cert store"),
};
if config.root_store.is_empty() {
panic!("no CA certificates found");
}
Self::build(config)
}
#[cfg(feature = "webpki-roots")]
#[must_use]
pub fn with_webpki_roots() -> Self {
let mut config = ClientConfig::new();
config
.root_store
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
Self::build(config)
}
pub fn https_only(&mut self, enable: bool) {
self.force_https = enable;
}
fn build(mut config: ClientConfig) -> Self {
let mut http = new_trust_dns_http_connector();
http.enforce_http(false);
config.alpn_protocols.clear();
#[cfg(feature = "http2")]
{
config.alpn_protocols.push(b"h2".to_vec());
}
#[cfg(feature = "http1")]
{
config.alpn_protocols.push(b"http/1.1".to_vec());
}
config.ct_logs = Some(&ct_logs::LOGS);
(http, config).into()
}
}
impl<T> fmt::Debug for HttpsConnector<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("HttpsConnector")
.field("force_https", &self.force_https)
.finish()
}
}
impl<H, C> From<(H, C)> for HttpsConnector<H>
where
C: Into<Arc<ClientConfig>>,
{
fn from((http, cfg): (H, C)) -> Self {
HttpsConnector {
force_https: false,
http,
tls_config: cfg.into(),
}
}
}
impl<T> Service<Uri> for HttpsConnector<T>
where
T: Service<Uri>,
T::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static,
T::Future: Send + 'static,
T::Error: Into<BoxError>,
{
type Response = MaybeHttpsStream<T::Response>;
type Error = BoxError;
#[allow(clippy::type_complexity)]
type Future =
Pin<Box<dyn Future<Output = Result<MaybeHttpsStream<T::Response>, BoxError>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self.http.poll_ready(cx) {
Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
Poll::Pending => Poll::Pending,
}
}
fn call(&mut self, dst: Uri) -> Self::Future {
let is_https = dst.scheme_str() == Some("https");
if is_https {
let cfg = self.tls_config.clone();
let hostname = dst.host().unwrap_or_default().to_string();
let connecting_future = self.http.call(dst);
let f = async move {
let tcp = connecting_future.await.map_err(Into::into)?;
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))?;
Ok(MaybeHttpsStream::Https(tls))
};
Box::pin(f)
} else if self.force_https {
let err = io::Error::new(io::ErrorKind::Other, "https required but URI was not https");
Box::pin(async move { Err(err.into()) })
} else {
let connecting_future = self.http.call(dst);
let f = async move {
let tcp = connecting_future.await.map_err(Into::into)?;
Ok(MaybeHttpsStream::Http(tcp))
};
Box::pin(f)
}
}
}