1use std::{
2 io,
3 net::{IpAddr, Ipv4Addr},
4 pin::Pin,
5 sync::Arc,
6 task::{Context, Poll},
7 time::Duration,
8};
9
10use rustls_pki_types::{self as pki_types, CertificateDer};
11
12use karyon_core::{
13 async_runtime::io::{AsyncRead, AsyncWrite},
14 async_util::timeout,
15};
16
17#[cfg(feature = "tokio")]
18use tokio::io::ReadBuf;
19
20use crate::{
21 ACCEPT_HANDSHAKE_TIMEOUT, Addr, ByteStream, Endpoint, Error, Result,
22 async_rustls::{TlsAcceptor, TlsConnector, TlsStream, rustls},
23 layer::{ClientLayer, ServerLayer},
24 transports::tcp::TcpListener,
25};
26
27#[derive(Clone)]
29pub struct ClientTlsConfig {
30 pub client_config: rustls::ClientConfig,
31 pub dns_name: String,
32}
33
34#[derive(Clone)]
36pub struct ServerTlsConfig {
37 pub server_config: rustls::ServerConfig,
38}
39
40#[derive(Clone)]
59pub struct TlsLayer {
60 client_config: Option<ClientTlsConfig>,
61 server_config: Option<ServerTlsConfig>,
62}
63
64impl TlsLayer {
65 pub fn client(config: ClientTlsConfig) -> Self {
67 Self {
68 client_config: Some(config),
69 server_config: None,
70 }
71 }
72
73 pub fn server(config: ServerTlsConfig) -> Self {
75 Self {
76 client_config: None,
77 server_config: Some(config),
78 }
79 }
80}
81
82impl ClientLayer<Box<dyn ByteStream>, Box<dyn ByteStream>> for TlsLayer {
83 async fn handshake(&self, stream: Box<dyn ByteStream>) -> Result<Box<dyn ByteStream>> {
84 let config = self.client_config.as_ref().ok_or_else(|| {
85 Error::IO(io::Error::new(
86 io::ErrorKind::InvalidInput,
87 "missing TLS client config",
88 ))
89 })?;
90
91 let connector = TlsConnector::from(Arc::new(config.client_config.clone()));
92 let dns = pki_types::ServerName::try_from(config.dns_name.clone())?;
93
94 let peer = stream.peer_endpoint();
95 let local = stream.local_endpoint();
96 let tls = connector.connect(dns, stream).await?;
97
98 Ok(Box::new(TlsByteStream {
99 inner: TlsStream::Client(tls),
100 peer_endpoint: peer,
101 local_endpoint: local,
102 }))
103 }
104}
105
106impl ServerLayer<Box<dyn ByteStream>, Box<dyn ByteStream>> for TlsLayer {
107 async fn handshake(&self, stream: Box<dyn ByteStream>) -> Result<Box<dyn ByteStream>> {
108 let config = self.server_config.as_ref().ok_or_else(|| {
109 Error::IO(io::Error::new(
110 io::ErrorKind::InvalidInput,
111 "missing TLS server config",
112 ))
113 })?;
114
115 let acceptor = TlsAcceptor::from(Arc::new(config.server_config.clone()));
116
117 let peer = stream.peer_endpoint();
118 let local = stream.local_endpoint();
119 let tls = acceptor.accept(stream).await?;
120
121 Ok(Box::new(TlsByteStream {
122 inner: TlsStream::Server(tls),
123 peer_endpoint: peer,
124 local_endpoint: local,
125 }))
126 }
127}
128
129pub struct TlsByteStream {
131 inner: TlsStream<Box<dyn ByteStream>>,
132 peer_endpoint: Option<Endpoint>,
133 local_endpoint: Option<Endpoint>,
134}
135
136impl ByteStream for TlsByteStream {
137 fn peer_endpoint(&self) -> Option<Endpoint> {
138 self.peer_endpoint.clone()
139 }
140 fn local_endpoint(&self) -> Option<Endpoint> {
141 self.local_endpoint.clone()
142 }
143 fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
144 let (_, state) = self.inner.get_ref();
148 state
149 .peer_certificates()
150 .map(|certs| certs.iter().map(|c| c.clone().into_owned()).collect())
151 }
152}
153
154#[cfg(feature = "smol")]
157impl AsyncRead for TlsByteStream {
158 fn poll_read(
159 mut self: Pin<&mut Self>,
160 cx: &mut Context<'_>,
161 buf: &mut [u8],
162 ) -> Poll<io::Result<usize>> {
163 Pin::new(&mut self.inner).poll_read(cx, buf)
164 }
165}
166
167#[cfg(feature = "tokio")]
168impl AsyncRead for TlsByteStream {
169 fn poll_read(
170 mut self: Pin<&mut Self>,
171 cx: &mut Context<'_>,
172 buf: &mut ReadBuf<'_>,
173 ) -> Poll<io::Result<()>> {
174 Pin::new(&mut self.inner).poll_read(cx, buf)
175 }
176}
177
178#[cfg(feature = "smol")]
179impl AsyncWrite for TlsByteStream {
180 fn poll_write(
181 mut self: Pin<&mut Self>,
182 cx: &mut Context<'_>,
183 buf: &[u8],
184 ) -> Poll<io::Result<usize>> {
185 Pin::new(&mut self.inner).poll_write(cx, buf)
186 }
187
188 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
189 Pin::new(&mut self.inner).poll_flush(cx)
190 }
191
192 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
193 Pin::new(&mut self.inner).poll_close(cx)
194 }
195}
196
197#[cfg(feature = "tokio")]
198impl AsyncWrite for TlsByteStream {
199 fn poll_write(
200 mut self: Pin<&mut Self>,
201 cx: &mut Context<'_>,
202 buf: &[u8],
203 ) -> Poll<io::Result<usize>> {
204 Pin::new(&mut self.inner).poll_write(cx, buf)
205 }
206
207 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
208 Pin::new(&mut self.inner).poll_flush(cx)
209 }
210
211 fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
212 Pin::new(&mut self.inner).poll_shutdown(cx)
213 }
214}
215
216pub struct TlsListener {
218 inner: TcpListener,
219 layer: TlsLayer,
220 handshake_timeout: Duration,
222}
223
224impl TlsListener {
225 pub fn new(inner: TcpListener, config: ServerTlsConfig) -> Self {
227 Self {
228 inner,
229 layer: TlsLayer::server(config),
230 handshake_timeout: ACCEPT_HANDSHAKE_TIMEOUT,
231 }
232 }
233
234 pub fn with_handshake_timeout(mut self, timeout: Duration) -> Self {
236 self.handshake_timeout = timeout;
237 self
238 }
239
240 pub async fn accept(&self) -> Result<Box<dyn ByteStream>> {
245 let stream = self.inner.accept().await?;
246 timeout(
247 self.handshake_timeout,
248 ServerLayer::handshake(&self.layer, stream),
249 )
250 .await?
251 }
252
253 pub fn local_endpoint(&self) -> Result<Endpoint> {
255 let tcp_ep = self.inner.local_endpoint()?;
256 let port = tcp_ep.port().unwrap_or(0);
257 let addr = tcp_ep
258 .addr()
259 .unwrap_or(Addr::Ip(IpAddr::V4(Ipv4Addr::UNSPECIFIED)));
260 Ok(Endpoint::Tls(addr, port))
261 }
262}