aboutsummaryrefslogtreecommitdiff
path: root/net/src/transports/tls.rs
blob: 476f495e5674e945bb7ebced83500ab6217e20be (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
use std::{net::SocketAddr, sync::Arc};

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

use crate::{
    connection::{Connection, ToConn},
    endpoint::Endpoint,
    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(
    endpoint: &Endpoint,
    config: rustls::ClientConfig,
    dns_name: &'static str,
) -> Result<TlsConn> {
    let addr = SocketAddr::try_from(endpoint.clone())?;

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

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

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

/// Tls network listener implementation of the `Listener` [`ConnListener`] trait.
pub struct TlsListener {
    inner: TcpListener,
    acceptor: TlsAcceptor,
}

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

    async fn accept(&self) -> Result<Box<dyn Connection>> {
        let (sock, _) = self.inner.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(endpoint: &Endpoint, config: rustls::ServerConfig) -> Result<TlsListener> {
    let addr = SocketAddr::try_from(endpoint.clone())?;
    let acceptor = TlsAcceptor::from(Arc::new(config));
    let listener = TcpListener::bind(addr).await?;
    Ok(TlsListener {
        acceptor,
        inner: listener,
    })
}

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()
    }
}