actix_tls/accept/
openssl.rs

1//! `openssl` based TLS acceptor service.
2//!
3//! See [`Acceptor`] for main service factory docs.
4
5use std::{
6    convert::Infallible,
7    future::Future,
8    io::{self, IoSlice},
9    pin::Pin,
10    task::{Context, Poll},
11    time::Duration,
12};
13
14use actix_rt::{
15    net::{ActixStream, Ready},
16    time::{sleep, Sleep},
17};
18use actix_service::{Service, ServiceFactory};
19use actix_utils::{
20    counter::{Counter, CounterGuard},
21    future::{ready, Ready as FutReady},
22};
23use openssl::ssl::{Error, Ssl, SslAcceptor};
24use pin_project_lite::pin_project;
25use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
26
27use super::{TlsError, DEFAULT_TLS_HANDSHAKE_TIMEOUT, MAX_CONN_COUNTER};
28
29pub mod reexports {
30    //! Re-exports from `openssl` that are useful for acceptors.
31
32    pub use openssl::ssl::{
33        AlpnError, Error, HandshakeError, Ssl, SslAcceptor, SslAcceptorBuilder,
34    };
35}
36
37/// Wraps an `openssl` based async TLS stream in order to implement [`ActixStream`].
38pub struct TlsStream<IO>(tokio_openssl::SslStream<IO>);
39
40impl_more::impl_from!(<IO> in tokio_openssl::SslStream<IO> => TlsStream<IO>);
41impl_more::impl_deref_and_mut!(<IO> in TlsStream<IO> => tokio_openssl::SslStream<IO>);
42
43impl<IO: ActixStream> AsyncRead for TlsStream<IO> {
44    fn poll_read(
45        self: Pin<&mut Self>,
46        cx: &mut Context<'_>,
47        buf: &mut ReadBuf<'_>,
48    ) -> Poll<io::Result<()>> {
49        Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
50    }
51}
52
53impl<IO: ActixStream> AsyncWrite for TlsStream<IO> {
54    fn poll_write(
55        self: Pin<&mut Self>,
56        cx: &mut Context<'_>,
57        buf: &[u8],
58    ) -> Poll<io::Result<usize>> {
59        Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
60    }
61
62    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
63        Pin::new(&mut **self.get_mut()).poll_flush(cx)
64    }
65
66    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
67        Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
68    }
69
70    fn poll_write_vectored(
71        self: Pin<&mut Self>,
72        cx: &mut Context<'_>,
73        bufs: &[IoSlice<'_>],
74    ) -> Poll<io::Result<usize>> {
75        Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
76    }
77
78    fn is_write_vectored(&self) -> bool {
79        (**self).is_write_vectored()
80    }
81}
82
83impl<IO: ActixStream> ActixStream for TlsStream<IO> {
84    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
85        IO::poll_read_ready((**self).get_ref(), cx)
86    }
87
88    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
89        IO::poll_write_ready((**self).get_ref(), cx)
90    }
91}
92
93/// Accept TLS connections via the `openssl` crate.
94pub struct Acceptor {
95    acceptor: SslAcceptor,
96    handshake_timeout: Duration,
97}
98
99impl Acceptor {
100    /// Create `openssl` based acceptor service factory.
101    #[inline]
102    pub fn new(acceptor: SslAcceptor) -> Self {
103        Acceptor {
104            acceptor,
105            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
106        }
107    }
108
109    /// Limit the amount of time that the acceptor will wait for a TLS handshake to complete.
110    ///
111    /// Default timeout is 3 seconds.
112    pub fn set_handshake_timeout(&mut self, handshake_timeout: Duration) -> &mut Self {
113        self.handshake_timeout = handshake_timeout;
114        self
115    }
116}
117
118impl Clone for Acceptor {
119    #[inline]
120    fn clone(&self) -> Self {
121        Self {
122            acceptor: self.acceptor.clone(),
123            handshake_timeout: self.handshake_timeout,
124        }
125    }
126}
127
128impl<IO: ActixStream> ServiceFactory<IO> for Acceptor {
129    type Response = TlsStream<IO>;
130    type Error = TlsError<Error, Infallible>;
131    type Config = ();
132    type Service = AcceptorService;
133    type InitError = ();
134    type Future = FutReady<Result<Self::Service, Self::InitError>>;
135
136    fn new_service(&self, _: ()) -> Self::Future {
137        let res = MAX_CONN_COUNTER.with(|conns| {
138            Ok(AcceptorService {
139                acceptor: self.acceptor.clone(),
140                conns: conns.clone(),
141                handshake_timeout: self.handshake_timeout,
142            })
143        });
144
145        ready(res)
146    }
147}
148
149/// OpenSSL based acceptor service.
150pub struct AcceptorService {
151    acceptor: SslAcceptor,
152    conns: Counter,
153    handshake_timeout: Duration,
154}
155
156impl<IO: ActixStream> Service<IO> for AcceptorService {
157    type Response = TlsStream<IO>;
158    type Error = TlsError<Error, Infallible>;
159    type Future = AcceptFut<IO>;
160
161    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
162        if self.conns.available(ctx) {
163            Poll::Ready(Ok(()))
164        } else {
165            Poll::Pending
166        }
167    }
168
169    fn call(&self, io: IO) -> Self::Future {
170        let ssl_ctx = self.acceptor.context();
171        let ssl = Ssl::new(ssl_ctx).expect("Provided SSL acceptor was invalid.");
172
173        AcceptFut {
174            _guard: self.conns.get(),
175            timeout: sleep(self.handshake_timeout),
176            stream: Some(tokio_openssl::SslStream::new(ssl, io).unwrap()),
177        }
178    }
179}
180
181pin_project! {
182    /// Accept future for OpenSSL service.
183    #[doc(hidden)]
184    pub struct AcceptFut<IO: ActixStream> {
185        stream: Option<tokio_openssl::SslStream<IO>>,
186        #[pin]
187        timeout: Sleep,
188        _guard: CounterGuard,
189    }
190}
191
192impl<IO: ActixStream> Future for AcceptFut<IO> {
193    type Output = Result<TlsStream<IO>, TlsError<Error, Infallible>>;
194
195    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
196        let this = self.project();
197
198        match Pin::new(this.stream.as_mut().unwrap()).poll_accept(cx) {
199            Poll::Ready(Ok(())) => Poll::Ready(Ok(this
200                .stream
201                .take()
202                .expect("Acceptor should not be polled after it has completed.")
203                .into())),
204            Poll::Ready(Err(err)) => Poll::Ready(Err(TlsError::Tls(err))),
205            Poll::Pending => this.timeout.poll(cx).map(|_| Err(TlsError::Timeout)),
206        }
207    }
208}