openssl-async 0.3.0-alpha.5

Wrappers for the OpenSSL crate to allow use in async applications
Documentation
use std::mem;
use std::pin::Pin;

use openssl::ssl::{self, SslAcceptor};

use futures::io::{AsyncRead, AsyncWrite};
use futures::prelude::*;
use futures::task::{Context, Poll};

use async_stdio::*;

use crate::{HandshakeError, MidHandshakeSslStream, SslStream};

/// Extension for [SslAcceptor] to allow connections to be accepted
/// asynchronously.
pub trait SslAcceptorExt {
    /// Asynchronously accept the connection
    fn accept_async<S: AsyncRead + AsyncWrite>(&self, stream: S) -> AcceptAsync<S>;
}

impl SslAcceptorExt for SslAcceptor {
    fn accept_async<S>(&self, stream: S) -> AcceptAsync<S>
    where
        S: AsyncRead + AsyncWrite,
    {
        AcceptAsync(AcceptInner::Init(self.clone(), stream))
    }
}

/// The future returned from [SslAcceptorExt::accept_async]
///
/// Resolves to an [SslStream]
pub struct AcceptAsync<S>(AcceptInner<S>);

enum AcceptInner<S> {
    Init(SslAcceptor, S),
    Handshake(MidHandshakeSslStream<S>),
    Done,
}

impl<S: AsyncRead + AsyncWrite + Unpin> Future for AcceptAsync<S> {
    type Output = Result<SslStream<S>, HandshakeError<S>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = Pin::get_mut(self);

        match mem::replace(&mut this.0, AcceptInner::Done) {
            AcceptInner::Init(acceptor, stream) => {
                let (stream, ctrl) = AsStdIo::new(stream, cx.waker().into());
                match acceptor.accept(stream) {
                    Ok(inner) => Poll::Ready(Ok(SslStream { inner, ctrl })),
                    Err(ssl::HandshakeError::WouldBlock(inner)) => {
                        this.0 = AcceptInner::Handshake(MidHandshakeSslStream::new(inner, ctrl));
                        Poll::Pending
                    }
                    Err(e) => Poll::Ready(Err(HandshakeError::from_ssl(e, ctrl).unwrap())),
                }
            }
            AcceptInner::Handshake(mut handshake) => match Pin::new(&mut handshake).poll(cx) {
                Poll::Ready(result) => Poll::Ready(result),
                Poll::Pending => {
                    this.0 = AcceptInner::Handshake(handshake);
                    Poll::Pending
                }
            },
            AcceptInner::Done => panic!("accept polled after completion"),
        }
    }
}