rfc5321/
traits.rs

1use std::fmt::Debug;
2use std::os::fd::{AsRawFd, FromRawFd};
3use tokio::io::{AsyncRead, AsyncWrite};
4use tokio::net::TcpStream;
5use tokio_openssl::SslStream;
6use tokio_rustls::client::TlsStream as TlsClientStream;
7use tokio_rustls::server::TlsStream as TlsServerStream;
8
9pub trait AsyncReadAndWrite: AsyncRead + AsyncWrite + Debug + Unpin + Send + Sync {
10    /// Optionally clone a TcpStream that represents the same underlying
11    /// stream as this one.
12    /// This only has an impl that returns Some for TcpStream.
13    /// It is present to facilitate a workaround for some awkwardness
14    /// in the SslStream implementation for the failed-handshake case.
15    fn try_dup(&self) -> Option<TcpStream> {
16        None
17    }
18}
19impl AsyncReadAndWrite for TlsClientStream<TcpStream> {}
20impl AsyncReadAndWrite for TlsClientStream<BoxedAsyncReadAndWrite> {}
21impl AsyncReadAndWrite for TlsServerStream<TcpStream> {}
22impl AsyncReadAndWrite for TlsServerStream<BoxedAsyncReadAndWrite> {}
23
24impl AsyncReadAndWrite for TcpStream {
25    fn try_dup(&self) -> Option<TcpStream> {
26        let fd = self.as_raw_fd();
27        // SAFETY: dup creates a new fd without affecting the state
28        // of other descriptors
29        let duplicate = unsafe { libc::dup(fd) };
30        if duplicate == -1 {
31            None
32        } else {
33            // SAFETY: we're wrapping the new duplicate from above,
34            // which is fine, and provides a destructor for that fd
35            // when the TcpStream is dropped
36            let duplicate_stream = unsafe { std::net::TcpStream::from_raw_fd(duplicate) };
37            TcpStream::from_std(duplicate_stream).ok()
38        }
39    }
40}
41impl AsyncReadAndWrite for SslStream<TcpStream> {}
42impl AsyncReadAndWrite for SslStream<BoxedAsyncReadAndWrite> {}
43impl AsyncReadAndWrite for tokio::net::UnixStream {}
44
45pub type BoxedAsyncReadAndWrite = Box<dyn AsyncReadAndWrite>;