tokio_tungstenite/
tls.rs

1//! Connection helper.
2use tokio::io::{AsyncRead, AsyncWrite};
3
4use tungstenite::{
5    client::uri_mode, error::Error, handshake::client::Response, protocol::WebSocketConfig,
6};
7
8use crate::{client_async_with_config, IntoClientRequest, WebSocketStream};
9
10pub use crate::stream::MaybeTlsStream;
11
12/// A connector that can be used when establishing connections, allowing to control whether
13/// `native-tls` or `rustls` is used to create a TLS connection. Or TLS can be disabled with the
14/// `Plain` variant.
15#[non_exhaustive]
16#[derive(Clone)]
17pub enum Connector {
18    /// Plain (non-TLS) connector.
19    Plain,
20    /// `native-tls` TLS connector.
21    #[cfg(feature = "native-tls")]
22    NativeTls(native_tls_crate::TlsConnector),
23    /// `rustls` TLS connector.
24    #[cfg(feature = "__rustls-tls")]
25    Rustls(std::sync::Arc<rustls::ClientConfig>),
26}
27
28mod encryption {
29    #[cfg(feature = "native-tls")]
30    pub mod native_tls {
31        use native_tls_crate::TlsConnector;
32        use tokio_native_tls::TlsConnector as TokioTlsConnector;
33
34        use tokio::io::{AsyncRead, AsyncWrite};
35
36        use tungstenite::{error::TlsError, stream::Mode, Error};
37
38        use crate::stream::MaybeTlsStream;
39
40        pub async fn wrap_stream<S>(
41            socket: S,
42            domain: String,
43            mode: Mode,
44            tls_connector: Option<TlsConnector>,
45        ) -> Result<MaybeTlsStream<S>, Error>
46        where
47            S: 'static + AsyncRead + AsyncWrite + Send + Unpin,
48        {
49            match mode {
50                Mode::Plain => Ok(MaybeTlsStream::Plain(socket)),
51                Mode::Tls => {
52                    let try_connector = tls_connector.map_or_else(TlsConnector::new, Ok);
53                    let connector = try_connector.map_err(TlsError::Native)?;
54                    let stream = TokioTlsConnector::from(connector);
55                    let connected = stream.connect(&domain, socket).await;
56                    match connected {
57                        Err(e) => Err(Error::Tls(e.into())),
58                        Ok(s) => Ok(MaybeTlsStream::NativeTls(s)),
59                    }
60                }
61            }
62        }
63    }
64
65    #[cfg(feature = "__rustls-tls")]
66    pub mod rustls {
67        pub use rustls::ClientConfig;
68        use rustls::RootCertStore;
69        use rustls_pki_types::ServerName;
70        use tokio_rustls::TlsConnector as TokioTlsConnector;
71
72        use std::{convert::TryFrom, sync::Arc};
73        use tokio::io::{AsyncRead, AsyncWrite};
74
75        use tungstenite::{error::TlsError, stream::Mode, Error};
76
77        use crate::stream::MaybeTlsStream;
78
79        pub async fn wrap_stream<S>(
80            socket: S,
81            domain: String,
82            mode: Mode,
83            tls_connector: Option<Arc<ClientConfig>>,
84        ) -> Result<MaybeTlsStream<S>, Error>
85        where
86            S: 'static + AsyncRead + AsyncWrite + Send + Unpin,
87        {
88            match mode {
89                Mode::Plain => Ok(MaybeTlsStream::Plain(socket)),
90                Mode::Tls => {
91                    let config = match tls_connector {
92                        Some(config) => config,
93                        None => {
94                            #[allow(unused_mut)]
95                            let mut root_store = RootCertStore::empty();
96                            #[cfg(feature = "rustls-tls-native-roots")]
97                            {
98                                let native_certs = rustls_native_certs::load_native_certs()?;
99                                let total_number = native_certs.len();
100                                let (number_added, number_ignored) =
101                                    root_store.add_parsable_certificates(native_certs);
102                                log::debug!("Added {number_added}/{total_number} native root certificates (ignored {number_ignored})");
103                            }
104                            #[cfg(feature = "rustls-tls-webpki-roots")]
105                            {
106                                root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
107                            }
108
109                            Arc::new(
110                                ClientConfig::builder()
111                                    .with_root_certificates(root_store)
112                                    .with_no_client_auth(),
113                            )
114                        }
115                    };
116                    let domain = ServerName::try_from(domain.as_str())
117                        .map_err(|_| TlsError::InvalidDnsName)?
118                        .to_owned();
119                    let stream = TokioTlsConnector::from(config);
120                    let connected = stream.connect(domain, socket).await;
121
122                    match connected {
123                        Err(e) => Err(Error::Io(e)),
124                        Ok(s) => Ok(MaybeTlsStream::Rustls(s)),
125                    }
126                }
127            }
128        }
129    }
130
131    pub mod plain {
132        use tokio::io::{AsyncRead, AsyncWrite};
133
134        use tungstenite::{
135            error::{Error, UrlError},
136            stream::Mode,
137        };
138
139        use crate::stream::MaybeTlsStream;
140
141        pub async fn wrap_stream<S>(socket: S, mode: Mode) -> Result<MaybeTlsStream<S>, Error>
142        where
143            S: 'static + AsyncRead + AsyncWrite + Send + Unpin,
144        {
145            match mode {
146                Mode::Plain => Ok(MaybeTlsStream::Plain(socket)),
147                Mode::Tls => Err(Error::Url(UrlError::TlsFeatureNotEnabled)),
148            }
149        }
150    }
151}
152
153/// Creates a WebSocket handshake from a request and a stream,
154/// upgrading the stream to TLS if required.
155#[cfg(any(feature = "native-tls", feature = "__rustls-tls"))]
156pub async fn client_async_tls<R, S>(
157    request: R,
158    stream: S,
159) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
160where
161    R: IntoClientRequest + Unpin,
162    S: 'static + AsyncRead + AsyncWrite + Send + Unpin,
163    MaybeTlsStream<S>: Unpin,
164{
165    client_async_tls_with_config(request, stream, None, None).await
166}
167
168/// The same as `client_async_tls()` but the one can specify a websocket configuration,
169/// and an optional connector. If no connector is specified, a default one will
170/// be created.
171///
172/// Please refer to `client_async_tls()` for more details.
173pub async fn client_async_tls_with_config<R, S>(
174    request: R,
175    stream: S,
176    config: Option<WebSocketConfig>,
177    connector: Option<Connector>,
178) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
179where
180    R: IntoClientRequest + Unpin,
181    S: 'static + AsyncRead + AsyncWrite + Send + Unpin,
182    MaybeTlsStream<S>: Unpin,
183{
184    let request = request.into_client_request()?;
185
186    #[cfg(any(feature = "native-tls", feature = "__rustls-tls"))]
187    let domain = crate::domain(&request)?;
188
189    // Make sure we check domain and mode first. URL must be valid.
190    let mode = uri_mode(request.uri())?;
191
192    let stream = match connector {
193        Some(conn) => match conn {
194            #[cfg(feature = "native-tls")]
195            Connector::NativeTls(conn) => {
196                self::encryption::native_tls::wrap_stream(stream, domain, mode, Some(conn)).await
197            }
198            #[cfg(feature = "__rustls-tls")]
199            Connector::Rustls(conn) => {
200                self::encryption::rustls::wrap_stream(stream, domain, mode, Some(conn)).await
201            }
202            Connector::Plain => self::encryption::plain::wrap_stream(stream, mode).await,
203        },
204        None => {
205            #[cfg(feature = "native-tls")]
206            {
207                self::encryption::native_tls::wrap_stream(stream, domain, mode, None).await
208            }
209            #[cfg(all(feature = "__rustls-tls", not(feature = "native-tls")))]
210            {
211                self::encryption::rustls::wrap_stream(stream, domain, mode, None).await
212            }
213            #[cfg(not(any(feature = "native-tls", feature = "__rustls-tls")))]
214            {
215                self::encryption::plain::wrap_stream(stream, mode).await
216            }
217        }
218    }?;
219
220    client_async_with_config(request, stream, config).await
221}