Skip to main content

trillium_rustls/client/
connector.rs

1use super::*;
2
3impl<C: Connector> RustlsConfig<C> {
4    fn tls_connector(&self, destination: &Destination) -> TlsConnector {
5        // A per-connection ALPN override replaces the config's default; absent one, the shared
6        // config is used as-is. Only clone the (otherwise shared) config when an override is
7        // present.
8        let rustls_config = if let Some(alpn) = destination.alpn() {
9            let mut config = (*self.rustls_config.0).clone();
10            config.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect();
11            Arc::new(config)
12        } else {
13            Arc::clone(&self.rustls_config.0)
14        };
15        rustls_config.into()
16    }
17}
18
19fn domain_server_name(destination: &Destination) -> Result<Option<ServerName<'static>>> {
20    destination
21        .host()
22        .map(|domain| {
23            ServerName::try_from(domain.to_owned()).map_err(|e| {
24                Error::new(
25                    ErrorKind::InvalidInput,
26                    format!("invalid server name {domain:?}: {e}"),
27                )
28            })
29        })
30        .transpose()
31}
32
33fn destination_server_name(destination: &Destination) -> Result<ServerName<'static>> {
34    if let Some(server_name) = domain_server_name(destination)? {
35        Ok(server_name)
36    } else {
37        let address = destination.addrs().first().ok_or_else(|| {
38            Error::new(
39                ErrorKind::InvalidInput,
40                "bare-ip destination has no socket address",
41            )
42        })?;
43        Ok(ServerName::IpAddress(address.ip().into()))
44    }
45}
46
47impl<C: Connector> Connector for RustlsConfig<C> {
48    type Runtime = C::Runtime;
49    type Transport = RustlsClientTransport<C::Transport>;
50    type Udp = C::Udp;
51
52    async fn connect(&self, url: &Url) -> Result<Self::Transport> {
53        self.connect_to(Destination::from_url(url)?).await
54    }
55
56    async fn connect_to(&self, destination: Destination) -> Result<Self::Transport> {
57        if !destination.secure() {
58            return self
59                .tcp_config
60                .connect_to(destination)
61                .await
62                .map(Into::into);
63        }
64
65        let connector = self.tls_connector(&destination);
66
67        // A domain destination's certificate identity (a DNS `ServerName`, sent via SNI) is fixed
68        // before the dial, so pre-resolved addresses can't influence validation. A host-less
69        // (bare-IP) destination has no SNI and validates against the address actually connected to,
70        // so its `IpAddress` server name is derived from the dialed stream below.
71        let domain_server_name = domain_server_name(&destination)?;
72
73        let stream = self
74            .tcp_config
75            .connect_to(destination.with_secure(false))
76            .await?;
77
78        let server_name = match domain_server_name {
79            Some(server_name) => server_name,
80            None => {
81                let ip = stream
82                    .peer_addr()?
83                    .ok_or_else(|| Error::other("no peer address for bare-ip destination"))?
84                    .ip();
85                ServerName::IpAddress(ip.into())
86            }
87        };
88
89        connector
90            .connect(server_name, stream)
91            .await
92            .map_err(|e| Error::other(e.to_string()))
93            .map(Into::into)
94    }
95
96    async fn connect_over(
97        &self,
98        transport: Box<dyn Transport>,
99        destination: Destination,
100    ) -> Result<Box<dyn Transport>> {
101        if !destination.secure() {
102            return self.tcp_config.connect_over(transport, destination).await;
103        }
104
105        let server_name = destination_server_name(&destination)?;
106        let connector = self.tls_connector(&destination);
107        let stream = connector
108            .connect(server_name, transport)
109            .await
110            .map_err(|e| Error::other(e.to_string()))?;
111        Ok(Box::new(RustlsClientTransport::<Box<dyn Transport>>::from(
112            stream,
113        )))
114    }
115
116    fn runtime(&self) -> Self::Runtime {
117        self.tcp_config.runtime()
118    }
119
120    async fn resolve(&self, host: &str, port: u16) -> Result<Vec<SocketAddr>> {
121        self.tcp_config.resolve(host, port).await
122    }
123}