1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::fmt;
use std::io::{self, Read, Write};
use std::ops::{Deref, DerefMut};
use std::pin::Pin;

use openssl::ssl;

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

use async_stdio::*;

/// An asynchronous SSL stream
pub struct SslStream<S> {
    pub(crate) inner: ssl::SslStream<AsStdIo<S>>,
    pub(crate) ctrl: WakerCtrlHandle,
}

impl<S> Deref for SslStream<S> {
    type Target = ssl::SslStream<AsStdIo<S>>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<S> DerefMut for SslStream<S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<S: fmt::Debug> fmt::Debug for SslStream<S> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("SslStream")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<S> AsyncRead for SslStream<S>
where
    S: Unpin + AsyncRead + AsyncWrite,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();

        this.ctrl.register(cx.waker());

        this.inner.read(buf).into_poll()
    }
}

impl<S> AsyncWrite for SslStream<S>
where
    S: AsyncWrite + AsyncRead + Unpin,
{
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();

        this.ctrl.register(cx.waker());

        this.inner.write(buf).into_poll()
    }

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

        this.ctrl.register(cx.waker());

        this.inner.flush().into_poll()
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        try_ready!(self.as_mut().poll_flush(cx));

        let (stream, mut cx) = self.get_mut().inner.get_mut().get_stream_with_context();
        stream.poll_close(&mut cx)
    }
}