boomnet 0.0.78

Framework for building low latency clients on top of TCP.
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Provides TLS stream implementation for different backends.

use crate::service::select::Selectable;
use crate::stream::{ConnectionInfo, ConnectionInfoProvider};
#[cfg(feature = "openssl")]
pub use __openssl::TlsStream;
#[cfg(all(feature = "rustls", not(feature = "openssl")))]
pub use __rustls::TlsStream;
#[cfg(feature = "mio")]
use mio::{Interest, Registry, Token, event::Source};
#[cfg(feature = "openssl")]
use openssl::ssl::{SslConnectorBuilder, SslVerifyMode};
#[cfg(all(feature = "rustls", not(feature = "openssl")))]
use rustls::ClientConfig;
use std::fmt::Debug;
use std::io;
use std::io::{Read, Write};

/// Used to configure TLS backend.
pub struct TlsConfig {
    #[cfg(all(feature = "rustls", not(feature = "openssl")))]
    rustls_config: ClientConfig,
    #[cfg(feature = "openssl")]
    openssl_config: SslConnectorBuilder,
}

#[cfg(feature = "openssl")]
impl From<SslConnectorBuilder> for TlsConfig {
    fn from(config: SslConnectorBuilder) -> Self {
        Self { openssl_config: config }
    }
}

#[cfg(all(feature = "rustls", not(feature = "openssl")))]
impl From<ClientConfig> for TlsConfig {
    fn from(config: ClientConfig) -> Self {
        Self { rustls_config: config }
    }
}

/// Extension methods for `TlsConfig`.
pub trait TlsConfigExt {
    /// Disable certificate verification.
    fn with_no_cert_verification(&mut self);

    #[cfg(feature = "openssl")]
    /// Try to resolve default certificate paths.
    ///
    /// NOTE: openssl will look at default locations for the ca/cert information set at compile
    /// time, however when the crate is included with the `vendored` feature flag, these are
    /// not set.
    /// If not the library will look under the following env vars:
    /// * SSL_CERT_FILE
    /// * SSL_CERT_DIR
    ///
    /// So here the system is probed for values to use as a starting point.
    ///
    /// NOTE: cargo leaks these env vars when running the binary under it.
    fn with_default_cert_paths(&mut self);
}

impl TlsConfig {
    /// Get reference to the `rustls` configuration object.
    #[cfg(all(feature = "rustls", not(feature = "openssl")))]
    pub const fn as_rustls(&self) -> &ClientConfig {
        &self.rustls_config
    }

    /// Get mutable reference to the `rustls` configuration object.
    #[cfg(all(feature = "rustls", not(feature = "openssl")))]
    pub const fn as_rustls_mut(&mut self) -> &mut ClientConfig {
        &mut self.rustls_config
    }

    /// Get reference to the `openssl` configuration object.
    #[cfg(feature = "openssl")]
    pub const fn as_openssl(&self) -> &SslConnectorBuilder {
        &self.openssl_config
    }

    /// Get mutable reference to the `openssl` configuration object.
    #[cfg(feature = "openssl")]
    pub const fn as_openssl_mut(&mut self) -> &mut SslConnectorBuilder {
        &mut self.openssl_config
    }

    /// Get mutable reference to the `openssl` configuration object.
    #[cfg(feature = "openssl")]
    pub fn into_openssl(self) -> SslConnectorBuilder {
        self.openssl_config
    }
}

impl TlsConfigExt for TlsConfig {
    fn with_no_cert_verification(&mut self) {
        #[cfg(all(feature = "rustls", not(feature = "openssl")))]
        self.rustls_config
            .dangerous()
            .set_certificate_verifier(std::sync::Arc::new(crate::stream::tls::__rustls::NoCertVerification));
        #[cfg(feature = "openssl")]
        self.openssl_config.set_verify(SslVerifyMode::NONE);
    }

    #[cfg(feature = "openssl")]
    fn with_default_cert_paths(&mut self) {
        use log::warn;
        use std::path::PathBuf;
        use std::sync::OnceLock;

        static PROBED_CERTS: OnceLock<(Option<PathBuf>, Option<PathBuf>)> = OnceLock::new();

        fn probed_certs() -> &'static (Option<PathBuf>, Option<PathBuf>) {
            PROBED_CERTS.get_or_init(|| {
                let p = openssl_probe::probe();
                (p.cert_file, p.cert_dir)
            })
        }

        let (cert_file, cert_dir) = probed_certs();

        // if neither is set, skip the call to avoid a guaranteed error.
        if cert_file.is_none() && cert_dir.is_none() {
            return;
        }

        if let Err(e) = self
            .openssl_config
            .load_verify_locations(cert_file.as_deref(), cert_dir.as_deref())
        {
            warn!("was not able to default ssl paths due to {:?}", e);
        }
    }
}

#[cfg(all(feature = "rustls", not(feature = "openssl")))]
mod __rustls {
    use crate::service::select::Selectable;
    use crate::stream::tls::TlsConfig;
    use crate::stream::{ConnectionInfo, ConnectionInfoProvider};
    use crate::util::NoBlock;
    #[cfg(feature = "mio")]
    use mio::{Interest, Registry, Token, event::Source};
    use rustls::SignatureScheme::{
        ECDSA_NISTP256_SHA256, ECDSA_NISTP384_SHA384, ECDSA_NISTP521_SHA512, ECDSA_SHA1_Legacy, ED448, ED25519,
        RSA_PKCS1_SHA1, RSA_PKCS1_SHA256, RSA_PKCS1_SHA384, RSA_PKCS1_SHA512, RSA_PSS_SHA256, RSA_PSS_SHA384,
        RSA_PSS_SHA512,
    };
    use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
    use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
    use rustls::{ClientConfig, ClientConnection, DigitallySignedStruct, Error, RootCertStore, SignatureScheme};
    use std::fmt::Debug;
    use std::io;
    use std::io::{Read, Write};

    pub struct TlsStream<S> {
        inner: S,
        tls: ClientConnection,
    }

    #[cfg(feature = "mio")]
    impl<S: Source> Source for TlsStream<S> {
        fn register(&mut self, registry: &Registry, token: Token, interests: Interest) -> io::Result<()> {
            registry.register(&mut self.inner, token, interests)
        }

        fn reregister(&mut self, registry: &Registry, token: Token, interests: Interest) -> io::Result<()> {
            registry.reregister(&mut self.inner, token, interests)
        }

        fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
            registry.deregister(&mut self.inner)
        }
    }

    impl<S: Selectable> Selectable for TlsStream<S> {
        fn connected(&mut self) -> io::Result<bool> {
            self.inner.connected()
        }

        fn make_writable(&mut self) -> io::Result<()> {
            self.inner.make_writable()
        }

        fn make_readable(&mut self) -> io::Result<()> {
            self.inner.make_readable()
        }
    }

    impl<S: Read + Write> Read for TlsStream<S> {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let (_, _) = self.complete_io()?;
            self.tls.reader().read(buf)
        }
    }

    impl<S: Read + Write> Write for TlsStream<S> {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.tls.writer().write(buf)
        }

        fn flush(&mut self) -> io::Result<()> {
            self.tls.writer().flush()
        }
    }

    impl<S: Read + Write> TlsStream<S> {
        pub fn new_with_config<F>(stream: S, server_name: &str, builder: F) -> io::Result<TlsStream<S>>
        where
            F: FnOnce(&mut TlsConfig),
        {
            #[cfg(not(all(feature = "rustls-native-certs", feature = "webpki-roots")))]
            let mut root_store = RootCertStore::empty();

            #[cfg(all(feature = "rustls-native-certs", feature = "webpki-roots"))]
            let root_store = RootCertStore::empty();

            #[cfg(all(feature = "webpki-roots", not(feature = "rustls-native-certs")))]
            root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

            #[cfg(all(feature = "rustls-native-certs", not(feature = "webpki-roots")))]
            {
                for cert in rustls_native_certs::load_native_certs().expect("could not load platform certs") {
                    root_store.add(cert).unwrap();
                }
            }

            let config = ClientConfig::builder()
                .with_root_certificates(root_store)
                .with_no_client_auth();

            let mut config = TlsConfig { rustls_config: config };
            builder(&mut config);

            let config = std::sync::Arc::new(config.rustls_config);
            let server_name = server_name.to_owned().try_into().map_err(io::Error::other)?;
            let tls = ClientConnection::new(config, server_name).map_err(io::Error::other)?;

            Ok(Self { inner: stream, tls })
        }

        pub fn new(stream: S, server_name: &str) -> io::Result<TlsStream<S>> {
            Self::new_with_config(stream, server_name, |_| {})
        }

        fn complete_io(&mut self) -> io::Result<(usize, usize)> {
            let wrote = if self.tls.wants_write() {
                self.tls.write_tls(&mut self.inner)?
            } else {
                0
            };

            if wrote > 0 && !self.tls.is_handshaking() {
                return Ok((0, wrote));
            }

            let read = if self.tls.wants_read() {
                let read = self.tls.read_tls(&mut self.inner).no_block()?;
                if read > 0 {
                    self.tls.process_new_packets().map_err(io::Error::other)?;
                }
                read
            } else {
                0
            };

            Ok((read, wrote))
        }
    }

    impl<S: ConnectionInfoProvider> ConnectionInfoProvider for TlsStream<S> {
        fn connection_info(&self) -> &ConnectionInfo {
            self.inner.connection_info()
        }
    }

    #[derive(Debug)]
    pub(crate) struct NoCertVerification;

    impl ServerCertVerifier for NoCertVerification {
        fn verify_server_cert(
            &self,
            _end_entity: &CertificateDer<'_>,
            _intermediates: &[CertificateDer<'_>],
            _server_name: &ServerName<'_>,
            _ocsp_response: &[u8],
            _now: UnixTime,
        ) -> Result<ServerCertVerified, Error> {
            Ok(ServerCertVerified::assertion())
        }

        fn verify_tls12_signature(
            &self,
            _message: &[u8],
            _cert: &CertificateDer<'_>,
            _dss: &DigitallySignedStruct,
        ) -> Result<HandshakeSignatureValid, Error> {
            Ok(HandshakeSignatureValid::assertion())
        }

        fn verify_tls13_signature(
            &self,
            _message: &[u8],
            _cert: &CertificateDer<'_>,
            _dss: &DigitallySignedStruct,
        ) -> Result<HandshakeSignatureValid, Error> {
            Ok(HandshakeSignatureValid::assertion())
        }

        fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
            vec![
                RSA_PKCS1_SHA1,
                ECDSA_SHA1_Legacy,
                RSA_PKCS1_SHA256,
                ECDSA_NISTP256_SHA256,
                RSA_PKCS1_SHA384,
                ECDSA_NISTP384_SHA384,
                RSA_PKCS1_SHA512,
                ECDSA_NISTP521_SHA512,
                RSA_PSS_SHA256,
                RSA_PSS_SHA384,
                RSA_PSS_SHA512,
                ED25519,
                ED448,
            ]
        }
    }
}

#[cfg(feature = "openssl")]
mod __openssl {
    use crate::service::select::Selectable;
    use crate::stream::tls::TlsConfig;
    use crate::stream::{ConnectionInfo, ConnectionInfoProvider};
    #[cfg(feature = "mio")]
    use mio::{Interest, Registry, Token, event::Source};
    use openssl::ssl::{
        HandshakeError, MidHandshakeSslStream, SslConnector, SslConnectorBuilder, SslMethod, SslRef, SslStream,
    };
    use openssl::x509::X509VerifyResult;
    use std::fmt::Debug;
    use std::fs::OpenOptions;
    use std::io;
    use std::io::ErrorKind::WouldBlock;
    use std::io::{Read, Write};

    trait SslConnectionBuilderExt {
        fn setup_default_keylog_policy(&mut self);
    }

    impl SslConnectionBuilderExt for SslConnectorBuilder {
        fn setup_default_keylog_policy(&mut self) {
            fn default_key_log_callback(_ssl: &SslRef, line: &str) {
                let path = std::env::var("SSLKEYLOGFILE").expect("SSLKEYLOGFILE not set");
                let mut file = OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(path)
                    .expect("Failed to open SSL key log file");

                writeln!(file, "{line}").expect("Failed to write to SSL key log file");
            }

            if std::env::var("SSLKEYLOGFILE").is_ok() {
                self.set_keylog_callback(default_key_log_callback)
            }
        }
    }

    #[derive(Debug)]
    pub struct TlsStream<S> {
        state: State<S>,
    }

    #[derive(Debug)]
    enum State<S> {
        Handshake(Option<(MidHandshakeSslStream<S>, Vec<u8>)>),
        Drain(Option<(SslStream<S>, Vec<u8>, usize)>),
        Stream(SslStream<S>),
    }

    impl<S> State<S> {
        fn get_mut(&mut self) -> io::Result<&mut S> {
            match self {
                State::Handshake(stream_and_buf) => match stream_and_buf.as_mut() {
                    Some((stream, _)) => Ok(stream.get_mut()),
                    None => Err(io::Error::other("unable to perform TLS handshake")),
                },
                State::Drain(stream_and_buf) => match stream_and_buf.as_mut() {
                    Some((stream, ..)) => Ok(stream.get_mut()),
                    None => Err(io::Error::other("unable to drain pending message buffer")),
                },
                State::Stream(stream) => Ok(stream.get_mut()),
            }
        }
    }

    impl<S: ConnectionInfoProvider> ConnectionInfoProvider for State<S> {
        fn connection_info(&self) -> &ConnectionInfo {
            match self {
                State::Handshake(stream_and_buf) => stream_and_buf.as_ref().unwrap().0.get_ref().connection_info(),
                State::Drain(stream_and_buf) => stream_and_buf.as_ref().unwrap().0.get_ref().connection_info(),
                State::Stream(stream) => stream.get_ref().connection_info(),
            }
        }
    }

    #[cfg(feature = "mio")]
    impl<S: Source> Source for TlsStream<S> {
        fn register(&mut self, registry: &Registry, token: Token, interests: Interest) -> io::Result<()> {
            registry.register(self.state.get_mut()?, token, interests)
        }

        fn reregister(&mut self, registry: &Registry, token: Token, interests: Interest) -> io::Result<()> {
            registry.reregister(self.state.get_mut()?, token, interests)
        }

        fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
            registry.deregister(self.state.get_mut()?)
        }
    }

    impl<S: Selectable> Selectable for TlsStream<S> {
        fn connected(&mut self) -> io::Result<bool> {
            self.state.get_mut()?.connected()
        }

        fn make_writable(&mut self) -> io::Result<()> {
            self.state.get_mut()?.make_writable()
        }

        fn make_readable(&mut self) -> io::Result<()> {
            self.state.get_mut()?.make_readable()
        }
    }

    impl<S: Read + Write> Read for TlsStream<S> {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            match &mut self.state {
                State::Handshake(stream_and_buf) => {
                    if let Some((mid_handshake, buffer)) = stream_and_buf.take() {
                        return match mid_handshake.handshake() {
                            Ok(ssl_stream) => {
                                self.state = State::Drain(Some((ssl_stream, buffer, 0)));
                                Err(io::Error::from(WouldBlock))
                            }
                            Err(HandshakeError::WouldBlock(mid)) => {
                                self.state = State::Handshake(Some((mid, buffer)));
                                Err(io::Error::from(WouldBlock))
                            }
                            Err(err) => match err {
                                HandshakeError::Failure(stream) => {
                                    let verify = stream.ssl().verify_result();
                                    if verify != X509VerifyResult::OK {
                                        Err(io::Error::other(format!("{} {}", stream.error(), verify)))
                                    } else {
                                        Err(io::Error::other(stream.error().to_string()))
                                    }
                                }
                                _ => Err(io::Error::other("TLS handshake failed")),
                            },
                        };
                    }
                    Err(io::Error::from(WouldBlock))
                }
                State::Drain(stream_and_buf) => {
                    let (mut stream, buffer, written) = stream_and_buf
                        .take()
                        .ok_or_else(|| io::Error::other("stream not present"))?;
                    let mut from = written;
                    let remaining = &buffer[from..];
                    if remaining.is_empty() {
                        stream.flush()?;
                        self.state = State::Stream(stream);
                    } else {
                        from += stream.write(remaining)?;
                        self.state = State::Drain(Some((stream, buffer, from)));
                    }
                    Err(io::Error::from(WouldBlock))
                }
                State::Stream(stream) => stream.read(buf),
            }
        }
    }

    impl<S: Read + Write> Write for TlsStream<S> {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            match &mut self.state {
                State::Handshake(stream_and_buf) => {
                    let (_, buffer) = stream_and_buf.as_mut().unwrap();
                    buffer.extend_from_slice(buf);
                    Ok(buf.len())
                }
                State::Drain(stream_and_buf) => {
                    let (_, buffer, _) = stream_and_buf.as_mut().unwrap();
                    buffer.extend_from_slice(buf);
                    Ok(buf.len())
                }
                State::Stream(stream) => stream.write(buf),
            }
        }

        fn flush(&mut self) -> io::Result<()> {
            match &mut self.state {
                State::Handshake(_) => Ok(()),
                State::Drain(_) => Ok(()),
                State::Stream(stream) => stream.flush(),
            }
        }
    }

    impl<S: Read + Write + Debug> TlsStream<S> {
        pub fn new_with_config<F>(stream: S, server_name: &str, configure: F) -> io::Result<TlsStream<S>>
        where
            F: FnOnce(&mut TlsConfig),
        {
            let mut builder = SslConnector::builder(SslMethod::tls_client()).map_err(io::Error::other)?;
            builder.setup_default_keylog_policy();

            let mut tls_config = TlsConfig {
                openssl_config: builder,
            };

            configure(&mut tls_config);

            let connector = tls_config.openssl_config.build();
            match connector.connect(server_name, stream) {
                Ok(stream) => Ok(Self {
                    state: State::Stream(stream),
                }),
                Err(HandshakeError::WouldBlock(mid_handshake)) => Ok(Self {
                    state: State::Handshake(Some((mid_handshake, Vec::with_capacity(4096)))),
                }),
                Err(e) => Err(io::Error::other(e.to_string())),
            }
        }

        pub fn new(stream: S, server_name: &str) -> io::Result<TlsStream<S>> {
            Self::new_with_config(stream, server_name, |_| {})
        }
    }

    impl<S: ConnectionInfoProvider> ConnectionInfoProvider for TlsStream<S> {
        fn connection_info(&self) -> &ConnectionInfo {
            self.state.connection_info()
        }
    }
}

/// Trait to convert underlying stream into [TlsStream].
pub trait IntoTlsStream {
    /// Convert underlying stream into [TlsStream] with default tls config.
    ///
    /// ## Examples
    /// ```no_run
    /// use boomnet::stream::tcp::TcpStream;
    /// use boomnet::stream::tls::IntoTlsStream;
    ///
    /// let tls = TcpStream::try_from(("127.0.0.1", 4222)).unwrap().into_tls_stream();
    /// ```
    fn into_tls_stream(self) -> io::Result<TlsStream<Self>>
    where
        Self: Sized,
    {
        self.into_tls_stream_with_config(|_| {})
    }

    /// Convert underlying stream into [TlsStream] and modify tls config. The type of`TlsConfig` used
    /// will depend on whether `openssl` or `rustls` has been enabled.
    ///
    /// ## Examples
    ///
    /// Using `openssl` configure the TLS stream to disable server side certificate verification.
    /// ```no_run
    /// #[cfg(feature = "openssl")]
    /// {
    ///     use openssl::ssl::SslVerifyMode;
    ///     {
    ///         use boomnet::stream::tcp::TcpStream;
    ///         use boomnet::stream::tls::IntoTlsStream;
    ///
    ///         let tls = TcpStream::try_from(("127.0.0.1", 4222)).unwrap().into_tls_stream_with_config(|config| {
    ///             config.as_openssl_mut().set_verify(SslVerifyMode::NONE);
    ///         });
    ///     }
    /// }
    /// ```
    fn into_tls_stream_with_config<F>(self, builder: F) -> io::Result<TlsStream<Self>>
    where
        Self: Sized,
        F: FnOnce(&mut TlsConfig);
}

impl<T> IntoTlsStream for T
where
    T: Read + Write + Debug + ConnectionInfoProvider,
{
    fn into_tls_stream_with_config<F>(self, builder: F) -> io::Result<TlsStream<Self>>
    where
        Self: Sized,
        F: FnOnce(&mut TlsConfig),
    {
        let server_name = self.connection_info().clone().host;
        TlsStream::new_with_config(self, &server_name, builder)
    }
}

#[allow(clippy::large_enum_variant)]
pub enum TlsReadyStream<S> {
    Plain(S),
    Tls(TlsStream<S>),
}

impl<S: Read + Write> Read for TlsReadyStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            TlsReadyStream::Plain(stream) => stream.read(buf),
            TlsReadyStream::Tls(stream) => stream.read(buf),
        }
    }
}

impl<S: Read + Write> Write for TlsReadyStream<S> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            TlsReadyStream::Plain(stream) => stream.write(buf),
            TlsReadyStream::Tls(stream) => stream.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self {
            TlsReadyStream::Plain(stream) => stream.flush(),
            TlsReadyStream::Tls(stream) => stream.flush(),
        }
    }
}

impl<S: ConnectionInfoProvider> ConnectionInfoProvider for TlsReadyStream<S> {
    fn connection_info(&self) -> &ConnectionInfo {
        match self {
            TlsReadyStream::Plain(stream) => stream.connection_info(),
            TlsReadyStream::Tls(stream) => stream.connection_info(),
        }
    }
}

#[cfg(feature = "mio")]
impl<S: Source> Source for TlsReadyStream<S> {
    fn register(&mut self, registry: &Registry, token: Token, interests: Interest) -> io::Result<()> {
        match self {
            TlsReadyStream::Plain(stream) => registry.register(stream, token, interests),
            TlsReadyStream::Tls(stream) => registry.register(stream, token, interests),
        }
    }

    fn reregister(&mut self, registry: &Registry, token: Token, interests: Interest) -> io::Result<()> {
        match self {
            TlsReadyStream::Plain(stream) => registry.reregister(stream, token, interests),
            TlsReadyStream::Tls(stream) => registry.reregister(stream, token, interests),
        }
    }

    fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
        match self {
            TlsReadyStream::Plain(stream) => registry.deregister(stream),
            TlsReadyStream::Tls(stream) => registry.deregister(stream),
        }
    }
}

impl<S: Selectable> Selectable for TlsReadyStream<S> {
    fn connected(&mut self) -> io::Result<bool> {
        match self {
            TlsReadyStream::Plain(stream) => stream.connected(),
            TlsReadyStream::Tls(stream) => stream.connected(),
        }
    }

    fn make_writable(&mut self) -> io::Result<()> {
        match self {
            TlsReadyStream::Plain(stream) => stream.make_writable(),
            TlsReadyStream::Tls(stream) => stream.make_writable(),
        }
    }

    fn make_readable(&mut self) -> io::Result<()> {
        match self {
            TlsReadyStream::Plain(stream) => stream.make_readable(),
            TlsReadyStream::Tls(stream) => stream.make_readable(),
        }
    }
}