1use std::mem;
2use std::pin::Pin;
3
4use openssl::ssl::{self, SslAcceptor};
5
6use futures::io::{AsyncRead, AsyncWrite};
7use futures::prelude::*;
8use futures::task::{Context, Poll};
9
10use async_stdio::*;
11
12use crate::{HandshakeError, MidHandshakeSslStream, SslStream};
13
14pub trait SslAcceptorExt {
17 fn accept_async<S: AsyncRead + AsyncWrite>(&self, stream: S) -> AcceptAsync<S>;
19}
20
21impl SslAcceptorExt for SslAcceptor {
22 fn accept_async<S>(&self, stream: S) -> AcceptAsync<S>
23 where
24 S: AsyncRead + AsyncWrite,
25 {
26 AcceptAsync(AcceptInner::Init(self.clone(), stream))
27 }
28}
29
30pub struct AcceptAsync<S>(AcceptInner<S>);
34
35enum AcceptInner<S> {
36 Init(SslAcceptor, S),
37 Handshake(MidHandshakeSslStream<S>),
38 Done,
39}
40
41impl<S: AsyncRead + AsyncWrite + Unpin> Future for AcceptAsync<S> {
42 type Output = Result<SslStream<S>, HandshakeError<S>>;
43
44 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
45 let this = Pin::get_mut(self);
46
47 match mem::replace(&mut this.0, AcceptInner::Done) {
48 AcceptInner::Init(acceptor, stream) => {
49 let (stream, ctrl) = AsStdIo::new(stream, cx.waker().into());
50 match acceptor.accept(stream) {
51 Ok(inner) => Poll::Ready(Ok(SslStream { inner, ctrl })),
52 Err(ssl::HandshakeError::WouldBlock(inner)) => {
53 this.0 = AcceptInner::Handshake(MidHandshakeSslStream::new(inner, ctrl));
54 Poll::Pending
55 }
56 Err(e) => Poll::Ready(Err(HandshakeError::from_ssl(e, ctrl).unwrap())),
57 }
58 }
59 AcceptInner::Handshake(mut handshake) => match Pin::new(&mut handshake).poll(cx) {
60 Poll::Ready(result) => Poll::Ready(result),
61 Poll::Pending => {
62 this.0 = AcceptInner::Handshake(handshake);
63 Poll::Pending
64 }
65 },
66 AcceptInner::Done => panic!("accept polled after completion"),
67 }
68 }
69}