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
use futures_rustls::{
    rustls::{ServerConfig, ServerConnection},
    server::TlsStream,
    TlsAcceptor,
};
use std::{
    fmt::{Debug, Formatter},
    io,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};
use trillium_server_common::{async_trait, Acceptor, AsyncRead, AsyncWrite, Transport};

use crate::crypto_provider;

/**
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("Rustls").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 cert chain (pem) and private key.

    See
    [`ConfigBuilder::with_single_cert`][`crate::rustls::ConfigBuilder::with_single_cert`]
    for accepted formats. If you need to customize the
    [`ServerConfig`], use ServerConfig's Into RustlsAcceptor, eg

    ```rust,ignore
    use trillium_rustls::{rustls::ServerConfig, RustlsAcceptor};
    let rustls_acceptor: RustlsAcceptor = ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(certs, private_key)
        .expect("could not build rustls ServerConfig")
        .into();
    ```

    # Example

    ```rust,no_run
    use trillium_rustls::RustlsAcceptor;
    const KEY: &[u8] = include_bytes!("../examples/key.pem");
    const CERT: &[u8] = include_bytes!("../examples/cert.pem");
    let rustls_acceptor = RustlsAcceptor::from_single_cert(CERT, KEY);
    ```
    */
    pub fn from_single_cert(cert: &[u8], key: &[u8]) -> Self {
        use std::io::Cursor;

        let cert_chain = rustls_pemfile::certs(&mut Cursor::new(cert))
            .collect::<Result<_, _>>()
            .expect("could not read certificate");

        let key_der = rustls_pemfile::private_key(&mut Cursor::new(key))
            .expect("could not read key pemfile")
            .expect("no private key found in `key`");

        ServerConfig::builder_with_provider(crypto_provider())
            .with_safe_default_protocol_versions()
            .expect("crypto provider did not support safe default protocol versions")
            .with_no_client_auth()
            .with_single_cert(cert_chain, key_der)
            .expect("could not create a rustls ServerConfig from the supplied cert and key")
            .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)
    }
}

/// Transport for rustls server acceptor
#[derive(Debug)]
pub struct RustlsServerTransport<T>(TlsStream<T>);

impl<T: AsyncRead + AsyncWrite + Unpin> AsyncRead for RustlsServerTransport<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.0).poll_read(cx, buf)
    }
}

impl<T: AsyncWrite + AsyncRead + Unpin> AsyncWrite for RustlsServerTransport<T> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.0).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_flush(cx)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_close(cx)
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[io::IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.0).poll_write_vectored(cx, bufs)
    }
}

impl<T: Transport> Transport for RustlsServerTransport<T> {
    fn peer_addr(&self) -> io::Result<Option<std::net::SocketAddr>> {
        self.inner_transport().peer_addr()
    }
}

impl<T> RustlsServerTransport<T> {
    /// access the contained transport type (eg TcpStream)
    pub fn inner_transport(&self) -> &T {
        self.0.get_ref().0
    }

    /// mutably access the contained transport type (eg TcpStream)
    pub fn inner_transport_mut(&mut self) -> &mut T {
        self.0.get_mut().0
    }
}

impl<T> AsRef<ServerConnection> for RustlsServerTransport<T> {
    fn as_ref(&self) -> &ServerConnection {
        self.0.get_ref().1
    }
}

impl<T> AsMut<ServerConnection> for RustlsServerTransport<T> {
    fn as_mut(&mut self) -> &mut ServerConnection {
        self.0.get_mut().1
    }
}

impl<T> From<TlsStream<T>> for RustlsServerTransport<T> {
    fn from(value: TlsStream<T>) -> Self {
        Self(value)
    }
}

impl<T> From<RustlsServerTransport<T>> for TlsStream<T> {
    fn from(RustlsServerTransport(value): RustlsServerTransport<T>) -> Self {
        value
    }
}

#[async_trait]
impl<Input> Acceptor<Input> for RustlsAcceptor
where
    Input: Transport,
{
    type Output = RustlsServerTransport<Input>;
    type Error = io::Error;
    async fn accept(&self, input: Input) -> Result<Self::Output, Self::Error> {
        self.0.accept(input).await.map(RustlsServerTransport)
    }
}