async_tungstenite/tokio/
rustls.rs

1use real_tokio_rustls::rustls::{ClientConfig, RootCertStore};
2use real_tokio_rustls::{client::TlsStream, TlsConnector};
3use rustls_pki_types::ServerName;
4
5use tungstenite::client::{uri_mode, IntoClientRequest};
6use tungstenite::error::TlsError;
7use tungstenite::handshake::client::Request;
8use tungstenite::stream::Mode;
9use tungstenite::Error;
10
11use std::convert::TryFrom;
12
13use crate::stream::Stream as StreamSwitcher;
14use crate::{client_async_with_config, domain, Response, WebSocketConfig, WebSocketStream};
15
16use super::TokioAdapter;
17
18/// A stream that might be protected with TLS.
19pub type MaybeTlsStream<S> = StreamSwitcher<TokioAdapter<S>, TokioAdapter<TlsStream<S>>>;
20
21pub type AutoStream<S> = MaybeTlsStream<S>;
22
23pub type Connector = TlsConnector;
24
25async fn wrap_stream<S>(
26    socket: S,
27    domain: String,
28    connector: Option<Connector>,
29    mode: Mode,
30) -> Result<AutoStream<S>, Error>
31where
32    S: 'static + tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
33{
34    match mode {
35        Mode::Plain => Ok(StreamSwitcher::Plain(TokioAdapter::new(socket))),
36        Mode::Tls => {
37            let stream = {
38                let connector = if let Some(connector) = connector {
39                    connector
40                } else {
41                    #[cfg(feature = "tokio-rustls-manual-roots")]
42                    log::error!("tokio-rustls-manual-roots was selected, but no connector was provided! No certificates can be verified in this state.");
43
44                    #[cfg(feature = "tokio-rustls-manual-roots")]
45                    let root_store = RootCertStore::empty();
46                    #[cfg(not(feature = "tokio-rustls-manual-roots"))]
47                    let mut root_store = RootCertStore::empty();
48
49                    #[cfg(feature = "tokio-rustls-native-certs")]
50                    {
51                        let mut native_certs = rustls_native_certs::load_native_certs();
52                        if let Some(err) = native_certs.errors.drain(..).next() {
53                            return Err(std::io::Error::new(std::io::ErrorKind::Other, err).into());
54                        }
55                        let native_certs = native_certs.certs;
56                        let total_number = native_certs.len();
57                        let (number_added, number_ignored) =
58                            root_store.add_parsable_certificates(native_certs);
59                        log::debug!("Added {number_added}/{total_number} native root certificates (ignored {number_ignored})");
60                    }
61                    #[cfg(all(
62                        feature = "tokio-rustls-webpki-roots",
63                        not(feature = "tokio-rustls-native-certs"),
64                        not(feature = "tokio-rustls-manual-roots")
65                    ))]
66                    {
67                        root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
68                    }
69                    TlsConnector::from(std::sync::Arc::new(
70                        ClientConfig::builder()
71                            .with_root_certificates(root_store)
72                            .with_no_client_auth(),
73                    ))
74                };
75                let domain = ServerName::try_from(domain)
76                    .map_err(|_| Error::Tls(TlsError::InvalidDnsName))?;
77                connector.connect(domain, socket).await?
78            };
79            Ok(StreamSwitcher::Tls(TokioAdapter::new(stream)))
80        }
81    }
82}
83
84/// Creates a WebSocket handshake from a request and a stream,
85/// upgrading the stream to TLS if required and using the given
86/// connector and WebSocket configuration.
87pub async fn client_async_tls_with_connector_and_config<R, S>(
88    request: R,
89    stream: S,
90    connector: Option<Connector>,
91    config: Option<WebSocketConfig>,
92) -> Result<(WebSocketStream<AutoStream<S>>, Response), Error>
93where
94    R: IntoClientRequest + Unpin,
95    S: 'static + tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
96    AutoStream<S>: Unpin,
97{
98    let request: Request = request.into_client_request()?;
99
100    let domain = domain(&request)?;
101
102    // Make sure we check domain and mode first. URL must be valid.
103    let mode = uri_mode(request.uri())?;
104
105    let stream = wrap_stream(stream, domain, connector, mode).await?;
106    client_async_with_config(request, stream, config).await
107}