Documentation
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! This module provides a TCP [`Session`] implementation and simple [`TcpServer`].

use std::{
    io::{Error, ErrorKind, Read, Write},
    net::{SocketAddr, TcpListener, ToSocketAddrs},
    time::Duration,
};

use tcp_stream::{HandshakeError, MidHandshakeTlsStream, TLSConfig, TcpStream};

use crate::{ReadStatus, Session, TlsSession, WriteStatus};

/// A [`Session`] that encapsulates a [`TcpStream`].
///
/// This implementation does not provide any framing guarantees.
/// Buffers will be returned as they are read from the underlying sockets.
/// Writes may be partially completed, with the remaining slice returned as [`WriteStatus::Pending`].
///
/// Once a client successfully connects, a plain TCP session can initiale a TLS handshake by calling [`TlsSession::to_tls`].
/// The TLS handshake will be driven to completion by calling the [`Session::drive`] function.
/// While a TLS handshake is in progress, calls to `read` and `write` will not be able to consume or produce data.
pub struct StreamingTcpSession {
    read_buffer: Vec<u8>,
    stream: Option<TcpStream>,
    mid_handshake: Option<MidHandshakeTlsStream>,
    tls_handshake_complete: bool,
    is_server_session: bool,
}
impl StreamingTcpSession {
    /// You may wish to use the more convenient `connect(..)` function.
    ///
    /// Create a new StreamingTcpSession with the given buffer length.
    /// You may the underlying stream with `set_stream` or `with_stream`.
    ///
    /// ```no_compile
    /// let session = StreamingTcpSession::new(4096).with_stream(my_stream);
    /// ````
    pub fn new(read_buffer_len: usize) -> Self {
        let mut read_buffer = Vec::new();
        read_buffer.resize(read_buffer_len, 0);
        Self {
            stream: None,
            mid_handshake: None,
            read_buffer,
            tls_handshake_complete: false,
            is_server_session: false,
        }
    }

    /// Connect to the given socket address in nonblocking mode.
    pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<Self, Error> {
        Ok(Self::default()
            .with_stream(TcpStream::Plain(std::net::TcpStream::connect(addr)?, true))
            .with_nonblocking(true)?)
    }

    /// Set the underlying stream
    pub fn set_stream(&mut self, stream: TcpStream) {
        self.stream = Some(stream);
        self.mid_handshake = None;
    }

    /// Set nodelay on the underlying stream
    pub fn set_nodelay(&self, nodelay: bool) -> Result<(), Error> {
        match &self.stream {
            Some(x) => x.set_nodelay(nodelay),
            None => Err(Error::new(ErrorKind::NotConnected, "stream not connected").into()),
        }
    }

    /// Set nonblocking on the underlying stream
    pub fn set_nonblocking(&self, nonblocking: bool) -> Result<(), Error> {
        match &self.stream {
            Some(x) => x.set_nonblocking(nonblocking),
            None => Err(Error::new(ErrorKind::NotConnected, "stream not connected").into()),
        }
    }

    /// Set read_timeout on the underlying stream
    pub fn set_read_timeout(&self, read_timeout: Option<Duration>) -> Result<(), Error> {
        match &self.stream {
            Some(x) => x.set_read_timeout(read_timeout),
            None => Err(Error::new(ErrorKind::NotConnected, "stream not connected").into()),
        }
    }

    /// Set ttl on the underlying stream
    pub fn set_ttl(&self, ttl: u32) -> Result<(), Error> {
        match &self.stream {
            Some(x) => x.set_ttl(ttl),
            None => Err(Error::new(ErrorKind::NotConnected, "stream not connected").into()),
        }
    }

    /// Set write_timeout on the underlying stream
    pub fn set_write_timeout(&self, write_timeout: Option<Duration>) -> Result<(), Error> {
        match &self.stream {
            Some(x) => x.set_write_timeout(write_timeout),
            None => Err(Error::new(ErrorKind::NotConnected, "stream not connected").into()),
        }
    }

    /// Set the underlying stream using a builder pattern
    pub fn with_stream(mut self, stream: TcpStream) -> Self {
        self.set_stream(stream);
        self
    }

    /// Set nodelay on the underlying stream using a builder pattern
    pub fn with_nodelay(self, nodelay: bool) -> Result<Self, Error> {
        self.set_nodelay(nodelay)?;
        Ok(self)
    }

    /// Set nonblocking on the underlying stream using a builder pattern
    pub fn with_nonblocking(self, nonblocking: bool) -> Result<Self, Error> {
        self.set_nonblocking(nonblocking)?;
        Ok(self)
    }

    /// Set read_timeout on the underlying stream using a builder pattern
    pub fn with_read_timeout(self, read_timeout: Option<Duration>) -> Result<Self, Error> {
        self.set_read_timeout(read_timeout)?;
        Ok(self)
    }

    /// Set nonblocking on the underlying stream using a builder pattern
    pub fn with_ttl(self, ttl: u32) -> Result<Self, Error> {
        self.set_ttl(ttl)?;
        Ok(self)
    }

    /// Set write_timeout on the underlying stream using a builder pattern
    pub fn with_write_timeout(self, write_timeout: Option<Duration>) -> Result<Self, Error> {
        self.set_write_timeout(write_timeout)?;
        Ok(self)
    }

    /// Internal use
    fn with_is_server_session(mut self, is_server_session: bool) -> Self {
        self.is_server_session = is_server_session;
        self
    }
}
impl Default for StreamingTcpSession {
    fn default() -> Self {
        Self::new(4096)
    }
}
impl Session for StreamingTcpSession {
    type ReadData = [u8];
    type WriteData = [u8];

    fn is_connected(&self) -> bool {
        match &self.stream {
            Some(x) => x.is_connected(),
            None => self.mid_handshake.is_some(),
        }
    }

    fn try_connect(&mut self) -> Result<bool, Error> {
        match &mut self.stream {
            Some(x) => x.try_connect(),
            None => {
                if self.mid_handshake.is_some() {
                    Ok(true)
                } else {
                    Err(Error::new(ErrorKind::ConnectionReset, "undefined stream"))
                }
            }
        }
    }

    fn drive(&mut self) -> Result<bool, Error> {
        if self.mid_handshake.is_some() {
            let mid_handshake = match self.mid_handshake.take() {
                Some(x) => x,
                None => return Err(Error::new(ErrorKind::Other, "stream is not mid-handshake")),
            };
            match mid_handshake.handshake() {
                Ok(x) => {
                    self.stream = Some(x);
                    self.tls_handshake_complete = true;
                    Ok(true)
                }
                Err(err) => match err {
                    HandshakeError::WouldBlock(x) => {
                        self.mid_handshake = Some(x);
                        Ok(false)
                    }
                    HandshakeError::Failure(err) => Err(err),
                },
            }
        } else {
            Ok(false)
        }
    }

    fn write<'a>(
        &mut self,
        data: &'a Self::WriteData,
    ) -> Result<WriteStatus<'a, Self::WriteData>, Error> {
        if data.is_empty() {
            // nothing to write, nothing to do
            return Ok(WriteStatus::Success);
        }
        let stream = match &mut self.stream {
            Some(x) => x,
            None => {
                if self.mid_handshake.is_some() {
                    return Ok(WriteStatus::Pending(data));
                } else {
                    return Err(Error::new(ErrorKind::NotConnected, "stream not connected").into());
                }
            }
        };
        let wrote = match stream.write(data) {
            Ok(0) => {
                // per rust docs: A return value of 0 typically means that the underlying object is no longer
                // able to accept bytes and will likely not be able to in the future as well, or that the buffer
                // provided is empty.
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "stream underlying write returned 0 instead of WouldBlock",
                ));
            }
            Ok(x) => x,
            Err(err) => match err.kind() {
                ErrorKind::WouldBlock => 0,
                _ => return Err(err.into()),
            },
        };
        if wrote == data.len() {
            Ok(WriteStatus::Success)
        } else {
            Ok(WriteStatus::Pending(&data[wrote..]))
        }
    }

    fn read<'a>(&'a mut self) -> Result<ReadStatus<'a, Self::ReadData>, Error> {
        let stream = match &mut self.stream {
            Some(x) => x,
            None => {
                if self.mid_handshake.is_some() {
                    return Ok(ReadStatus::None);
                } else {
                    return Err(Error::new(ErrorKind::NotConnected, "stream not connected").into());
                }
            }
        };
        let read = match stream.read(self.read_buffer.as_mut_slice()) {
            Ok(x) => x,
            Err(err) => match err.kind() {
                ErrorKind::WouldBlock => 0,
                _ => return Err(err.into()),
            },
        };
        if read == 0 {
            Ok(ReadStatus::None)
        } else {
            Ok(ReadStatus::Data(
                &mut self.read_buffer.as_mut_slice()[..read],
            ))
        }
    }

    fn flush(&mut self) -> Result<(), Error> {
        match &mut self.stream {
            None => Ok(()),
            Some(stream) => stream.flush(),
        }
    }
}
impl TlsSession for StreamingTcpSession {
    fn to_tls(&mut self, domain: &str, config: TLSConfig<'_, '_, '_>) -> Result<(), Error> {
        if self.is_server_session {
            return Err(Error::new(
                ErrorKind::Unsupported,
                "to_tls is only supported for client connections",
            ));
        }
        let stream = match self.stream.take() {
            Some(x) => x,
            None => return Err(Error::new(ErrorKind::NotConnected, "stream not connected")),
        };
        match stream.into_tls(domain, config) {
            Ok(x) => {
                self.stream = Some(x);
                self.tls_handshake_complete = true;
                Ok(())
            }
            Err(err) => match err {
                HandshakeError::WouldBlock(x) => {
                    self.mid_handshake = Some(x);
                    Ok(())
                }
                HandshakeError::Failure(err) => Err(err),
            },
        }
    }

    fn is_handshake_complete(&self) -> Result<bool, Error> {
        Ok(self.tls_handshake_complete)
    }
}

/// A TcpServer, which produces connected, nonblocking [`StreamingTcpSession`] on calling `accept`.
pub struct TcpServer {
    listener: TcpListener,
}
impl TcpServer {
    /// Encapsulate the given [`TcpListener`]
    pub fn new(listener: TcpListener) -> Self {
        Self { listener }
    }

    /// Bind to the given socket address in nonblocking mode.
    pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<Self, Error> {
        let listener = TcpListener::bind(addr)?;
        listener.set_nonblocking(true)?;
        Ok(Self::new(listener))
    }

    /// Set nonblocking on the listener
    pub fn set_nonblocking(&self, nonblocking: bool) -> Result<(), Error> {
        self.listener.set_nonblocking(nonblocking)
    }

    /// Set ttl on the listener
    pub fn set_ttl(&self, ttl: u32) -> Result<(), Error> {
        self.listener.set_ttl(ttl)
    }

    /// Set nonblocking on the listener using a builder pattern
    pub fn with_nonblocking(self, nonblocking: bool) -> Result<Self, Error> {
        self.set_nonblocking(nonblocking)?;
        Ok(self)
    }

    /// Set ttl on the listener using a builder pattern
    pub fn with_ttl(self, ttl: u32) -> Result<Self, Error> {
        self.set_ttl(ttl)?;
        Ok(self)
    }

    /// Accept a new TCP Session, immediately returning None in nonblocking mode if there are no new sessions.
    pub fn accept(&self) -> Result<Option<(StreamingTcpSession, SocketAddr)>, Error> {
        let (stream, addr) = self.listener.accept()?;
        Ok(Some((
            StreamingTcpSession::default()
                .with_stream(TcpStream::Plain(stream, true))
                .with_is_server_session(true)
                .with_nonblocking(true)?,
            addr,
        )))
    }
}

#[cfg(test)]
mod test {
    use tcp_stream::TLSConfig;

    use crate::{ReadStatus, Session, TlsSession, WriteStatus};

    use super::{StreamingTcpSession, TcpServer};

    #[test]
    pub fn tcp_client_server() {
        // create server, connect client, establish server session
        let server = TcpServer::bind("127.0.0.1:33001").unwrap();
        let mut client = StreamingTcpSession::connect("127.0.0.1:33001").unwrap();
        let mut session = None;
        while let None = session {
            session = server.accept().unwrap().map(|(s, _)| s);
        }
        let mut session = session.unwrap();

        // construct read buffer and a large payload to write
        let mut read_buffer = Vec::new();
        let mut write_payload = Vec::new();
        for i in 0..9999999 {
            write_payload.push(i as u8)
        }

        // send the message with the client while reading it with the server session
        let mut remaining = write_payload.as_slice();
        while let WriteStatus::Pending(pw) = client.write(remaining).unwrap() {
            remaining = pw;
            if let ReadStatus::Data(read) = session.read().unwrap() {
                read_buffer.extend_from_slice(read);
            }
        }

        // read the rest of the message with the server session
        while read_buffer.len() < 9999999 {
            if let ReadStatus::Data(read) = session.read().unwrap() {
                read_buffer.extend_from_slice(read);
            }
        }

        // validate the received message
        assert_eq!(read_buffer.len(), write_payload.len());
        assert_eq!(read_buffer, write_payload);
    }

    #[test]
    pub fn tcp_tls() {
        // create client
        let mut client = StreamingTcpSession::connect("www.google.com:443").unwrap();

        // handshake
        client
            .to_tls("www.google.com", TLSConfig::default())
            .unwrap();

        // send request
        let request = "GET / HTTP/1.1\r\nhost: www.google.com\r\n\r\n"
            .as_bytes()
            .to_vec();
        let mut remaining = request.as_slice();
        while let Ok(WriteStatus::Pending(pw)) = client.write(remaining) {
            remaining = pw;
            client.drive().unwrap();
        }

        // read (some of) response
        let mut response = Vec::new();
        while response.len() < 9 {
            if let ReadStatus::Data(read) = client.read().unwrap() {
                response.extend_from_slice(read);
            }
        }

        assert!(String::from_utf8_lossy(&response).starts_with("HTTP/1.1 "));
    }

    #[test]
    pub fn tcp_slow_consumer() {
        // create server, connect client, establish server session
        let server = TcpServer::bind("127.0.0.1:33002").unwrap();
        let mut client = StreamingTcpSession::connect("127.0.0.1:33002").unwrap();
        let mut session = server.accept().unwrap().unwrap().0;

        // send 100,000 messages with client while "slowly" reading with session
        let mut received: Vec<u8> = Vec::new();
        let mut backpressure = false;
        for i in 0..100000 {
            let write_payload = format!("test test test test hello world {i:06}!");
            // send the message with the client while reading it with the server session
            let mut remaining = write_payload.as_bytes();
            while let WriteStatus::Pending(pw) = client.write(remaining).unwrap() {
                remaining = pw;
                backpressure = true;
                // only read when backpressure is encountered to simulate a slow consumer
                for _ in 0..10 {
                    if let ReadStatus::Data(read) = session.read().unwrap() {
                        received.extend_from_slice(&read);
                    }
                }
            }
        }

        // assert backpressure and write failures were tested
        assert!(backpressure);

        // finish reading with session until all 100,000 messages of length=39 were received while driving client to write completion
        while received.len() < (100000 * 39) {
            client.drive().unwrap();
            if let ReadStatus::Data(read) = session.read().unwrap() {
                received.extend_from_slice(&read);
            }
        }
        assert_eq!(received.len(), 100000 * 39)
    }
}