1use std::net::IpAddr;
14use std::path::PathBuf;
15use std::sync::Arc;
16use std::time::Duration;
17
18use rustls::ClientConfig as TlsConfig;
19use rustls::crypto::CryptoProvider;
20use rustls_platform_verifier::Verifier;
21
22use crate::device::{DeviceKeyStore, DevicePlatform, HardwareDeviceKey, StoreChoice};
23
24#[derive(Clone, Debug)]
26#[non_exhaustive]
27pub struct ClientConfig {
28 pub app_id: String,
31 pub data_dir: PathBuf,
33 pub device_store: StoreChoice,
38 pub device_platform: DevicePlatform,
41 pub reconnect_window: Duration,
44 pub connect_timeout: Duration,
46 pub crypto_provider: Option<Arc<CryptoProvider>>,
53 pub video_h264: bool,
65 #[cfg(feature = "testing")]
67 pub testing: TestingOverrides,
68}
69
70impl ClientConfig {
71 pub fn new(app_id: &str, data_dir: PathBuf) -> ClientConfig {
73 ClientConfig {
74 app_id: app_id.to_owned(),
75 data_dir,
76 device_store: StoreChoice::Auto,
77 device_platform: crate::device::default_platform(),
78 reconnect_window: Duration::from_secs(20),
79 connect_timeout: Duration::from_secs(20),
80 crypto_provider: None,
81 video_h264: default_video_h264(),
82 #[cfg(feature = "testing")]
83 testing: TestingOverrides::default(),
84 }
85 }
86
87 pub fn with_video_h264(mut self, on: bool) -> ClientConfig {
90 self.video_h264 = on;
91 self
92 }
93
94 pub fn with_device_key_store(mut self, store: Arc<dyn DeviceKeyStore>) -> ClientConfig {
97 self.device_store = StoreChoice::Host(store);
98 self
99 }
100
101 pub fn with_hardware_device_key(mut self, key: Arc<dyn HardwareDeviceKey>) -> ClientConfig {
106 self.device_store = StoreChoice::Hardware(key);
107 self
108 }
109
110 pub fn with_device_platform(mut self, platform: DevicePlatform) -> ClientConfig {
112 self.device_platform = platform;
113 self
114 }
115
116 pub fn with_crypto_provider(mut self, provider: Arc<CryptoProvider>) -> ClientConfig {
119 self.crypto_provider = Some(provider);
120 self
121 }
122}
123
124pub const fn default_video_h264() -> bool {
127 !cfg!(target_os = "linux")
128}
129
130#[cfg(feature = "testing")]
132#[derive(Clone, Debug, Default)]
133pub struct TestingOverrides {
134 pub extra_roots: Vec<Vec<u8>>,
136 pub resolve: Vec<(String, IpAddr)>,
139 pub source_ip: Arc<std::sync::RwLock<Option<IpAddr>>>,
143 pub first_seq: Option<u16>,
147 pub drop_video_packets: Arc<std::sync::atomic::AtomicU32>,
151}
152
153#[cfg(feature = "testing")]
155pub(crate) fn drop_video_packet(cfg: &ClientConfig) -> bool {
156 use std::sync::atomic::Ordering;
157 cfg.testing
158 .drop_video_packets
159 .try_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1))
160 .is_ok()
161}
162
163#[cfg(not(feature = "testing"))]
165pub(crate) fn drop_video_packet(_cfg: &ClientConfig) -> bool {
166 false
167}
168
169#[cfg(feature = "testing")]
171pub(crate) fn source_ip(cfg: &ClientConfig) -> Option<IpAddr> {
172 cfg.testing.source_ip.read().ok().and_then(|g| *g)
173}
174
175#[cfg(not(feature = "testing"))]
177pub(crate) fn source_ip(_cfg: &ClientConfig) -> Option<IpAddr> {
178 None
179}
180
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub(crate) enum ProviderSource {
184 Caller,
186 ProcessDefault,
188 #[cfg_attr(not(feature = "builtin-ring-provider"), allow(dead_code))]
190 BuiltIn,
191}
192
193impl ProviderSource {
194 fn as_str(self) -> &'static str {
195 match self {
196 ProviderSource::Caller => "caller",
197 ProviderSource::ProcessDefault => "process default",
198 ProviderSource::BuiltIn => "built-in",
199 }
200 }
201}
202
203#[cfg(not(feature = "builtin-ring-provider"))]
205pub(crate) const NO_CRYPTO_PROVIDER: &str = "no_crypto_provider";
206
207pub(crate) fn crypto_provider(
211 explicit: Option<&Arc<CryptoProvider>>,
212) -> Result<Arc<CryptoProvider>, rustls::Error> {
213 let (provider, source) = choose_provider(explicit, CryptoProvider::get_default())?;
214 log_choice(&provider, source);
215 Ok(provider)
216}
217
218fn choose_provider(
219 explicit: Option<&Arc<CryptoProvider>>,
220 default: Option<&Arc<CryptoProvider>>,
221) -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
222 if let Some(p) = explicit {
223 return Ok((p.clone(), ProviderSource::Caller));
224 }
225 if let Some(p) = default {
226 return Ok((p.clone(), ProviderSource::ProcessDefault));
227 }
228 builtin_provider()
229}
230
231#[cfg(feature = "builtin-ring-provider")]
232fn builtin_provider() -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
233 Ok((
234 Arc::new(rustls::crypto::ring::default_provider()),
235 ProviderSource::BuiltIn,
236 ))
237}
238
239#[cfg(not(feature = "builtin-ring-provider"))]
240fn builtin_provider() -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
241 Err(rustls::Error::General(format!(
242 "{NO_CRYPTO_PROVIDER}: no rustls crypto provider was passed \
243 (ClientConfig::with_crypto_provider) or installed as the process default, and the \
244 built-in one is off (feature `builtin-ring-provider`)"
245 )))
246}
247
248pub(crate) fn provider_name(p: &CryptoProvider) -> String {
251 format!("{:?}", p.secure_random)
252}
253
254fn log_choice(provider: &CryptoProvider, source: ProviderSource) {
255 static LAST: std::sync::Mutex<Option<(String, ProviderSource)>> = std::sync::Mutex::new(None);
256 let choice = (provider_name(provider), source);
257 let mut last = LAST
258 .lock()
259 .unwrap_or_else(std::sync::PoisonError::into_inner);
260 if last.as_ref() != Some(&choice) {
261 tracing::info!("tls provider: {} ({})", choice.0, source.as_str());
262 *last = Some(choice);
263 }
264}
265
266pub(crate) fn tls_config(cfg: &ClientConfig) -> Result<Arc<TlsConfig>, rustls::Error> {
268 let provider = crypto_provider(cfg.crypto_provider.as_ref())?;
269 #[cfg(feature = "testing")]
270 let verifier = if cfg.testing.extra_roots.is_empty() {
271 Verifier::new(provider.clone())?
272 } else {
273 let extra = cfg
274 .testing
275 .extra_roots
276 .iter()
277 .map(|d| rustls::pki_types::CertificateDer::from(d.clone()));
278 Verifier::new_with_extra_roots(extra, provider.clone())?
279 };
280 #[cfg(not(feature = "testing"))]
281 let verifier = {
282 let _ = cfg;
283 Verifier::new(provider.clone())?
284 };
285 let tls = TlsConfig::builder_with_provider(provider)
286 .with_safe_default_protocol_versions()?
287 .dangerous()
288 .with_custom_certificate_verifier(Arc::new(verifier))
289 .with_no_client_auth();
290 Ok(Arc::new(tls))
291}
292
293pub(crate) fn platform_tls() -> Result<Arc<TlsConfig>, rustls::Error> {
296 let provider = crypto_provider(None)?;
297 let verifier = Verifier::new(provider.clone())?;
298 let tls = TlsConfig::builder_with_provider(provider)
299 .with_safe_default_protocol_versions()?
300 .dangerous()
301 .with_custom_certificate_verifier(Arc::new(verifier))
302 .with_no_client_auth();
303 Ok(Arc::new(tls))
304}
305
306impl ClientConfig {
307 pub fn tls(&self) -> Result<Arc<TlsConfig>, rustls::Error> {
312 tls_config(self)
313 }
314}
315
316pub(crate) async fn resolve(
318 cfg: &ClientConfig,
319 host: &str,
320 port: u16,
321) -> std::io::Result<std::net::SocketAddr> {
322 let host = host.trim_start_matches('[').trim_end_matches(']');
323 if let Ok(ip) = host.parse::<IpAddr>() {
324 return Ok(std::net::SocketAddr::new(ip, port));
325 }
326 #[cfg(feature = "testing")]
327 if let Some((_, ip)) = cfg.testing.resolve.iter().find(|(n, _)| n == host) {
328 return Ok(std::net::SocketAddr::new(*ip, port));
329 }
330 #[cfg(not(feature = "testing"))]
331 let _ = cfg;
332 tokio::net::lookup_host((host, port))
333 .await?
334 .next()
335 .ok_or_else(|| std::io::Error::other(format!("{host} does not resolve")))
336}
337
338pub(crate) fn is_loopback_host(host: &str) -> bool {
340 let h = host.trim_start_matches('[').trim_end_matches(']');
341 h.eq_ignore_ascii_case("localhost") || h.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
342}
343
344#[cfg(test)]
345mod tests {
346 #![allow(clippy::unwrap_used)]
347 use super::*;
348
349 #[cfg(feature = "builtin-ring-provider")]
350 #[test]
351 fn the_platform_verifier_builds() {
352 let cfg = ClientConfig::new("test.app", std::env::temp_dir());
353 assert!(tls_config(&cfg).is_ok());
354 }
355
356 #[cfg(feature = "builtin-ring-provider")]
357 fn suites(p: &CryptoProvider) -> Vec<rustls::CipherSuite> {
358 p.cipher_suites.iter().map(|s| s.suite()).collect()
359 }
360
361 #[cfg(feature = "builtin-ring-provider")]
362 fn groups(p: &CryptoProvider) -> Vec<rustls::NamedGroup> {
363 p.kx_groups.iter().map(|g| g.name()).collect()
364 }
365
366 fn narrow() -> Arc<CryptoProvider> {
368 let ring = rustls::crypto::ring::default_provider();
369 Arc::new(CryptoProvider {
370 cipher_suites: vec![rustls::crypto::ring::cipher_suite::TLS13_AES_128_GCM_SHA256],
371 kx_groups: vec![rustls::crypto::ring::kx_group::X25519],
372 ..ring
373 })
374 }
375
376 #[test]
377 fn the_explicit_provider_wins_then_the_default() {
378 let explicit = narrow();
379 let default = narrow();
380 let (p, src) = choose_provider(Some(&explicit), Some(&default)).unwrap();
381 assert!(Arc::ptr_eq(&p, &explicit), "the explicit provider is used");
382 assert_eq!(src, ProviderSource::Caller);
383 let (p, src) = choose_provider(None, Some(&default)).unwrap();
384 assert!(Arc::ptr_eq(&p, &default), "the process default is used");
385 assert_eq!(src, ProviderSource::ProcessDefault);
386 }
387
388 #[test]
389 fn provider_names() {
390 assert_eq!(
391 provider_name(&rustls::crypto::ring::default_provider()),
392 "Ring"
393 );
394 }
395
396 #[cfg(feature = "builtin-ring-provider")]
400 #[test]
401 fn without_a_default_the_configs_are_on_the_builtin_ring() {
402 assert!(CryptoProvider::get_default().is_none());
403 let ring = rustls::crypto::ring::default_provider();
404 let (p, src) = choose_provider(None, None).unwrap();
405 assert_eq!(src, ProviderSource::BuiltIn);
406 assert_eq!(suites(&p), suites(&ring), "ring's suites");
407 assert_eq!(groups(&p), groups(&ring), "ring's groups");
408 let cfg = ClientConfig::new("test.app", std::env::temp_dir());
409 for tls in [tls_config(&cfg).unwrap(), platform_tls().unwrap()] {
410 assert_eq!(suites(tls.crypto_provider()), suites(&ring));
411 assert_eq!(groups(tls.crypto_provider()), groups(&ring));
412 }
413 let explicit = narrow();
414 let tls = tls_config(&cfg.with_crypto_provider(explicit.clone())).unwrap();
415 assert!(Arc::ptr_eq(tls.crypto_provider(), &explicit));
416 }
417
418 #[cfg(not(feature = "builtin-ring-provider"))]
421 #[test]
422 fn without_the_builtin_nothing_is_guessed() {
423 assert!(CryptoProvider::get_default().is_none());
424 let e = choose_provider(None, None).unwrap_err();
425 assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
426 let cfg = ClientConfig::new("test.app", std::env::temp_dir());
427 let e = tls_config(&cfg).unwrap_err();
428 assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
429 let e = platform_tls().unwrap_err();
430 assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
431 let explicit = narrow();
432 let tls = tls_config(&cfg.with_crypto_provider(explicit.clone())).unwrap();
433 assert!(Arc::ptr_eq(tls.crypto_provider(), &explicit));
434 }
435
436 #[test]
437 fn loopback_hosts() {
438 assert!(is_loopback_host("127.0.0.1"));
439 assert!(is_loopback_host("[::1]"));
440 assert!(is_loopback_host("localhost"));
441 assert!(!is_loopback_host("voice.example"));
442 assert!(!is_loopback_host("10.0.0.1"));
443 }
444}