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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use super::*;
use rustls::Session;
use std::io::Write;

/// A wrapper around an underlying raw stream which implements the TLS or SSL
/// protocol.
#[derive(Debug)]
pub struct TlsStream<IO> {
    pub(crate) io: IO,
    pub(crate) session: ClientSession,
    pub(crate) state: TlsState,

    #[cfg(feature = "early-data")]
    pub(crate) early_data: (usize, Vec<u8>),
}

pub(crate) enum MidHandshake<IO> {
    Handshaking(TlsStream<IO>),
    #[cfg(feature = "early-data")]
    EarlyData(TlsStream<IO>),
    End,
}

impl<IO> TlsStream<IO> {
    #[inline]
    pub fn get_ref(&self) -> (&IO, &ClientSession) {
        (&self.io, &self.session)
    }

    #[inline]
    pub fn get_mut(&mut self) -> (&mut IO, &mut ClientSession) {
        (&mut self.io, &mut self.session)
    }

    #[inline]
    pub fn into_inner(self) -> (IO, ClientSession) {
        (self.io, self.session)
    }
}

impl<IO> Future for MidHandshake<IO>
where
    IO: AsyncRead + AsyncWrite,
{
    type Item = TlsStream<IO>;
    type Error = io::Error;

    #[inline]
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        if let MidHandshake::Handshaking(stream) = self {
            let state = stream.state;
            let (io, session) = stream.get_mut();
            let mut stream = Stream::new(io, session).set_eof(!state.readable());

            if stream.session.is_handshaking() {
                try_nb!(stream.complete_io());
            }

            if stream.session.wants_write() {
                try_nb!(stream.complete_io());
            }
        }

        match mem::replace(self, MidHandshake::End) {
            MidHandshake::Handshaking(stream) => Ok(Async::Ready(stream)),
            #[cfg(feature = "early-data")]
            MidHandshake::EarlyData(stream) => Ok(Async::Ready(stream)),
            MidHandshake::End => panic!(),
        }
    }
}

impl<IO> io::Read for TlsStream<IO>
where
    IO: AsyncRead + AsyncWrite,
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self.state {
            #[cfg(feature = "early-data")]
            TlsState::EarlyData => {
                {
                    let mut stream = Stream::new(&mut self.io, &mut self.session);
                    let (pos, data) = &mut self.early_data;

                    // complete handshake
                    if stream.session.is_handshaking() {
                        stream.complete_io()?;
                    }

                    // write early data (fallback)
                    if !stream.session.is_early_data_accepted() {
                        while *pos < data.len() {
                            let len = stream.write(&data[*pos..])?;
                            *pos += len;
                        }
                    }

                    // end
                    self.state = TlsState::Stream;
                    *data = Vec::new();
                }

                self.read(buf)
            }
            TlsState::Stream | TlsState::WriteShutdown => {
                let mut stream = Stream::new(&mut self.io, &mut self.session).set_eof(!self.state.readable());

                match stream.read(buf) {
                    Ok(0) => {
                        self.state.shutdown_read();
                        Ok(0)
                    }
                    Ok(n) => Ok(n),
                    Err(ref e) if e.kind() == io::ErrorKind::ConnectionAborted => {
                        self.state.shutdown_read();
                        if self.state.writeable() {
                            stream.session.send_close_notify();
                            self.state.shutdown_write();
                        }
                        Ok(0)
                    }
                    Err(e) => Err(e),
                }
            }
            TlsState::ReadShutdown | TlsState::FullyShutdown => Ok(0),
        }
    }
}

impl<IO> io::Write for TlsStream<IO>
where
    IO: AsyncRead + AsyncWrite,
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let mut stream = Stream::new(&mut self.io, &mut self.session).set_eof(!self.state.readable());

        match self.state {
            #[cfg(feature = "early-data")]
            TlsState::EarlyData => {
                let (pos, data) = &mut self.early_data;

                // write early data
                if let Some(mut early_data) = stream.session.early_data() {
                    let len = early_data.write(buf)?;
                    data.extend_from_slice(&buf[..len]);
                    if len != 0 {
                        return Ok(len);
                    }
                }

                // complete handshake
                if stream.session.is_handshaking() {
                    stream.complete_io()?;
                }

                // write early data (fallback)
                if !stream.session.is_early_data_accepted() {
                    while *pos < data.len() {
                        let len = stream.write(&data[*pos..])?;
                        *pos += len;
                    }
                }

                // end
                self.state = TlsState::Stream;
                *data = Vec::new();
                stream.write(buf)
            }
            _ => stream.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        let mut stream = Stream::new(&mut self.io, &mut self.session)
            .set_eof(!self.state.readable());

        #[cfg(feature = "early-data")] {
            let (pos, data) = &mut self.early_data;

            while stream.session.is_handshaking() {
                stream.complete_io()?;
            }

            // write early data (fallback)
            if !stream.session.is_early_data_accepted() {
                while *pos < data.len() {
                    *pos = stream.write(&data[*pos..])?;
                }
            }

            self.state = TlsState::Stream;
            *data = Vec::new();
        }

        stream.flush()?;
        self.io.flush()
    }
}

impl<IO> AsyncRead for TlsStream<IO>
where
    IO: AsyncRead + AsyncWrite,
{
    unsafe fn prepare_uninitialized_buffer(&self, _: &mut [u8]) -> bool {
        false
    }
}

impl<IO> AsyncWrite for TlsStream<IO>
where
    IO: AsyncRead + AsyncWrite,
{
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        if self.state.writeable() {
            self.session.send_close_notify();
            self.state.shutdown_write();
        }

        let mut stream = Stream::new(&mut self.io, &mut self.session).set_eof(!self.state.readable());
        try_nb!(stream.flush());
        stream.io.shutdown()
    }
}