Skip to main content

trillium_native_tls/
client.rs

1use async_native_tls::{TlsConnector, TlsStream};
2use std::{
3    fmt::{Debug, Formatter},
4    io::{Error, IoSlice, IoSliceMut, Result},
5    net::SocketAddr,
6    pin::Pin,
7    sync::Arc,
8    task::{Context, Poll},
9};
10use trillium_server_common::{AsyncRead, AsyncWrite, Connector, Destination, Transport, Url};
11
12/// Configuration for the native tls client connector
13#[derive(Clone)]
14pub struct NativeTlsConfig<Config> {
15    /// configuration for the inner Connector (usually tcp)
16    pub tcp_config: Config,
17
18    /// native tls configuration
19    ///
20    /// Although async_native_tls calls this
21    /// a TlsConnector, it's actually a builder ¯\_(ツ)_/¯
22    pub tls_connector: Arc<TlsConnector>,
23}
24
25impl<C: Connector> NativeTlsConfig<C> {
26    /// replace the tcp config
27    pub fn with_tcp_config(mut self, config: C) -> Self {
28        self.tcp_config = config;
29        self
30    }
31}
32
33impl<C: Connector> From<C> for NativeTlsConfig<C> {
34    fn from(tcp_config: C) -> Self {
35        Self {
36            tcp_config,
37            tls_connector: Arc::new(TlsConnector::default()),
38        }
39    }
40}
41
42impl<Config: Debug> Debug for NativeTlsConfig<Config> {
43    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("NativeTlsConfig")
45            .field("tcp_config", &self.tcp_config)
46            .field("tls_connector", &format_args!(".."))
47            .finish()
48    }
49}
50
51impl<Config: Default> Default for NativeTlsConfig<Config> {
52    fn default() -> Self {
53        Self {
54            tcp_config: Config::default(),
55            tls_connector: Arc::new(TlsConnector::default()),
56        }
57    }
58}
59
60impl<Config> AsRef<Config> for NativeTlsConfig<Config> {
61    fn as_ref(&self) -> &Config {
62        &self.tcp_config
63    }
64}
65
66fn destination_host(destination: &Destination) -> Result<String> {
67    if let Some(host) = destination.host() {
68        Ok(host.to_owned())
69    } else {
70        Ok(destination
71            .addrs()
72            .first()
73            .ok_or_else(|| {
74                Error::new(
75                    std::io::ErrorKind::InvalidInput,
76                    "bare-ip destination has no socket address",
77                )
78            })?
79            .ip()
80            .to_string())
81    }
82}
83
84impl<T: Connector> Connector for NativeTlsConfig<T> {
85    type Runtime = T::Runtime;
86    type Transport = NativeTlsClientTransport<T::Transport>;
87    type Udp = T::Udp;
88
89    async fn connect(&self, url: &Url) -> Result<Self::Transport> {
90        self.connect_to(Destination::from_url(url)?).await
91    }
92
93    async fn connect_to(&self, destination: Destination) -> Result<Self::Transport> {
94        if !destination.secure() {
95            return self
96                .tcp_config
97                .connect_to(destination)
98                .await
99                .map(NativeTlsClientTransport::from);
100        }
101
102        // The server name comes from the destination, never the dialed address; capture a domain
103        // before the dial moves the destination, deferring the host-less (bare-IP) case to the
104        // address actually connected to.
105        let domain = destination.host().map(str::to_owned);
106        let inner_stream = self
107            .tcp_config
108            .connect_to(destination.with_secure(false))
109            .await?;
110        let host = match domain {
111            Some(domain) => domain,
112            None => inner_stream
113                .peer_addr()?
114                .ok_or_else(|| Error::other("no peer address for bare-ip destination"))?
115                .ip()
116                .to_string(),
117        };
118
119        // `destination.alpn()` is intentionally ignored: `async-native-tls` does not yet expose
120        // per-connection ALPN configuration. Honoring the override awaits the upstream ALPN support
121        // PR; until then this connector negotiates no ALPN (effectively h1-only).
122        self.tls_connector
123            .connect(host.as_str(), inner_stream)
124            .await
125            .map_err(|e| Error::other(e.to_string()))
126            .map(NativeTlsClientTransport::from)
127    }
128
129    async fn connect_over(
130        &self,
131        transport: Box<dyn Transport>,
132        destination: Destination,
133    ) -> Result<Box<dyn Transport>> {
134        if !destination.secure() {
135            return self.tcp_config.connect_over(transport, destination).await;
136        }
137
138        let host = destination_host(&destination)?;
139        let stream = self
140            .tls_connector
141            .connect(host.as_str(), transport)
142            .await
143            .map_err(|e| Error::other(e.to_string()))?;
144        Ok(Box::new(
145            NativeTlsClientTransport::<Box<dyn Transport>>::from(stream),
146        ))
147    }
148
149    fn runtime(&self) -> Self::Runtime {
150        self.tcp_config.runtime()
151    }
152
153    async fn resolve(&self, host: &str, port: u16) -> Result<Vec<SocketAddr>> {
154        self.tcp_config.resolve(host, port).await
155    }
156}
157
158/// Client [`Transport`] for the native tls connector
159///
160/// This may represent either an encrypted tls connection or a plaintext
161/// connection
162
163#[derive(Debug)]
164pub struct NativeTlsClientTransport<T>(NativeTlsClientTransportInner<T>);
165
166impl<T: AsyncWrite + AsyncRead + Unpin> NativeTlsClientTransport<T> {
167    /// Borrow the TlsStream, if this connection is tls.
168    ///
169    /// Returns None otherwise
170    pub fn as_tls(&self) -> Option<&TlsStream<T>> {
171        match &self.0 {
172            Tcp(_) => None,
173            Tls(tls) => Some(tls),
174        }
175    }
176}
177
178impl<T> From<T> for NativeTlsClientTransport<T> {
179    fn from(value: T) -> Self {
180        Self(Tcp(value))
181    }
182}
183
184impl<T> From<TlsStream<T>> for NativeTlsClientTransport<T> {
185    fn from(value: TlsStream<T>) -> Self {
186        Self(Tls(value))
187    }
188}
189
190impl<T: Transport> AsRef<T> for NativeTlsClientTransport<T> {
191    fn as_ref(&self) -> &T {
192        match &self.0 {
193            Tcp(transport) => transport,
194            Tls(tls_stream) => tls_stream.get_ref(),
195        }
196    }
197}
198
199#[derive(Debug)]
200enum NativeTlsClientTransportInner<T> {
201    Tcp(T),
202    Tls(TlsStream<T>),
203}
204use NativeTlsClientTransportInner::{Tcp, Tls};
205
206impl<T: AsyncRead + AsyncWrite + Unpin> AsyncRead for NativeTlsClientTransport<T> {
207    fn poll_read(
208        mut self: Pin<&mut Self>,
209        cx: &mut Context<'_>,
210        buf: &mut [u8],
211    ) -> Poll<Result<usize>> {
212        match &mut self.0 {
213            Tcp(t) => Pin::new(t).poll_read(cx, buf),
214            Tls(t) => Pin::new(t).poll_read(cx, buf),
215        }
216    }
217
218    fn poll_read_vectored(
219        mut self: Pin<&mut Self>,
220        cx: &mut Context<'_>,
221        bufs: &mut [IoSliceMut<'_>],
222    ) -> Poll<Result<usize>> {
223        match &mut self.0 {
224            Tcp(t) => Pin::new(t).poll_read_vectored(cx, bufs),
225            Tls(t) => Pin::new(t).poll_read_vectored(cx, bufs),
226        }
227    }
228}
229
230impl<T: AsyncRead + AsyncWrite + Unpin> AsyncWrite for NativeTlsClientTransport<T> {
231    fn poll_write(
232        mut self: Pin<&mut Self>,
233        cx: &mut Context<'_>,
234        buf: &[u8],
235    ) -> Poll<Result<usize>> {
236        match &mut self.0 {
237            Tcp(t) => Pin::new(t).poll_write(cx, buf),
238            Tls(t) => Pin::new(t).poll_write(cx, buf),
239        }
240    }
241
242    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
243        match &mut self.0 {
244            Tcp(t) => Pin::new(t).poll_flush(cx),
245            Tls(t) => Pin::new(t).poll_flush(cx),
246        }
247    }
248
249    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
250        match &mut self.0 {
251            Tcp(t) => Pin::new(t).poll_close(cx),
252            Tls(t) => Pin::new(t).poll_close(cx),
253        }
254    }
255
256    fn poll_write_vectored(
257        mut self: Pin<&mut Self>,
258        cx: &mut Context<'_>,
259        bufs: &[IoSlice<'_>],
260    ) -> Poll<Result<usize>> {
261        match &mut self.0 {
262            Tcp(t) => Pin::new(t).poll_write_vectored(cx, bufs),
263            Tls(t) => Pin::new(t).poll_write_vectored(cx, bufs),
264        }
265    }
266}
267
268impl<T: Transport> Transport for NativeTlsClientTransport<T> {
269    fn peer_addr(&self) -> Result<Option<SocketAddr>> {
270        self.as_ref().peer_addr()
271    }
272
273    // `negotiated_alpn` is left at the trait default (`None`). `native-tls` exposes the negotiated
274    // ALPN protocol via `TlsStream::negotiated_alpn` (gated on the `alpn` feature), but the
275    // `async-native-tls` 0.6 wrapper keeps its inner `native_tls::TlsStream` private and offers no
276    // accessor for it, so we cannot reach the value from here. Lift this once async-native-tls
277    // exposes the read side.
278}