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 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 let duplicate = unsafe { libc::dup(fd) };
30 if duplicate == -1 {
31 None
32 } else {
33 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>;