hyper_server/tls_openssl/future.rs
1//! Future types.
2//!
3//! This module provides the futures and supporting types for integrating OpenSSL with a hyper/tokio HTTP/TLS server.
4//! `OpenSSLAcceptorFuture` is the main public-facing type which wraps around the core logic of establishing an SSL/TLS
5//! connection.
6
7use super::OpenSSLConfig;
8use pin_project_lite::pin_project;
9use std::io::{Error, ErrorKind};
10use std::time::Duration;
11use std::{
12 fmt,
13 future::Future,
14 io,
15 pin::Pin,
16 task::{Context, Poll},
17};
18use tokio::io::{AsyncRead, AsyncWrite};
19use tokio::time::{timeout, Timeout};
20
21use openssl::ssl::Ssl;
22use tokio_openssl::SslStream;
23
24// The OpenSSLAcceptorFuture encapsulates the asynchronous logic of accepting an SSL/TLS connection.
25pin_project! {
26 /// A Future for establishing an SSL/TLS connection using `OpenSSLAcceptor`.
27 ///
28 /// This wraps around the process of asynchronously establishing an SSL/TLS connection via OpenSSL.
29 /// It waits for the inner non-TLS connection to be established, and then handles the TLS handshake.
30 pub struct OpenSSLAcceptorFuture<F, I, S> {
31 #[pin]
32 inner: AcceptFuture<F, I, S>, // Inner future which manages the state machine of accepting connections.
33 config: Option<OpenSSLConfig>, // The SSL/TLS configuration to use for the handshake.
34 }
35}
36
37impl<F, I, S> OpenSSLAcceptorFuture<F, I, S> {
38 /// Constructs a new `OpenSSLAcceptorFuture`.
39 ///
40 /// # Arguments
41 /// - `future`: The initial future that handles the non-TLS accept phase.
42 /// - `config`: SSL/TLS configuration.
43 /// - `handshake_timeout`: Maximum duration allowed for the TLS handshake.
44 pub(crate) fn new(future: F, config: OpenSSLConfig, handshake_timeout: Duration) -> Self {
45 let inner = AcceptFuture::InnerAccepting {
46 future,
47 handshake_timeout,
48 };
49 let config = Some(config);
50
51 Self { inner, config }
52 }
53}
54
55impl<F, I, S> fmt::Debug for OpenSSLAcceptorFuture<F, I, S> {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 f.debug_struct("OpenSSLAcceptorFuture").finish()
58 }
59}
60
61// A future for performing the SSL/TLS handshake using an `SslStream`.
62pin_project! {
63 struct TlsAccept<I> {
64 #[pin]
65 tls_stream: Option<SslStream<I>>, // The SSL/TLS stream on which the handshake will be performed.
66 }
67}
68
69impl<I> Future for TlsAccept<I>
70where
71 I: AsyncRead + AsyncWrite + Unpin, // The inner type must support asynchronous reading and writing.
72{
73 type Output = io::Result<SslStream<I>>; // The result will be an `SslStream` if the handshake is successful.
74
75 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
76 let mut this = self.project();
77
78 match this
79 .tls_stream
80 .as_mut()
81 .as_pin_mut()
82 .map(|inner| inner.poll_accept(cx))
83 .expect("tlsaccept polled after ready")
84 {
85 Poll::Ready(Ok(())) => {
86 let tls_stream = this.tls_stream.take().expect("tls stream vanished?");
87 Poll::Ready(Ok(tls_stream))
88 }
89 Poll::Ready(Err(e)) => Poll::Ready(Err(Error::new(ErrorKind::Other, e))),
90 Poll::Pending => Poll::Pending,
91 }
92 }
93}
94
95// Enumerates the possible states of the accept process, either waiting for the inner non-TLS
96// connection to be accepted, or performing the TLS handshake.
97pin_project! {
98 #[project = AcceptFutureProj]
99 enum AcceptFuture<F, I, S> {
100 // Waiting for the non-TLS connection to be accepted.
101 InnerAccepting {
102 #[pin]
103 future: F, // The future representing the non-TLS accept phase.
104 handshake_timeout: Duration, // Maximum duration for the TLS handshake.
105 },
106 // Performing the TLS handshake.
107 TlsAccepting {
108 #[pin]
109 future: Timeout<TlsAccept<I>>, // Future that represents the TLS handshake, with a timeout.
110 service: Option<S>, // The underlying service that will handle the request after the TLS handshake.
111 }
112 }
113}
114
115// Main implementation of the future for `OpenSSLAcceptor`.
116impl<F, I, S> Future for OpenSSLAcceptorFuture<F, I, S>
117where
118 F: Future<Output = io::Result<(I, S)>>, // The initial non-TLS accept future.
119 I: AsyncRead + AsyncWrite + Unpin, // The inner type must support asynchronous reading and writing.
120{
121 type Output = io::Result<(SslStream<I>, S)>; // The output will be an `SslStream` and the service to handle the request.
122
123 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
124 let mut this = self.project();
125
126 // The inner future here is what is doing the lower level accept, such as
127 // our tcp socket.
128 //
129 // So we poll on that first, when it's ready we then swap our the inner future to
130 // one waiting for our ssl layer to accept/install.
131 //
132 // Then once that's ready we can then wrap and provide the SslStream back out.
133
134 // This loop exists to allow the Poll::Ready from InnerAccept on complete
135 // to re-poll immediately. Otherwise all other paths are immediate returns.
136 loop {
137 match this.inner.as_mut().project() {
138 AcceptFutureProj::InnerAccepting {
139 future,
140 handshake_timeout,
141 } => match future.poll(cx) {
142 Poll::Ready(Ok((stream, service))) => {
143 let server_config = this.config.take().expect(
144 "config is not set. this is a bug in hyper-server, please report",
145 );
146
147 // Change to poll::ready(err)
148 let ssl = Ssl::new(server_config.acceptor.context()).unwrap();
149
150 let tls_stream = SslStream::new(ssl, stream).unwrap();
151 let future = TlsAccept {
152 tls_stream: Some(tls_stream),
153 };
154
155 let service = Some(service);
156 let handshake_timeout = *handshake_timeout;
157
158 this.inner.set(AcceptFuture::TlsAccepting {
159 future: timeout(handshake_timeout, future),
160 service,
161 });
162 // the loop is now triggered to immediately poll on
163 // ssl stream accept.
164 }
165 Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
166 Poll::Pending => return Poll::Pending,
167 },
168
169 AcceptFutureProj::TlsAccepting { future, service } => match future.poll(cx) {
170 Poll::Ready(Ok(Ok(stream))) => {
171 let service = service.take().expect("future polled after ready");
172 return Poll::Ready(Ok((stream, service)));
173 }
174 Poll::Ready(Ok(Err(e))) => return Poll::Ready(Err(e)),
175 Poll::Ready(Err(timeout)) => {
176 return Poll::Ready(Err(Error::new(ErrorKind::TimedOut, timeout)))
177 }
178 Poll::Pending => return Poll::Pending,
179 },
180 }
181 }
182 }
183}