1use std::{
2 io::{self, Read, Write},
3 net::{SocketAddr, TcpStream},
4 sync::{Arc, Mutex},
5 time::Duration,
6};
7
8use rustls::{ServerConnection, StreamOwned};
9
10#[derive(Debug, Clone)]
11pub struct RustlsConnection(Arc<Mutex<StreamOwned<ServerConnection, TcpStream>>>);
12
13impl RustlsConnection {
14 pub(crate) fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
15 let stream = self.0.lock().unwrap();
16 stream.get_ref().set_read_timeout(timeout)?;
17 Ok(())
18 }
19
20 pub(crate) fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
21 let stream = self.0.lock().unwrap();
22 stream.get_ref().set_nodelay(nodelay)?;
23 Ok(())
24 }
25
26 pub(crate) fn into_inner(self) -> Result<StreamOwned<ServerConnection, TcpStream>, Self> {
27 match Arc::try_unwrap(self.0) {
28 Ok(conn) => Ok(conn.into_inner().unwrap()),
29 Err(err) => Err(Self(err)),
30 }
31 }
32}
33
34impl From<StreamOwned<ServerConnection, TcpStream>> for RustlsConnection {
35 fn from(tls: StreamOwned<ServerConnection, TcpStream>) -> Self {
36 RustlsConnection(Arc::new(Mutex::new(tls)))
37 }
38}
39
40impl RustlsConnection {
41 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
42 self.0
43 .lock()
44 .map_err(|_err| io::Error::new(io::ErrorKind::Other, "Failed to aquire lock"))?
45 .sock
46 .peer_addr()
47 }
48
49 pub fn local_addr(&self) -> io::Result<SocketAddr> {
50 self.0
51 .lock()
52 .map_err(|_err| io::Error::new(io::ErrorKind::Other, "Failed to aquire lock"))?
53 .sock
54 .local_addr()
55 }
56}
57
58impl Read for RustlsConnection {
59 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
60 self.0
61 .lock()
62 .map_err(|_err| io::Error::new(io::ErrorKind::Other, "Failed to aquire lock"))?
63 .read(buf)
64 }
65}
66
67impl Write for RustlsConnection {
68 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
69 self.0
70 .lock()
71 .map_err(|_err| io::Error::new(io::ErrorKind::Other, "Failed to aquire lock"))?
72 .write(buf)
73 }
74
75 fn flush(&mut self) -> io::Result<()> {
76 self.0
77 .lock()
78 .map_err(|_err| io::Error::new(io::ErrorKind::Other, "Failed to aquire lock"))?
79 .flush()
80 }
81}