http-request 23.3.0

http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.
Documentation
use super::*;

/// Constructs a rustls [`ClientConfig`] with session resumption and protocol ALPN.
///
/// # Arguments
///
/// - `RootCertStore` - Trust anchor root certificate store.
/// - `bool` - Whether to advertise `h2` ALPN ahead of `http/1.1`.
///
/// # Returns
///
/// - `Arc<ClientConfig>` - Ready shared client TLS configuration.
fn build_client_config(roots: RootCertStore, enable_h2: bool) -> Arc<ClientConfig> {
    let mut cfg: ClientConfig = ClientConfig::builder()
        .with_root_certificates(roots)
        .with_no_client_auth();
    cfg.resumption = Resumption::in_memory_sessions(TLS_CLIENT_SESSION_CACHE_CAP);
    cfg.alpn_protocols = if enable_h2 {
        vec![ALPN_H2.to_vec(), ALPN_HTTP1_1.to_vec()]
    } else {
        vec![ALPN_HTTP1_1.to_vec()]
    };
    Arc::new(cfg)
}

/// Computes a deterministic 64-bit fingerprint for TLS trust stores (`0` for default WebPKI roots).
///
/// # Arguments
///
/// - `Option<&RootCertStore>` - Optional custom TLS trust anchor store (`None` means bundled Mozilla roots).
///
/// # Returns
///
/// - `u64` - `0` for bundled default roots, or a non-zero FNV-1a digest over all custom trust anchors.
#[inline(always)]
pub(crate) fn root_cert_fingerprint(roots: Option<&RootCertStore>) -> u64 {
    let Some(store) = roots else {
        return 0;
    };
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for anchor in &store.roots {
        for &byte in anchor.subject.as_ref() {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
        for &byte in anchor.subject_public_key_info.as_ref() {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
    }
    (hash ^ (store.roots.len() as u64)) | 1
}

/// Returns a cached default TLS config or caches/constructs one for a custom root certificate store.
///
/// # Arguments
///
/// - `Option<&RootCertStore>` - Optional custom root certificate store (`None` uses bundled Mozilla roots).
/// - `bool` - Whether HTTP/2 ALPN should be advertised.
///
/// # Returns
///
/// - `Arc<ClientConfig>` - Shared rustls client configuration.
pub(crate) fn resolve_tls_client_config(
    roots: Option<&RootCertStore>,
    enable_h2: bool,
) -> Arc<ClientConfig> {
    let Some(custom) = roots else {
        let cache: &OnceLock<Arc<ClientConfig>> = if enable_h2 {
            &DEFAULT_H2_TLS_CONFIG
        } else {
            &DEFAULT_H1_TLS_CONFIG
        };
        return Arc::clone(cache.get_or_init(|| {
            let default_roots: RootCertStore = RootCertStore {
                roots: TLS_SERVER_ROOTS.to_vec(),
            };
            build_client_config(default_roots, enable_h2)
        }));
    };
    let key: (u64, bool) = (root_cert_fingerprint(Some(custom)), enable_h2);
    let cache_lock: &Mutex<CustomTlsConfigMap> =
        CUSTOM_TLS_CONFIG_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    if let Ok(cache) = cache_lock.lock()
        && let Some(existing) = cache.get(&key)
    {
        return Arc::clone(existing);
    }
    let built: Arc<ClientConfig> = build_client_config(custom.clone(), enable_h2);
    if let Ok(mut cache) = cache_lock.lock() {
        if cache.len() >= CUSTOM_TLS_CONFIG_CACHE_CAP {
            cache.clear();
        }
        cache.insert(key, Arc::clone(&built));
    }
    built
}

/// Parses one or more PEM-encoded X.509 certificates and inserts them into `roots`.
///
/// # Arguments
///
/// - `&mut RootCertStore` - Target root certificate store.
/// - `&[u8]` - Raw PEM-encoded certificate bytes.
///
/// # Returns
///
/// - `Result<usize, RequestError>` - Number of certificates added, or an error when none are valid.
pub(crate) fn add_pem_certs_to_store(
    roots: &mut RootCertStore,
    pem_bytes: &[u8],
) -> Result<usize, RequestError> {
    let mut added: usize = 0;
    for parsed in CertificateDer::pem_slice_iter(pem_bytes) {
        let cert: CertificateDer<'static> =
            parsed.map_err(|_| RequestError::Request(INVALID_PEM_CERT_ERROR.to_owned()))?;
        roots
            .add(cert)
            .map_err(|_| RequestError::Request(INVALID_PEM_CERT_ERROR.to_owned()))?;
        added += 1;
    }
    if added == 0 {
        return Err(RequestError::Request(INVALID_PEM_CERT_ERROR.to_owned()));
    }
    Ok(added)
}