aboutsummaryrefslogtreecommitdiff
path: root/net/src/transports/tls.rs
blob: 8a43d7daa9461292e4ba922a6c71321066a27ace (plain)
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
use std::sync::Arc;

use async_rustls::{rustls, TlsAcceptor, TlsConnector, TlsStream};
use async_trait::async_trait;
use smol::{
    io::{split, AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf},
    lock::Mutex,
    net::{TcpListener, TcpStream},
};

use crate::{
    connection::{Connection, ToConn},
    endpoint::{Addr, Endpoint, Port},
    listener::{ConnListener, ToListener},
    Error, Result,
};

/// TLS network connection implementation of the [`Connection`] trait.
pub struct TlsConn {
    inner: TcpStream,
    read: Mutex<ReadHalf<TlsStream<TcpStream>>>,
    write: Mutex<WriteHalf<TlsStream<TcpStream>>>,
}

impl TlsConn {
    /// Creates a new TlsConn
    pub fn new(sock: TcpStream, conn: TlsStream<TcpStream>) -> Self {
        let (read, write) = split(conn);
        Self {
            inner: sock,
            read: Mutex::new(read),
            write: Mutex::new(write),
        }
    }
}

#[async_trait]
impl Connection for TlsConn {
    fn peer_endpoint(&self) -> Result<Endpoint> {
        Ok(Endpoint::new_tls_addr(&self.inner.peer_addr()?))
    }

    fn local_endpoint(&self) -> Result<Endpoint> {
        Ok(Endpoint::new_tls_addr(&self.inner.local_addr()?))
    }

    async fn read(&self, buf: &mut [u8]) -> Result<usize> {
        self.read.lock().await.read(buf).await.map_err(Error::from)
    }

    async fn write(&self, buf: &[u8]) -> Result<usize> {
        self.write
            .lock()
            .await
            .write(buf)
            .await
            .map_err(Error::from)
    }
}

/// Connects to the given TLS address and port.
pub async fn dial_tls(
    addr: &Addr,
    port: &Port,
    config: rustls::ClientConfig,
    dns_name: &str,
) -> Result<TlsConn> {
    let address = format!("{}:{}", addr, port);

    let connector = TlsConnector::from(Arc::new(config));

    let sock = TcpStream::connect(&address).await?;
    sock.set_nodelay(true)?;

    let altname = rustls::ServerName::try_from(dns_name)?;
    let conn = connector.connect(altname, sock.clone()).await?;
    Ok(TlsConn::new(sock, TlsStream::Client(conn)))
}

/// Connects to the given TLS endpoint, returns `Conn` ([`Connection`]).
pub async fn dial(
    endpoint: &Endpoint,
    config: rustls::ClientConfig,
    dns_name: &str,
) -> Result<Box<dyn Connection>> {
    match endpoint {
        Endpoint::Tcp(..) | Endpoint::Tls(..) => {}
        _ => return Err(Error::InvalidEndpoint(endpoint.to_string())),
    }

    dial_tls(endpoint.addr()?, endpoint.port()?, config, dns_name)
        .await
        .map(|c| Box::new(c) as Box<dyn Connection>)
}
/// Tls network listener implementation of the `Listener` [`ConnListener`] trait.
pub struct TlsListener {
    acceptor: TlsAcceptor,
    listener: TcpListener,
}

#[async_trait]
impl ConnListener for TlsListener {
    fn local_endpoint(&self) -> Result<Endpoint> {
        Ok(Endpoint::new_tls_addr(&self.listener.local_addr()?))
    }

    async fn accept(&self) -> Result<Box<dyn Connection>> {
        let (sock, _) = self.listener.accept().await?;
        sock.set_nodelay(true)?;
        let conn = self.acceptor.accept(sock.clone()).await?;
        Ok(Box::new(TlsConn::new(sock, TlsStream::Server(conn))))
    }
}

/// Listens on the given TLS address and port.
pub async fn listen_tls(
    addr: &Addr,
    port: &Port,
    config: rustls::ServerConfig,
) -> Result<TlsListener> {
    let address = format!("{}:{}", addr, port);
    let acceptor = TlsAcceptor::from(Arc::new(config));
    let listener = TcpListener::bind(&address).await?;
    Ok(TlsListener { acceptor, listener })
}

/// Listens on the given TLS endpoint, returns `Listener` [`ConnListener`].
pub async fn listen(
    endpoint: &Endpoint,
    config: rustls::ServerConfig,
) -> Result<Box<dyn ConnListener>> {
    match endpoint {
        Endpoint::Tcp(..) | Endpoint::Tls(..) => {}
        _ => return Err(Error::InvalidEndpoint(endpoint.to_string())),
    }

    listen_tls(endpoint.addr()?, endpoint.port()?, config)
        .await
        .map(|l| Box::new(l) as Box<dyn ConnListener>)
}

impl From<TlsStream<TcpStream>> for Box<dyn Connection> {
    fn from(conn: TlsStream<TcpStream>) -> Self {
        Box::new(TlsConn::new(conn.get_ref().0.clone(), conn))
    }
}

impl From<TlsListener> for Box<dyn ConnListener> {
    fn from(listener: TlsListener) -> Self {
        Box::new(listener)
    }
}

impl ToConn for TlsStream<TcpStream> {
    fn to_conn(self) -> Box<dyn Connection> {
        self.into()
    }
}

impl ToConn for TlsConn {
    fn to_conn(self) -> Box<dyn Connection> {
        Box::new(self)
    }
}

impl ToListener for TlsListener {
    fn to_listener(self) -> Box<dyn ConnListener> {
        self.into()
    }
}