cyper_core/
backend.rs

1#[cfg(any(feature = "native-tls", feature = "rustls"))]
2use {compio::tls::TlsConnector, std::io};
3
4/// Represents TLS backend options
5#[derive(Debug, Clone)]
6#[non_exhaustive]
7pub enum TlsBackend {
8    /// Don't use TLS backend.
9    None,
10    /// Use [`native_tls`] as TLS backend.
11    #[cfg(feature = "native-tls")]
12    NativeTls,
13    /// Use [`rustls`] as TLS backend.
14    #[cfg(feature = "rustls")]
15    Rustls(Option<std::sync::Arc<compio::tls::rustls::ClientConfig>>),
16}
17
18impl Default for TlsBackend {
19    fn default() -> Self {
20        cfg_if::cfg_if! {
21            if #[cfg(feature = "native-tls")] {
22                Self::NativeTls
23            } else if #[cfg(feature = "rustls")] {
24                Self::Rustls(None)
25            } else {
26                Self::None
27            }
28        }
29    }
30}
31
32impl TlsBackend {
33    #[cfg(any(feature = "native-tls", feature = "rustls"))]
34    pub(crate) fn create_connector(&self) -> io::Result<TlsConnector> {
35        match self {
36            Self::None => Err(io::Error::other(
37                "could not create TLS connector without TLS backend",
38            )),
39            #[cfg(feature = "native-tls")]
40            Self::NativeTls => Ok(TlsConnector::from(
41                compio::tls::native_tls::TlsConnector::builder()
42                    .request_alpns(if cfg!(feature = "http2") {
43                        &["h2", "http/1.1"]
44                    } else {
45                        &["http/1.1"]
46                    })
47                    .build()
48                    .map_err(io::Error::other)?,
49            )),
50            #[cfg(feature = "rustls")]
51            Self::Rustls(config) => Ok(TlsConnector::from(if let Some(config) = config.clone() {
52                config
53            } else {
54                use std::sync::Arc;
55
56                use compio::rustls::ClientConfig;
57                use rustls_platform_verifier::ConfigVerifierExt;
58
59                let mut config =
60                    ClientConfig::with_platform_verifier().map_err(io::Error::other)?;
61                config.alpn_protocols = if cfg!(feature = "http2") {
62                    vec![b"h2".into(), b"http/1.1".into()]
63                } else {
64                    vec![b"http/1.1".into()]
65                };
66                config.key_log = Arc::new(compio::rustls::KeyLogFile::new());
67                Arc::new(config)
68            })),
69        }
70    }
71}