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
use async_rustls::{server::TlsStream, TlsAcceptor};
use rustls::{
    internal::pemfile::{certs, pkcs8_private_keys},
    NoClientAuth, ServerConfig,
};
use std::{
    fmt::{Debug, Formatter},
    io::{BufReader, Error, Result},
    sync::Arc,
};
use trillium_tls_common::{async_trait, Acceptor, AsyncRead, AsyncWrite};

/**
trillium [`Acceptor`] for Rustls
*/

#[derive(Clone)]
pub struct RustlsAcceptor(TlsAcceptor);
impl Debug for RustlsAcceptor {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("RustTls").field(&"<<TlsAcceptor>>").finish()
    }
}

impl RustlsAcceptor {
    /**
    build a new RustlsAcceptor from a [`ServerConfig`] or a [`TlsAcceptor`]
    */
    pub fn new(t: impl Into<Self>) -> Self {
        t.into()
    }

    /**
    build a new RustlsAcceptor from a pkcs8 cert and key
    */
    pub fn from_pkcs8(cert: &[u8], key: &[u8]) -> Self {
        let mut config = ServerConfig::new(NoClientAuth::new());

        config
            .set_single_cert(
                certs(&mut BufReader::new(cert)).unwrap(),
                pkcs8_private_keys(&mut BufReader::new(key))
                    .unwrap()
                    .remove(0),
            )
            .expect("could not create a rustls ServerConfig from the supplied cert and key");

        config.into()
    }
}

impl From<ServerConfig> for RustlsAcceptor {
    fn from(sc: ServerConfig) -> Self {
        Self(Arc::new(sc).into())
    }
}

impl From<TlsAcceptor> for RustlsAcceptor {
    fn from(ta: TlsAcceptor) -> Self {
        Self(ta)
    }
}

#[async_trait]
impl<Input> Acceptor<Input> for RustlsAcceptor
where
    Input: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
{
    type Output = TlsStream<Input>;
    type Error = Error;
    async fn accept(&self, input: Input) -> Result<Self::Output> {
        self.0.accept(input).await
    }
}