monoio_native_tls/
server.rs

1use std::fmt;
2
3use monoio::io::{AsyncReadRent, AsyncWriteRent};
4
5use crate::{
6    utils::{handshake, IOWrapper},
7    TlsError, TlsStream,
8};
9
10/// A wrapper around a `native_tls::TlsAcceptor`, providing an async `accept`
11/// method.
12#[derive(Clone)]
13pub struct TlsAcceptor {
14    inner: native_tls::TlsAcceptor,
15    read_buffer: Option<usize>,
16    write_buffer: Option<usize>,
17}
18
19impl TlsAcceptor {
20    /// Accepts a new client connection with the provided stream.
21    ///
22    /// This function will internally call `TlsAcceptor::accept` to connect
23    /// the stream and returns a future representing the resolution of the
24    /// connection operation. The returned future will resolve to either
25    /// `TlsStream<S>` or `Error` depending if it's successful or not.
26    ///
27    /// This is typically used after a new socket has been accepted from a
28    /// `TcpListener`. That socket is then passed to this function to perform
29    /// the server half of accepting a client connection.
30    pub async fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, TlsError>
31    where
32        S: AsyncReadRent + AsyncWriteRent,
33    {
34        let io = IOWrapper::new_with_buffer_size(stream, self.read_buffer, self.write_buffer);
35        handshake(move |s_wrap| self.inner.accept(s_wrap), io).await
36    }
37
38    pub fn read_buffer(mut self, size: Option<usize>) -> Self {
39        self.read_buffer = size;
40        self
41    }
42
43    pub fn write_buffer(mut self, size: Option<usize>) -> Self {
44        self.write_buffer = size;
45        self
46    }
47}
48
49impl fmt::Debug for TlsAcceptor {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.debug_struct("TlsAcceptor").finish()
52    }
53}
54
55impl From<native_tls::TlsAcceptor> for TlsAcceptor {
56    fn from(inner: native_tls::TlsAcceptor) -> TlsAcceptor {
57        TlsAcceptor {
58            inner,
59            read_buffer: None,
60            write_buffer: None,
61        }
62    }
63}