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
use crate::common::tls_state::TlsState;
use crate::server;
use futures_io::{AsyncRead, AsyncWrite};
use rustls::{ServerConfig, ServerConnection};
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
/// The TLS accepting part. The acceptor drives
/// the server side of the TLS handshake process. It works
/// on any asynchronous stream.
///
/// It provides a simple interface (`accept`), returning a future
/// that will resolve when the handshake process completed. On
/// success, it will hand you an async `TLSStream`.
///
/// ## Example
///
/// See /examples/server for an example.
#[derive(Clone)]
pub struct TlsAcceptor {
inner: Arc<ServerConfig>,
}
impl TlsAcceptor {
/// Accept a client connections. `stream` can be any type implementing `AsyncRead` and `AsyncWrite`,
/// such as TcpStreams or Unix domain sockets.
///
/// Otherwise, it will return a `Accept` Future, representing the Acceptance part of a
/// Tls handshake. It will resolve when the handshake is over.
#[inline]
pub fn accept<IO>(&self, stream: IO) -> Accept<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
self.accept_with(stream, |_| ())
}
// Currently private, as exposing ServerConnections exposes rusttls
fn accept_with<IO, F>(&self, stream: IO, f: F) -> Accept<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
F: FnOnce(&mut ServerConnection),
{
let mut conn = match ServerConnection::new(self.inner.clone()) {
Ok(conn) => conn,
Err(_) => {
return Accept(server::MidHandshake::End);
}
};
f(&mut conn);
Accept(server::MidHandshake::Handshaking(server::TlsStream {
conn,
io: stream,
state: TlsState::Stream,
}))
}
}
/// Future returned from `TlsAcceptor::accept` which will resolve
/// once the accept handshake has finished.
pub struct Accept<IO>(server::MidHandshake<IO>);
impl<IO: AsyncRead + AsyncWrite + Unpin> Future for Accept<IO> {
type Output = io::Result<server::TlsStream<IO>>;
#[inline]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.0).poll(cx)
}
}
impl From<Arc<ServerConfig>> for TlsAcceptor {
fn from(inner: Arc<ServerConfig>) -> TlsAcceptor {
TlsAcceptor { inner }
}
}
impl From<ServerConfig> for TlsAcceptor {
fn from(inner: ServerConfig) -> TlsAcceptor {
TlsAcceptor {
inner: Arc::new(inner),
}
}
}