Skip to main content

actix_tls/accept/
openssl.rs

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