monoio_transports/connectors/
tls_connector.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
use std::{fmt::Debug, net::ToSocketAddrs};

use http::Uri;
use monoio::io::{AsyncReadRent, AsyncWriteRent, Split};
use service_async::Param;
use thiserror::Error as ThisError;

use super::{Connector, TransportConnMeta, TransportConnMetadata};
use crate::FromUriError;

#[cfg(not(feature = "native-tls"))]
pub type TlsStream<C> = monoio_rustls::ClientTlsStream<C>;

#[cfg(feature = "native-tls")]
pub type TlsStream<C> = monoio_native_tls::TlsStream<C>;

#[cfg(feature = "native-tls")]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TlsServerName(pub smol_str::SmolStr);
#[cfg(feature = "native-tls")]
pub use monoio_native_tls::TlsConnector as MonoioTlsConnector;
#[cfg(feature = "native-tls")]
pub use monoio_native_tls::TlsError;
#[cfg(not(feature = "native-tls"))]
pub use monoio_rustls::TlsConnector as MonoioTlsConnector;
#[cfg(not(feature = "native-tls"))]
pub use monoio_rustls::TlsError;

#[cfg(feature = "native-tls")]
pub type ServerName<'a> = TlsServerName;

#[cfg(not(feature = "native-tls"))]
pub type ServerName<'a> = rustls::pki_types::ServerName<'a>;

#[cfg(feature = "native-tls")]
impl<T: Into<smol_str::SmolStr>> From<T> for ServerName<'static> {
    #[inline]
    fn from(value: T) -> Self {
        Self(value.into())
    }
}

impl<S> TransportConnMetadata for TlsStream<S> {
    type Metadata = TransportConnMeta;

    fn get_conn_metadata(&self) -> Self::Metadata {
        let mut meta = TransportConnMeta::default();
        meta.set_alpn(self.alpn_protocol());
        meta
    }
}
/// A connector for establishing TLS connections over an inner connector.
///
/// This connector wraps another connector (typically a TCP or Unix socket connector)
/// and adds TLS encryption to the connection. The underlying TLS implentation
/// can be either `rustls` or `native-tls` depending on the feature flags. Set th
/// `native-tls` feature to use the `native-tls` implementation.
#[derive(Clone)]
pub struct TlsConnector<C> {
    inner_connector: C,
    tls_connector: MonoioTlsConnector,
}

impl<C: Debug> std::fmt::Debug for TlsConnector<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "TlsConnector, inner: {:?}", self.inner_connector)
    }
}

impl<C> TlsConnector<C> {
    pub const fn new(inner_connector: C, tls_connector: MonoioTlsConnector) -> Self {
        Self {
            inner_connector,
            tls_connector,
        }
    }

    // Create a new `TlsConnector` with custom ALPN protocols.
    #[cfg(not(feature = "native-tls"))]
    #[inline]
    pub fn new_with_tls_default(inner_connector: C, alpn: Option<Vec<&str>>) -> Self {
        let mut root_store = rustls::RootCertStore::empty();
        root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

        let mut cfg = rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();

        // Set ALPN from client side
        if let Some(alpn) = alpn {
            let alpn: Vec<Vec<u8>> = alpn.iter().map(|a| a.as_bytes().to_vec()).collect();
            cfg.alpn_protocols = alpn;
        }

        TlsConnector::new(inner_connector, cfg.into())
    }

    // Create a new `TlsConnector` with custom ALPN protocols.
    #[cfg(feature = "native-tls")]
    #[inline]
    pub fn new_with_tls_default(inner_connector: C, alpn: Option<Vec<&str>>) -> Self {
        let mut tls_connector = native_tls::TlsConnector::builder();
        if let Some(alpn) = alpn {
            tls_connector.request_alpns(&alpn);
        }
        TlsConnector::new(inner_connector, tls_connector.build().unwrap().into())
    }

    #[inline]
    pub fn inner_connector(&self) -> &C {
        &self.inner_connector
    }

    #[inline]
    pub fn tls_connector(&self) -> &MonoioTlsConnector {
        &self.tls_connector
    }
}

impl<C: Default> Default for TlsConnector<C> {
    /// Create a new `TlsConnector` with the default inner connector.
    /// Additionally, the default ALPN protocols are set to `h2` and `http/1.1`.
    #[inline]
    fn default() -> Self {
        let alpn = Some(vec!["h2", "http/1.1"]);
        TlsConnector::new_with_tls_default(Default::default(), alpn)
    }
}

impl<C, T, CN> Connector<T> for TlsConnector<C>
where
    T: AsRef<ServerName<'static>>,
    for<'a> C: Connector<&'a T, Error = std::io::Error, Connection = CN>,
    CN: AsyncReadRent + AsyncWriteRent,
{
    type Connection = TlsStream<CN>;
    type Error = TlsError;

    #[inline]
    async fn connect(&self, key: T) -> Result<Self::Connection, Self::Error> {
        let stream = self.inner_connector.connect(&key).await?;
        let server_name = key.as_ref();
        #[cfg(not(feature = "native-tls"))]
        let tls_stream = self
            .tls_connector
            .connect(server_name.clone(), stream)
            .await?;
        #[cfg(feature = "native-tls")]
        let tls_stream = self.tls_connector.connect(&server_name.0, stream).await?;
        Ok(tls_stream)
    }
}

/// A unified TLS address that can be either a TCP or Unix address.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct UnifiedTlsAddr {
    pub addr: super::UnifiedL4Addr,
    pub sn: ServerName<'static>,
}

impl Param<ServerName<'static>> for UnifiedTlsAddr {
    #[inline]
    fn param(&self) -> ServerName<'static> {
        self.sn.clone()
    }
}

impl AsRef<ServerName<'static>> for UnifiedTlsAddr {
    #[inline]
    fn as_ref(&self) -> &ServerName<'static> {
        &self.sn
    }
}

impl Param<super::UnifiedL4Addr> for UnifiedTlsAddr {
    #[inline]
    fn param(&self) -> super::UnifiedL4Addr {
        self.addr.clone()
    }
}

impl AsRef<super::UnifiedL4Addr> for UnifiedTlsAddr {
    #[inline]
    fn as_ref(&self) -> &super::UnifiedL4Addr {
        &self.addr
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TcpTlsAddr {
    pub host: smol_str::SmolStr,
    pub port: u16,
    pub sn: ServerName<'static>,
}

impl Param<ServerName<'static>> for TcpTlsAddr {
    #[inline]
    fn param(&self) -> ServerName<'static> {
        self.sn.clone()
    }
}

impl AsRef<ServerName<'static>> for TcpTlsAddr {
    #[inline]
    fn as_ref(&self) -> &ServerName<'static> {
        &self.sn
    }
}

impl ToSocketAddrs for TcpTlsAddr {
    type Iter = <(&'static str, u16) as ToSocketAddrs>::Iter;

    #[inline]
    fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
        (self.host.as_str(), self.port).to_socket_addrs()
    }
}

impl TryFrom<&Uri> for TcpTlsAddr {
    type Error = FromUriError;

    #[inline]
    fn try_from(uri: &Uri) -> Result<Self, Self::Error> {
        let host = match uri.host() {
            Some(a) => a,
            None => return Err(FromUriError::NoAuthority),
        };

        let (tls, default_port) = match uri.scheme() {
            Some(scheme) if scheme == &http::uri::Scheme::HTTP => (false, 80),
            Some(scheme) if scheme == &http::uri::Scheme::HTTPS => (true, 443),
            _ => (false, 0),
        };
        if !tls {
            return Err(FromUriError::UnsupportScheme);
        }
        let host = smol_str::SmolStr::from(host);
        let port = uri.port_u16().unwrap_or(default_port);

        let sn = {
            #[cfg(feature = "native-tls")]
            {
                ServerName::from(host.clone())
            }
            #[cfg(not(feature = "native-tls"))]
            {
                ServerName::try_from(host.to_string())?
            }
        };

        Ok(TcpTlsAddr { host, port, sn })
    }
}

impl TryFrom<Uri> for TcpTlsAddr {
    type Error = FromUriError;

    #[inline]
    fn try_from(value: Uri) -> Result<Self, Self::Error> {
        Self::try_from(&value)
    }
}

#[derive(Debug, Clone)]
pub struct UnifiedConnector(pub TlsConnector<super::UnifiedL4Connector>);

impl UnifiedConnector {
    pub const fn new(
        inner_connector: super::UnifiedL4Connector,
        tls_connector: MonoioTlsConnector,
    ) -> Self {
        Self(TlsConnector::new(inner_connector, tls_connector))
    }

    #[inline]
    pub fn inner_connector(&self) -> &super::UnifiedL4Connector {
        &self.0.inner_connector
    }

    #[inline]
    pub fn tls_connector(&self) -> &MonoioTlsConnector {
        &self.0.tls_connector
    }
}

impl<'a> Connector<&'a UnifiedTlsAddr> for UnifiedConnector {
    type Connection = TlsStream<super::UnifiedL4Stream>;
    type Error = TlsError;

    #[inline]
    async fn connect(&self, key: &'a UnifiedTlsAddr) -> Result<Self::Connection, Self::Error> {
        let sn = &key.sn;
        let addr = &key.addr;
        let stream = self.0.inner_connector.connect(addr).await?;
        #[cfg(not(feature = "native-tls"))]
        let tls_stream = self.0.tls_connector.connect(sn.clone(), stream).await?;
        #[cfg(feature = "native-tls")]
        let tls_stream = self.0.tls_connector.connect(&sn.0, stream).await?;
        Ok(tls_stream)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnifiedAddr {
    pub addr: super::UnifiedL4Addr,
    pub sn: Option<ServerName<'static>>,
}

impl Param<Option<ServerName<'static>>> for UnifiedAddr {
    #[inline]
    fn param(&self) -> Option<ServerName<'static>> {
        self.sn.clone()
    }
}

impl AsRef<Option<ServerName<'static>>> for UnifiedAddr {
    #[inline]
    fn as_ref(&self) -> &Option<ServerName<'static>> {
        &self.sn
    }
}

impl Param<super::UnifiedL4Addr> for UnifiedAddr {
    #[inline]
    fn param(&self) -> super::UnifiedL4Addr {
        self.addr.clone()
    }
}

impl AsRef<super::UnifiedL4Addr> for UnifiedAddr {
    #[inline]
    fn as_ref(&self) -> &super::UnifiedL4Addr {
        &self.addr
    }
}

impl TryFrom<&Uri> for UnifiedAddr {
    type Error = FromUriError;

    #[inline]
    fn try_from(uri: &Uri) -> Result<Self, Self::Error> {
        let host = match uri.host() {
            Some(a) => a.to_string(),
            None => return Err(FromUriError::NoAuthority),
        };

        let (tls, default_port) = match uri.scheme() {
            Some(scheme) if scheme == &http::uri::Scheme::HTTP => (false, 80),
            Some(scheme) if scheme == &http::uri::Scheme::HTTPS => (true, 443),
            _ => (false, 0),
        };
        let port = uri.port_u16().unwrap_or(default_port);

        let l4_addr = super::UnifiedL4Addr::Tcp(
            (host.to_string(), port)
                .to_socket_addrs()?
                .next()
                .ok_or(crate::FromUriError::NoResolve)?,
        );

        let sn = if tls {
            #[cfg(feature = "native-tls")]
            {
                Some(ServerName::from(host))
            }
            #[cfg(not(feature = "native-tls"))]
            {
                Some(ServerName::try_from(host.to_string())?)
            }
        } else {
            None
        };

        Ok(UnifiedAddr { addr: l4_addr, sn })
    }
}

impl TryFrom<Uri> for UnifiedAddr {
    type Error = FromUriError;

    #[inline]
    fn try_from(value: Uri) -> Result<Self, Self::Error> {
        Self::try_from(&value)
    }
}

/// A unified stream that can be either a L4 or TLS stream.
#[derive(Debug)]
pub enum UnifiedStream {
    L4(super::UnifiedL4Stream),
    Tls(TlsStream<super::UnifiedL4Stream>),
}

#[derive(ThisError, Debug)]
pub enum UnifiedError {
    #[error("L4 connect error {0}")]
    L4(std::io::Error),
    #[error("TLS connect error {0}")]
    Tls(TlsError),
}

impl<'a> Connector<&'a UnifiedAddr> for UnifiedConnector {
    type Connection = UnifiedStream;
    type Error = UnifiedError;

    #[inline]
    async fn connect(&self, key: &'a UnifiedAddr) -> Result<Self::Connection, Self::Error> {
        match &key.sn {
            Some(sn) => {
                let addr = &key.addr;
                let stream = self
                    .0
                    .inner_connector
                    .connect(addr)
                    .await
                    .map_err(|e| UnifiedError::Tls(TlsError::from(e)))?;
                #[cfg(not(feature = "native-tls"))]
                let tls_stream = self
                    .0
                    .tls_connector
                    .connect(sn.clone(), stream)
                    .await
                    .map_err(UnifiedError::Tls)?;
                #[cfg(feature = "native-tls")]
                let tls_stream = self
                    .0
                    .tls_connector
                    .connect(&sn.0, stream)
                    .await
                    .map_err(UnifiedError::Tls)?;
                Ok(UnifiedStream::Tls(tls_stream))
            }
            None => {
                let addr = &key.addr;
                let stream = self
                    .0
                    .inner_connector
                    .connect(addr)
                    .await
                    .map_err(UnifiedError::L4)?;
                Ok(UnifiedStream::L4(stream))
            }
        }
    }
}

impl AsyncReadRent for UnifiedStream {
    #[inline]
    async fn read<T: monoio::buf::IoBufMut>(&mut self, buf: T) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedStream::L4(inner) => inner.read(buf).await,
            UnifiedStream::Tls(inner) => inner.read(buf).await,
        }
    }

    #[inline]
    async fn readv<T: monoio::buf::IoVecBufMut>(&mut self, buf: T) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedStream::L4(inner) => inner.readv(buf).await,
            UnifiedStream::Tls(inner) => inner.readv(buf).await,
        }
    }
}

impl AsyncWriteRent for UnifiedStream {
    #[inline]
    async fn write<T: monoio::buf::IoBuf>(&mut self, buf: T) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedStream::L4(inner) => inner.write(buf).await,
            UnifiedStream::Tls(inner) => inner.write(buf).await,
        }
    }

    #[inline]
    async fn writev<T: monoio::buf::IoVecBuf>(
        &mut self,
        buf_vec: T,
    ) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedStream::L4(inner) => inner.writev(buf_vec).await,
            UnifiedStream::Tls(inner) => inner.writev(buf_vec).await,
        }
    }

    #[inline]
    async fn flush(&mut self) -> std::io::Result<()> {
        match self {
            UnifiedStream::L4(inner) => inner.flush().await,
            UnifiedStream::Tls(inner) => inner.flush().await,
        }
    }

    #[inline]
    async fn shutdown(&mut self) -> std::io::Result<()> {
        match self {
            UnifiedStream::L4(inner) => inner.shutdown().await,
            UnifiedStream::Tls(inner) => inner.shutdown().await,
        }
    }
}

unsafe impl Split for UnifiedStream {}