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
use std::{convert::TryFrom, future::Future, io, pin::Pin, task::Context, task::Poll};

pub use ntex_tls::rustls::TlsFilter;
pub use tls_rustls::{ClientConfig, ServerName};

use ntex_tls::rustls::TlsConnector;

use crate::io::{utils::Boxed, Base, Io};
use crate::service::{Service, ServiceFactory};
use crate::util::{PoolId, Ready};

use super::{Address, Connect, ConnectError, Connector as BaseConnector};

/// Rustls connector factory
pub struct Connector<T> {
    connector: BaseConnector<T>,
    inner: TlsConnector,
}

impl<T> From<std::sync::Arc<ClientConfig>> for Connector<T> {
    fn from(cfg: std::sync::Arc<ClientConfig>) -> Self {
        Connector {
            inner: TlsConnector::new(cfg),
            connector: BaseConnector::default(),
        }
    }
}

impl<T> Connector<T> {
    pub fn new(config: ClientConfig) -> Self {
        Connector {
            inner: TlsConnector::new(std::sync::Arc::new(config)),
            connector: BaseConnector::default(),
        }
    }

    /// Set memory pool.
    ///
    /// Use specified memory pool for memory allocations. By default P0
    /// memory pool is used.
    pub fn memory_pool(self, id: PoolId) -> Self {
        Self {
            connector: self.connector.memory_pool(id),
            inner: self.inner,
        }
    }
}

impl<T: Address + 'static> Connector<T> {
    /// Resolve and connect to remote host
    pub fn connect<U>(
        &self,
        message: U,
    ) -> impl Future<Output = Result<Io<TlsFilter<Base>>, ConnectError>>
    where
        Connect<T>: From<U>,
    {
        let req = Connect::from(message);
        let host = req.host().split(':').next().unwrap().to_owned();
        let conn = self.connector.call(req);
        let connector = self.inner.clone();

        async move {
            let io = conn.await?;
            trace!("SSL Handshake start for: {:?}", host);

            let host = ServerName::try_from(host.as_str())
                .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}", e)))?;
            let connector = connector.server_name(host.clone());

            match io.add_filter(connector).await {
                Ok(io) => {
                    trace!("TLS Handshake success: {:?}", &host);
                    Ok(io)
                }
                Err(e) => {
                    trace!("TLS Handshake error: {:?}", e);
                    Err(io::Error::new(io::ErrorKind::Other, format!("{}", e)).into())
                }
            }
        }
    }

    /// Produce sealed io stream (IoBoxed)
    pub fn seal(self) -> Boxed<Connector<T>, Connect<T>> {
        Boxed::new(self)
    }
}

impl<T> Clone for Connector<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            connector: self.connector.clone(),
        }
    }
}

impl<T: Address, C> ServiceFactory<Connect<T>, C> for Connector<T> {
    type Response = Io<TlsFilter<Base>>;
    type Error = ConnectError;
    type Service = Connector<T>;
    type InitError = ();
    type Future = Ready<Self::Service, Self::InitError>;

    #[inline]
    fn new_service(&self, _: C) -> Self::Future {
        Ready::Ok(self.clone())
    }
}

impl<T: Address> Service<Connect<T>> for Connector<T> {
    type Response = Io<TlsFilter<Base>>;
    type Error = ConnectError;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    #[inline]
    fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&self, req: Connect<T>) -> Self::Future {
        Box::pin(self.connect(req))
    }
}

#[cfg(test)]
mod tests {
    use tls_rustls::{OwnedTrustAnchor, RootCertStore};

    use super::*;
    use crate::service::{Service, ServiceFactory};

    #[crate::rt_test]
    async fn test_rustls_connect() {
        let server = crate::server::test_server(|| {
            crate::service::fn_service(|_| async { Ok::<_, ()>(()) })
        });

        let mut cert_store = RootCertStore::empty();
        cert_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(
            |ta| {
                OwnedTrustAnchor::from_subject_spki_name_constraints(
                    ta.subject,
                    ta.spki,
                    ta.name_constraints,
                )
            },
        ));
        let config = ClientConfig::builder()
            .with_safe_defaults()
            .with_root_certificates(cert_store)
            .with_no_client_auth();
        let factory = Connector::new(config).clone();

        let srv = factory.new_service(()).await.unwrap();
        let result = srv
            .call(Connect::new("www.rust-lang.org").set_addr(Some(server.addr())))
            .await;
        assert!(result.is_err());
    }
}