Cotton code
42 lines · 1.8 KB · RustRaw
//! Non-Apple client TLS. The Apple connector stays in `wire.rs`.use super::{Origin, Timed, Wire};use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};use std::sync::Arc;pub(super) fn roots() -> RootCertStore {    RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned())}pub(super) fn config(roots: RootCertStore) -> Result<ClientConfig, String> {    // Select the provider explicitly: another linked crate must not change    // which implementation this client uses via process-global initialization.    ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))        .with_safe_default_protocol_versions()        .map(|builder| builder.with_root_certificates(roots).with_no_client_auth())        .map_err(|error| format!("this device's TLS could not start ({error})"))}pub(super) fn connect(    origin: &Origin,    mut socket: Timed,    config: ClientConfig,) -> Result<Wire, String> {    let name = rustls::pki_types::ServerName::try_from(origin.host.clone())        .map_err(|error| format!("{} has an invalid TLS host ({error})", origin.text))?;    let mut connection = ClientConnection::new(Arc::new(config), name)        .map_err(|error| format!("this device's TLS could not start ({error})"))?;    // Finish verification here, before a caller can write its signed request.    // Every read and write of it waits only for what is left of the dial's    // deadline — `Timed` sets that per syscall, the same as Apple's path.    while connection.is_handshaking() {        connection            .complete_io(&mut socket)            .map_err(|error| format!("{} could not be trusted ({error})", origin.text))?;    }    Ok(Wire::Tls(Box::new(StreamOwned::new(connection, socket))))}#[cfg(test)]#[path = "wire_tls_tests.rs"]mod tests;