use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use rustls::ClientConfig as TlsConfig;
use rustls::crypto::CryptoProvider;
use rustls_platform_verifier::Verifier;
use crate::device::{DeviceKeyStore, DevicePlatform, HardwareDeviceKey, StoreChoice};
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ClientConfig {
pub app_id: String,
pub data_dir: PathBuf,
pub device_store: StoreChoice,
pub device_platform: DevicePlatform,
pub reconnect_window: Duration,
pub connect_timeout: Duration,
pub crypto_provider: Option<Arc<CryptoProvider>>,
pub video_h264: bool,
#[cfg(feature = "testing")]
pub testing: TestingOverrides,
}
impl ClientConfig {
pub fn new(app_id: &str, data_dir: PathBuf) -> ClientConfig {
ClientConfig {
app_id: app_id.to_owned(),
data_dir,
device_store: StoreChoice::Auto,
device_platform: crate::device::default_platform(),
reconnect_window: Duration::from_secs(20),
connect_timeout: Duration::from_secs(20),
crypto_provider: None,
video_h264: default_video_h264(),
#[cfg(feature = "testing")]
testing: TestingOverrides::default(),
}
}
pub fn with_video_h264(mut self, on: bool) -> ClientConfig {
self.video_h264 = on;
self
}
pub fn with_device_key_store(mut self, store: Arc<dyn DeviceKeyStore>) -> ClientConfig {
self.device_store = StoreChoice::Host(store);
self
}
pub fn with_hardware_device_key(mut self, key: Arc<dyn HardwareDeviceKey>) -> ClientConfig {
self.device_store = StoreChoice::Hardware(key);
self
}
pub fn with_device_platform(mut self, platform: DevicePlatform) -> ClientConfig {
self.device_platform = platform;
self
}
pub fn with_crypto_provider(mut self, provider: Arc<CryptoProvider>) -> ClientConfig {
self.crypto_provider = Some(provider);
self
}
}
pub const fn default_video_h264() -> bool {
!cfg!(target_os = "linux")
}
#[cfg(feature = "testing")]
#[derive(Clone, Debug, Default)]
pub struct TestingOverrides {
pub extra_roots: Vec<Vec<u8>>,
pub resolve: Vec<(String, IpAddr)>,
pub source_ip: Arc<std::sync::RwLock<Option<IpAddr>>>,
pub first_seq: Option<u16>,
pub drop_video_packets: Arc<std::sync::atomic::AtomicU32>,
}
#[cfg(feature = "testing")]
pub(crate) fn drop_video_packet(cfg: &ClientConfig) -> bool {
use std::sync::atomic::Ordering;
cfg.testing
.drop_video_packets
.try_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1))
.is_ok()
}
#[cfg(not(feature = "testing"))]
pub(crate) fn drop_video_packet(_cfg: &ClientConfig) -> bool {
false
}
#[cfg(feature = "testing")]
pub(crate) fn source_ip(cfg: &ClientConfig) -> Option<IpAddr> {
cfg.testing.source_ip.read().ok().and_then(|g| *g)
}
#[cfg(not(feature = "testing"))]
pub(crate) fn source_ip(_cfg: &ClientConfig) -> Option<IpAddr> {
None
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ProviderSource {
Caller,
ProcessDefault,
#[cfg_attr(not(feature = "builtin-ring-provider"), allow(dead_code))]
BuiltIn,
}
impl ProviderSource {
fn as_str(self) -> &'static str {
match self {
ProviderSource::Caller => "caller",
ProviderSource::ProcessDefault => "process default",
ProviderSource::BuiltIn => "built-in",
}
}
}
#[cfg(not(feature = "builtin-ring-provider"))]
pub(crate) const NO_CRYPTO_PROVIDER: &str = "no_crypto_provider";
pub(crate) fn crypto_provider(
explicit: Option<&Arc<CryptoProvider>>,
) -> Result<Arc<CryptoProvider>, rustls::Error> {
let (provider, source) = choose_provider(explicit, CryptoProvider::get_default())?;
log_choice(&provider, source);
Ok(provider)
}
fn choose_provider(
explicit: Option<&Arc<CryptoProvider>>,
default: Option<&Arc<CryptoProvider>>,
) -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
if let Some(p) = explicit {
return Ok((p.clone(), ProviderSource::Caller));
}
if let Some(p) = default {
return Ok((p.clone(), ProviderSource::ProcessDefault));
}
builtin_provider()
}
#[cfg(feature = "builtin-ring-provider")]
fn builtin_provider() -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
Ok((
Arc::new(rustls::crypto::ring::default_provider()),
ProviderSource::BuiltIn,
))
}
#[cfg(not(feature = "builtin-ring-provider"))]
fn builtin_provider() -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
Err(rustls::Error::General(format!(
"{NO_CRYPTO_PROVIDER}: no rustls crypto provider was passed \
(ClientConfig::with_crypto_provider) or installed as the process default, and the \
built-in one is off (feature `builtin-ring-provider`)"
)))
}
pub(crate) fn provider_name(p: &CryptoProvider) -> String {
format!("{:?}", p.secure_random)
}
fn log_choice(provider: &CryptoProvider, source: ProviderSource) {
static LAST: std::sync::Mutex<Option<(String, ProviderSource)>> = std::sync::Mutex::new(None);
let choice = (provider_name(provider), source);
let mut last = LAST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if last.as_ref() != Some(&choice) {
tracing::info!("tls provider: {} ({})", choice.0, source.as_str());
*last = Some(choice);
}
}
pub(crate) fn tls_config(cfg: &ClientConfig) -> Result<Arc<TlsConfig>, rustls::Error> {
let provider = crypto_provider(cfg.crypto_provider.as_ref())?;
#[cfg(feature = "testing")]
let verifier = if cfg.testing.extra_roots.is_empty() {
Verifier::new(provider.clone())?
} else {
let extra = cfg
.testing
.extra_roots
.iter()
.map(|d| rustls::pki_types::CertificateDer::from(d.clone()));
Verifier::new_with_extra_roots(extra, provider.clone())?
};
#[cfg(not(feature = "testing"))]
let verifier = {
let _ = cfg;
Verifier::new(provider.clone())?
};
let tls = TlsConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.dangerous()
.with_custom_certificate_verifier(Arc::new(verifier))
.with_no_client_auth();
Ok(Arc::new(tls))
}
pub(crate) fn platform_tls() -> Result<Arc<TlsConfig>, rustls::Error> {
let provider = crypto_provider(None)?;
let verifier = Verifier::new(provider.clone())?;
let tls = TlsConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.dangerous()
.with_custom_certificate_verifier(Arc::new(verifier))
.with_no_client_auth();
Ok(Arc::new(tls))
}
impl ClientConfig {
pub fn tls(&self) -> Result<Arc<TlsConfig>, rustls::Error> {
tls_config(self)
}
}
pub(crate) async fn resolve(
cfg: &ClientConfig,
host: &str,
port: u16,
) -> std::io::Result<std::net::SocketAddr> {
let host = host.trim_start_matches('[').trim_end_matches(']');
if let Ok(ip) = host.parse::<IpAddr>() {
return Ok(std::net::SocketAddr::new(ip, port));
}
#[cfg(feature = "testing")]
if let Some((_, ip)) = cfg.testing.resolve.iter().find(|(n, _)| n == host) {
return Ok(std::net::SocketAddr::new(*ip, port));
}
#[cfg(not(feature = "testing"))]
let _ = cfg;
tokio::net::lookup_host((host, port))
.await?
.next()
.ok_or_else(|| std::io::Error::other(format!("{host} does not resolve")))
}
pub(crate) fn is_loopback_host(host: &str) -> bool {
let h = host.trim_start_matches('[').trim_end_matches(']');
h.eq_ignore_ascii_case("localhost") || h.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[cfg(feature = "builtin-ring-provider")]
#[test]
fn the_platform_verifier_builds() {
let cfg = ClientConfig::new("test.app", std::env::temp_dir());
assert!(tls_config(&cfg).is_ok());
}
#[cfg(feature = "builtin-ring-provider")]
fn suites(p: &CryptoProvider) -> Vec<rustls::CipherSuite> {
p.cipher_suites.iter().map(|s| s.suite()).collect()
}
#[cfg(feature = "builtin-ring-provider")]
fn groups(p: &CryptoProvider) -> Vec<rustls::NamedGroup> {
p.kx_groups.iter().map(|g| g.name()).collect()
}
fn narrow() -> Arc<CryptoProvider> {
let ring = rustls::crypto::ring::default_provider();
Arc::new(CryptoProvider {
cipher_suites: vec![rustls::crypto::ring::cipher_suite::TLS13_AES_128_GCM_SHA256],
kx_groups: vec![rustls::crypto::ring::kx_group::X25519],
..ring
})
}
#[test]
fn the_explicit_provider_wins_then_the_default() {
let explicit = narrow();
let default = narrow();
let (p, src) = choose_provider(Some(&explicit), Some(&default)).unwrap();
assert!(Arc::ptr_eq(&p, &explicit), "the explicit provider is used");
assert_eq!(src, ProviderSource::Caller);
let (p, src) = choose_provider(None, Some(&default)).unwrap();
assert!(Arc::ptr_eq(&p, &default), "the process default is used");
assert_eq!(src, ProviderSource::ProcessDefault);
}
#[test]
fn provider_names() {
assert_eq!(
provider_name(&rustls::crypto::ring::default_provider()),
"Ring"
);
}
#[cfg(feature = "builtin-ring-provider")]
#[test]
fn without_a_default_the_configs_are_on_the_builtin_ring() {
assert!(CryptoProvider::get_default().is_none());
let ring = rustls::crypto::ring::default_provider();
let (p, src) = choose_provider(None, None).unwrap();
assert_eq!(src, ProviderSource::BuiltIn);
assert_eq!(suites(&p), suites(&ring), "ring's suites");
assert_eq!(groups(&p), groups(&ring), "ring's groups");
let cfg = ClientConfig::new("test.app", std::env::temp_dir());
for tls in [tls_config(&cfg).unwrap(), platform_tls().unwrap()] {
assert_eq!(suites(tls.crypto_provider()), suites(&ring));
assert_eq!(groups(tls.crypto_provider()), groups(&ring));
}
let explicit = narrow();
let tls = tls_config(&cfg.with_crypto_provider(explicit.clone())).unwrap();
assert!(Arc::ptr_eq(tls.crypto_provider(), &explicit));
}
#[cfg(not(feature = "builtin-ring-provider"))]
#[test]
fn without_the_builtin_nothing_is_guessed() {
assert!(CryptoProvider::get_default().is_none());
let e = choose_provider(None, None).unwrap_err();
assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
let cfg = ClientConfig::new("test.app", std::env::temp_dir());
let e = tls_config(&cfg).unwrap_err();
assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
let e = platform_tls().unwrap_err();
assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
let explicit = narrow();
let tls = tls_config(&cfg.with_crypto_provider(explicit.clone())).unwrap();
assert!(Arc::ptr_eq(tls.crypto_provider(), &explicit));
}
#[test]
fn loopback_hosts() {
assert!(is_loopback_host("127.0.0.1"));
assert!(is_loopback_host("[::1]"));
assert!(is_loopback_host("localhost"));
assert!(!is_loopback_host("voice.example"));
assert!(!is_loopback_host("10.0.0.1"));
}
}