Skip to main content

giong_tls/
lib.rs

1//! # giong-tls
2//!
3//! TLS for the [giong] thread-per-core runtime, built on [rustls] (TLS 1.2
4//! and 1.3, `ring` for cryptography, no OpenSSL): [`TlsAcceptor`] for
5//! servers, [`TlsConnector`] for clients. Both produce a [`TlsStream`].
6//!
7//! A server:
8//!
9//! ```no_run
10//! use giong::net::TcpListener;
11//! use giong_tls::TlsAcceptor;
12//!
13//! # fn main() -> std::io::Result<()> {
14//! let cert = std::fs::read("cert.pem")?;
15//! let key = std::fs::read("key.pem")?;
16//! let acceptor = TlsAcceptor::from_pem(&cert, &key)?;
17//!
18//! giong::block_on(async move {
19//!     let listener = TcpListener::bind("0.0.0.0:8443")?;
20//!     loop {
21//!         let tcp = listener.accept().await?;
22//!         let acceptor = acceptor.clone();
23//!         giong::spawn(async move {
24//!             let Ok(tls) = acceptor.accept(tcp).await else { return };
25//!             while let Ok(data) = tls.recv().await {
26//!                 if data.is_empty() {
27//!                     break; // closed by the peer
28//!                 }
29//!                 if tls.write_all(data).await.0.is_err() {
30//!                     break;
31//!                 }
32//!             }
33//!             let _ = tls.shutdown().await;
34//!         });
35//!     }
36//! })
37//! # }
38//! ```
39//!
40//! A client, trusting the certificate authorities installed on the machine:
41//!
42//! ```no_run
43//! use giong::net::TcpStream;
44//! use giong_tls::TlsConnector;
45//!
46//! # fn main() -> std::io::Result<()> {
47//! let connector = TlsConnector::with_system_roots()?;
48//!
49//! giong::block_on(async move {
50//!     let tcp = TcpStream::connect("example.com:443").await?;
51//!     let tls = connector.connect("example.com", tcp).await?;
52//!     let request = b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n";
53//!     tls.write_all(request.to_vec()).await.0?;
54//!     loop {
55//!         let data = tls.recv().await?;
56//!         if data.is_empty() {
57//!             break;
58//!         }
59//!         print!("{}", String::from_utf8_lossy(&data));
60//!     }
61//!     Ok(())
62//! })
63//! # }
64//! ```
65//!
66//! The API mirrors [`giong::net::TcpStream`]: [`TlsStream::recv`] returns the
67//! next piece of decrypted data and [`TlsStream::write_all`] takes a buffer by
68//! value and hands it back.
69//!
70//! # Kernel TLS
71//!
72//! With [`TlsAcceptor::ktls`] or [`TlsConnector::ktls`], rustls does the
73//! handshake and then hands the connection's keys to the kernel (kTLS), which
74//! encrypts and decrypts from then on. The API stays the same;
75//! [`TlsStream::is_ktls`] says which way a connection went, [`ktls_support`]
76//! what the running kernel can do, and [`ktls_stats`] how many connections
77//! went to the kernel.
78
79#![warn(missing_docs)]
80
81mod ktls;
82
83pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
84
85use std::cell::{Cell, RefCell, RefMut};
86use std::collections::HashSet;
87use std::ffi::OsStr;
88use std::future::poll_fn;
89use std::io::{self, Read, Write};
90use std::mem;
91use std::net::Shutdown;
92use std::path::{Path, PathBuf};
93use std::sync::Arc;
94use std::task::{Poll, Waker};
95use std::time::Duration;
96
97use giong::error::Code;
98use giong::net::TcpStream;
99use giong::time::timeout;
100use rustls::client::ResolvesClientCert;
101use rustls::pki_types::pem::PemObject;
102use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
103use rustls::sign::CertifiedKey;
104use rustls::{
105    ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
106    SignatureScheme,
107};
108
109pub use rustls;
110
111fn coded(
112    code: Code,
113    message: impl Into<std::borrow::Cow<'static, str>>,
114    fix: &'static str,
115) -> io::Error {
116    giong::error::Error::new(code, message, fix).into()
117}
118
119/// `send_file` was asked for bytes past the end of the file; it stopped at
120/// `at`.
121fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
122    let end = offset.saturating_add(len);
123    coded(
124        Code::FileTooShort,
125        format!(
126            "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
127            end - at
128        ),
129        "take the length from the open file (File::len), and replace a file that is being \
130         served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
131         than announced, so close the connection.",
132    )
133}
134
135/// PEM data or a certificate file that cannot be used.
136fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
137    coded(
138        Code::BadCertificateData,
139        e.to_string(),
140        "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
141         at least one certificate.",
142    )
143}
144
145/// A private key that cannot be read.
146fn bad_key(e: impl std::fmt::Display) -> io::Error {
147    coded(
148        Code::BadCertificateData,
149        format!("cannot read the private key: {e}"),
150        "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
151         EC forms).",
152    )
153}
154
155/// A certificate and a key that cannot be used together.
156fn mismatched_key(e: rustls::Error) -> io::Error {
157    coded(
158        Code::BadCertificateData,
159        format!("the certificate and the private key cannot be used together: {e}"),
160        "check that the key belongs to the first certificate of the chain, and that its type \
161         (RSA, ECDSA, Ed25519) is supported.",
162    )
163}
164
165/// What rustls reported, with the code that says what to do about it.
166fn tls_error(e: rustls::Error) -> io::Error {
167    match e {
168        rustls::Error::InvalidCertificate(_) => coded(
169            Code::TlsCertificate,
170            format!("the peer's certificate was rejected: {e}"),
171            "check the name you connect to, the certificate's expiry and its chain; a \
172             private authority has to be trusted with TlsConnector::with_roots.",
173        ),
174        e => coded(
175            Code::TlsProtocol,
176            format!("TLS error: {e}"),
177            "check that the other side speaks TLS on this port, and that both sides share a \
178             protocol version and cipher suite.",
179        ),
180    }
181}
182
183/// How long a handshake may take unless configured otherwise.
184const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
185
186fn handshake_timed_out(limit: Duration) -> io::Error {
187    coded(
188        Code::TlsHandshakeTimeout,
189        format!("the TLS handshake did not finish within {limit:?}"),
190        "check that the other side speaks TLS on this port and is not overloaded, or raise \
191         handshake_timeout.",
192    )
193}
194
195fn handshake_eof() -> io::Error {
196    coded(
197        Code::TlsHandshakeEof,
198        "the peer closed the connection during the TLS handshake",
199        "check that the other side speaks TLS on this port, and whether it wants a client \
200         certificate or another server name.",
201    )
202}
203
204fn broken() -> io::Error {
205    coded(
206        Code::TlsBroken,
207        "a TLS write failed or was cancelled; nothing more can be sent",
208        "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
209         leaves a partial record or message behind, so the stream cannot go on.",
210    )
211}
212
213/// Every certificate in `pem`, or an error if there is none.
214fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
215    let certs = CertificateDer::pem_slice_iter(pem)
216        .collect::<Result<Vec<_>, _>>()
217        .map_err(bad_certificate_data)?;
218    if certs.is_empty() {
219        return Err(bad_certificate_data("no certificate found in the PEM data"));
220    }
221    Ok(certs)
222}
223
224fn ring() -> Arc<rustls::crypto::CryptoProvider> {
225    Arc::new(rustls::crypto::ring::default_provider())
226}
227
228/// Turns accepted TCP connections into TLS connections.
229///
230/// Cheap to clone; share one between all workers.
231#[derive(Clone)]
232pub struct TlsAcceptor {
233    config: Arc<ServerConfig>,
234    handshake_timeout: Duration,
235    ktls: ktls::Plan,
236}
237
238impl TlsAcceptor {
239    /// An acceptor using an existing rustls configuration.
240    pub fn new(config: Arc<ServerConfig>) -> Self {
241        Self {
242            config,
243            handshake_timeout: HANDSHAKE_TIMEOUT,
244            ktls: ktls::Plan::Off,
245        }
246    }
247
248    /// An acceptor for one certificate chain and its private key, both in PEM
249    /// format. TLS 1.2 and 1.3 with rustls' default cipher suites, no client
250    /// authentication, and `http/1.1` offered through ALPN.
251    pub fn from_pem(cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
252        let certs = pem_certs(cert_chain)?;
253        let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
254        let mut config = ServerConfig::builder_with_provider(ring())
255            .with_safe_default_protocol_versions()
256            .map_err(tls_error)?
257            .with_no_client_auth()
258            .with_single_cert(certs, key)
259            .map_err(mismatched_key)?;
260        config.alpn_protocols = vec![b"http/1.1".to_vec()];
261        Ok(Self::new(Arc::new(config)))
262    }
263
264    /// The protocols to accept through ALPN, most preferred first, for
265    /// example `&[b"h2", b"http/1.1"]`. A client that offers none of them
266    /// fails the handshake; one that offers no ALPN at all is accepted.
267    /// The protocol agreed on is [`TlsStream::alpn_protocol`].
268    ///
269    /// giong-http's `Server::serve_tls` sets this itself, to the protocols
270    /// the server speaks.
271    pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
272        Arc::make_mut(&mut self.config).alpn_protocols =
273            protocols.iter().map(|p| p.to_vec()).collect();
274        self
275    }
276
277    /// How long a client may take to complete the TLS handshake (default:
278    /// 10 s).
279    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
280        self.handshake_timeout = timeout;
281        self
282    }
283
284    /// Whether connections hand their keys to the kernel after the
285    /// handshake, so that the kernel encrypts and decrypts (kernel TLS).
286    /// [`Ktls::Off`] by default. See [`Ktls`] for what each mode does, and
287    /// the crate README for when it pays off.
288    ///
289    /// Decided here, once: the running kernel is probed (see
290    /// [`ktls_support`]) and checked against every cipher suite the
291    /// configuration allows. [`Ktls::Required`] fails here with `GIONG-E2009`
292    /// if the kernel cannot take them; [`Ktls::Auto`] then leaves every
293    /// connection in the process instead. A configuration that allows 0-RTT
294    /// data (`max_early_data_size` above 0) cannot use kTLS.
295    ///
296    /// Turns on rustls' `enable_secret_extraction`, which kTLS needs, in this
297    /// acceptor's copy of the configuration.
298    ///
299    /// ```no_run
300    /// use giong_tls::{Ktls, TlsAcceptor};
301    ///
302    /// # fn main() -> std::io::Result<()> {
303    /// let acceptor = TlsAcceptor::from_pem(&std::fs::read("cert.pem")?, &std::fs::read("key.pem")?)?
304    ///     .ktls(Ktls::Auto)?;
305    /// # Ok(())
306    /// # }
307    /// ```
308    pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
309        let early_data = self.config.max_early_data_size > 0;
310        self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
311        if mode != Ktls::Off {
312            Arc::make_mut(&mut self.config).enable_secret_extraction = true;
313        }
314        Ok(self)
315    }
316
317    /// Why connections stay in the process although [`Ktls::Auto`] asked for
318    /// kernel TLS, if they all do: the kernel has no `tls` module, lacks a
319    /// cipher suite the configuration allows, or cannot change TLS 1.3 keys.
320    /// `None` otherwise. Worth a line in the log at startup.
321    pub fn ktls_unavailable(&self) -> Option<&str> {
322        self.ktls.unavailable()
323    }
324
325    /// Performs the TLS handshake on an accepted connection.
326    ///
327    /// With kernel TLS (see [`ktls`](Self::ktls)), the keys go to the kernel
328    /// once the handshake is done. Under [`Ktls::Required`], a stream that
329    /// cannot take them fails with `GIONG-E2009` before anything is sent.
330    pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
331        let tcp = match &self.ktls {
332            ktls::Plan::Off => tcp,
333            ktls::Plan::Try { required } => {
334                let start = ktls::Start::Server(self.config.clone());
335                match ktls::handshake(tcp, start, self.handshake_timeout).await? {
336                    ktls::Outcome::Kernel(tls) => return Ok(*tls),
337                    ktls::Outcome::Declined(_, e) if *required => return Err(e),
338                    ktls::Outcome::Declined(tcp, _) => {
339                        self.ktls.stayed();
340                        tcp
341                    }
342                }
343            }
344            ktls::Plan::Unavailable(_) => {
345                self.ktls.stayed();
346                tcp
347            }
348        };
349        let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
350        TlsStream::new(tcp, conn.into())
351            .handshake(self.handshake_timeout)
352            .await
353    }
354}
355
356impl std::fmt::Debug for TlsAcceptor {
357    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        f.debug_struct("TlsAcceptor")
359            .field("handshake_timeout", &self.handshake_timeout)
360            .field("ktls", &self.ktls)
361            .finish_non_exhaustive()
362    }
363}
364
365/// Opens TLS connections to servers, checking their certificates.
366///
367/// Cheap to clone; share one between all workers. Clones share the session
368/// cache, so reconnecting to a server resumes the earlier session and skips
369/// most of the handshake.
370///
371/// ```no_run
372/// use std::time::Duration;
373/// use giong_tls::TlsConnector;
374///
375/// # fn main() -> std::io::Result<()> {
376/// // A private certificate authority, a client certificate for mutual TLS,
377/// // and HTTP/1.1 through ALPN.
378/// let connector = TlsConnector::with_root_pem(&std::fs::read("ca.pem")?)?
379///     .client_auth(&std::fs::read("client.pem")?, &std::fs::read("client.key")?)?
380///     .alpn(&[b"http/1.1"])
381///     .handshake_timeout(Duration::from_secs(5));
382/// # Ok(())
383/// # }
384/// ```
385#[derive(Clone)]
386pub struct TlsConnector {
387    config: Arc<ClientConfig>,
388    handshake_timeout: Duration,
389    ktls: ktls::Plan,
390}
391
392impl TlsConnector {
393    /// A connector using an existing rustls configuration.
394    pub fn new(config: Arc<ClientConfig>) -> Self {
395        Self {
396            config,
397            handshake_timeout: HANDSHAKE_TIMEOUT,
398            ktls: ktls::Plan::Off,
399        }
400    }
401
402    /// A connector that trusts the given certificate authorities. TLS 1.2
403    /// and 1.3 with rustls' default cipher suites.
404    pub fn with_roots(roots: RootCertStore) -> io::Result<Self> {
405        if roots.is_empty() {
406            return Err(io::Error::new(
407                io::ErrorKind::InvalidData,
408                giong::error::Error::new(
409                    Code::NoTrustedRoots,
410                    "no trusted certificate authority given",
411                    "pass at least one certificate, or use TlsConnector::with_system_roots.",
412                ),
413            ));
414        }
415        let config = ClientConfig::builder_with_provider(ring())
416            .with_safe_default_protocol_versions()
417            .map_err(tls_error)?
418            .with_root_certificates(roots)
419            .with_no_client_auth();
420        Ok(Self::new(Arc::new(config)))
421    }
422
423    /// A connector that trusts the certificate authorities in `pem`: a
424    /// private CA, or a server's own self-signed certificate.
425    pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
426        let mut roots = RootCertStore::empty();
427        for cert in pem_certs(pem)? {
428            roots.add(cert).map_err(bad_certificate_data)?;
429        }
430        Self::with_roots(roots)
431    }
432
433    /// A connector that trusts the certificate authorities installed on this
434    /// machine, read once, now.
435    ///
436    /// They are read from the file named by the `SSL_CERT_FILE` environment
437    /// variable and the directories named by `SSL_CERT_DIR` (separated by
438    /// `:`) if either is set, the way OpenSSL does. Otherwise from the first
439    /// bundle found among the places Linux distributions keep it
440    /// (`/etc/ssl/certs/ca-certificates.crt` on Debian, Ubuntu, Alpine and
441    /// Arch, `/etc/pki/tls/certs/ca-bundle.crt` on Fedora and RHEL, and so
442    /// on), or else from the files in `/etc/ssl/certs`.
443    ///
444    /// Fails with [`io::ErrorKind::NotFound`] if there are none, as in a
445    /// container image built `FROM scratch` or without the `ca-certificates`
446    /// package. Install that package, or enable the `webpki-roots` feature and
447    /// use `TlsConnector::with_webpki_roots`.
448    pub fn with_system_roots() -> io::Result<Self> {
449        let file = std::env::var_os("SSL_CERT_FILE");
450        let dirs = std::env::var_os("SSL_CERT_DIR");
451        let roots = load_roots(
452            file.as_deref(),
453            dirs.as_deref(),
454            SYSTEM_CA_BUNDLES,
455            SYSTEM_CA_DIR,
456        )?;
457        Self::with_roots(roots)
458    }
459
460    /// A connector that trusts the certificate authorities in Mozilla's root
461    /// program, compiled into the program by the `webpki-roots` crate. Useful
462    /// where the machine has none installed; they change only when this
463    /// crate's dependency is updated.
464    ///
465    /// Needs the `webpki-roots` feature.
466    #[cfg(feature = "webpki-roots")]
467    pub fn with_webpki_roots() -> Self {
468        let roots = RootCertStore {
469            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
470        };
471        Self::with_roots(roots).expect("the webpki-roots crate provides roots")
472    }
473
474    /// The protocols to offer through ALPN, most preferred first, for example
475    /// `&[b"h2", b"http/1.1"]`. None by default. The one the server picked is
476    /// [`TlsStream::alpn_protocol`].
477    pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
478        Arc::make_mut(&mut self.config).alpn_protocols =
479            protocols.iter().map(|p| p.to_vec()).collect();
480        self
481    }
482
483    /// Presents a client certificate to servers that ask for one (mutual
484    /// TLS): a certificate chain and its private key, both in PEM format.
485    pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
486        let certs = pem_certs(cert_chain)?;
487        let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
488        let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
489            .map_err(mismatched_key)?;
490        Arc::make_mut(&mut self.config).client_auth_cert_resolver =
491            Arc::new(ClientCert(Arc::new(key)));
492        Ok(self)
493    }
494
495    /// How long a server may take to complete the TLS handshake (default:
496    /// 10 s).
497    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
498        self.handshake_timeout = timeout;
499        self
500    }
501
502    /// Whether connections hand their keys to the kernel after the
503    /// handshake, so that the kernel encrypts and decrypts (kernel TLS).
504    /// [`Ktls::Off`] by default; see [`TlsAcceptor::ktls`], which works the
505    /// same way. Session tickets the server sends later still reach the
506    /// session cache, so reconnecting resumes as without kTLS. A
507    /// configuration that allows 0-RTT data (`enable_early_data`) cannot use
508    /// kTLS.
509    ///
510    /// A stream on which [`TcpStream::recv`] was already used, as by a
511    /// protocol that reads a plaintext greeting before TLS starts, cannot
512    /// take kTLS: under [`Ktls::Auto`] it stays in the process, under
513    /// [`Ktls::Required`] it fails with `GIONG-E2009`. Use
514    /// [`TcpStream::read`] for such greetings.
515    pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
516        let early_data = self.config.enable_early_data;
517        self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
518        if mode != Ktls::Off {
519            Arc::make_mut(&mut self.config).enable_secret_extraction = true;
520        }
521        Ok(self)
522    }
523
524    /// Why connections stay in the process although [`Ktls::Auto`] asked for
525    /// kernel TLS, if they all do; see [`TlsAcceptor::ktls_unavailable`].
526    pub fn ktls_unavailable(&self) -> Option<&str> {
527        self.ktls.unavailable()
528    }
529
530    /// Performs the TLS handshake on a connection to `server_name`, which the
531    /// server's certificate must be valid for. `server_name` is a DNS name,
532    /// sent to the server through SNI, or an IP address (`[...]` brackets
533    /// around an IPv6 address are allowed), which is not.
534    ///
535    /// A certificate that is not valid for the name, expired, or not issued
536    /// by a trusted authority fails the handshake with
537    /// [`io::ErrorKind::InvalidData`] and a message saying which it was.
538    pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
539        let name = parse_server_name(server_name)?;
540        let tcp = match &self.ktls {
541            ktls::Plan::Off => tcp,
542            ktls::Plan::Try { required } => {
543                let start = ktls::Start::Client(self.config.clone(), name.clone());
544                match ktls::handshake(tcp, start, self.handshake_timeout).await? {
545                    ktls::Outcome::Kernel(tls) => return Ok(*tls),
546                    ktls::Outcome::Declined(_, e) if *required => return Err(e),
547                    ktls::Outcome::Declined(tcp, _) => {
548                        self.ktls.stayed();
549                        tcp
550                    }
551                }
552            }
553            ktls::Plan::Unavailable(_) => {
554                self.ktls.stayed();
555                tcp
556            }
557        };
558        let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
559        TlsStream::new(tcp, conn.into())
560            .handshake(self.handshake_timeout)
561            .await
562    }
563}
564
565impl std::fmt::Debug for TlsConnector {
566    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
567        f.debug_struct("TlsConnector")
568            .field("handshake_timeout", &self.handshake_timeout)
569            .field("ktls", &self.ktls)
570            .finish_non_exhaustive()
571    }
572}
573
574/// The name a client checks the server's certificate against.
575fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
576    let ipv6 = name
577        .strip_prefix('[')
578        .and_then(|n| n.strip_suffix(']'))
579        .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
580    if let Some(ip) = ipv6 {
581        return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
582    }
583    ServerName::try_from(name.to_owned()).map_err(|_| {
584        coded(
585            Code::InvalidServerName,
586            format!("{name:?} is neither a DNS name nor an IP address"),
587            "pass the host name the certificate is for (\"example.com\"), or an IP address, \
588             without a port or a scheme.",
589        )
590    })
591}
592
593/// Always presents the same client certificate.
594#[derive(Debug)]
595struct ClientCert(Arc<CertifiedKey>);
596
597impl ResolvesClientCert for ClientCert {
598    fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
599        Some(self.0.clone())
600    }
601
602    fn has_certs(&self) -> bool {
603        true
604    }
605}
606
607/// Where Linux distributions keep the bundle of trusted CA certificates.
608const SYSTEM_CA_BUNDLES: &[&str] = &[
609    // Debian, Ubuntu, Alpine, Arch, Gentoo
610    "/etc/ssl/certs/ca-certificates.crt",
611    // Fedora, RHEL, CentOS
612    "/etc/pki/tls/certs/ca-bundle.crt",
613    "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
614    // openSUSE, SLES
615    "/etc/ssl/ca-bundle.pem",
616    // Alpine, Void
617    "/etc/ssl/cert.pem",
618];
619
620/// Where they are kept one per file, when there is no bundle.
621const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
622
623/// Reads trusted certificates the way OpenSSL finds them: `file` and `dirs`
624/// (the `SSL_CERT_FILE` and `SSL_CERT_DIR` variables) if either is set,
625/// otherwise the first of `bundles` that exists, otherwise the files in
626/// `dir`. Certificates rustls cannot use are skipped.
627fn load_roots(
628    file: Option<&OsStr>,
629    dirs: Option<&OsStr>,
630    bundles: &[&str],
631    dir: &str,
632) -> io::Result<RootCertStore> {
633    let mut roots = Roots {
634        store: RootCertStore::empty(),
635        seen: HashSet::new(),
636    };
637    if file.is_some() || dirs.is_some() {
638        if let Some(file) = file {
639            roots.add_file(Path::new(file)).map_err(|e| {
640                io::Error::new(
641                    e.kind(),
642                    giong::error::Error::new(
643                        Code::BadCertificateData,
644                        format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
645                        "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
646                         it to use the system's.",
647                    )
648                    .with_source(e),
649                )
650            })?;
651        }
652        for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
653            roots.add_dir(&dir);
654        }
655    } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
656        roots.add_file(bundle)?;
657    } else {
658        roots.add_dir(Path::new(dir));
659    }
660    if roots.store.is_empty() {
661        return Err(coded(
662            Code::NoTrustedRoots,
663            "no trusted CA certificates found on this machine",
664            "install the ca-certificates package, set SSL_CERT_FILE, or use \
665             TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
666        ));
667    }
668    Ok(roots.store)
669}
670
671struct Roots {
672    store: RootCertStore,
673    /// Files already read. The hashed names in certificate directories are
674    /// links to other files there.
675    seen: HashSet<PathBuf>,
676}
677
678impl Roots {
679    fn add_file(&mut self, path: &Path) -> io::Result<()> {
680        let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
681        if !self.seen.insert(real) {
682            return Ok(());
683        }
684        let pem = std::fs::read(path)?;
685        let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
686        self.store.add_parsable_certificates(certs);
687        Ok(())
688    }
689
690    fn add_dir(&mut self, dir: &Path) {
691        let Ok(entries) = std::fs::read_dir(dir) else {
692            return;
693        };
694        let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
695        paths.sort();
696        for path in paths.iter().filter(|p| p.is_file()) {
697            // One unreadable file does not spoil the others.
698            let _ = self.add_file(path);
699        }
700    }
701}
702
703/// A TLS connection over a [`TcpStream`], made by [`TlsAcceptor::accept`] on
704/// the server side or [`TlsConnector::connect`] on the client side.
705pub struct TlsStream {
706    tcp: TcpStream,
707    /// Who encrypts: rustls in the process, or the kernel.
708    engine: RefCell<Engine>,
709    /// Decrypted data not handed out yet.
710    plain: RefCell<Vec<u8>>,
711    /// Scratch buffer for outgoing TLS records, reused between writes.
712    wire: RefCell<Vec<u8>>,
713    /// The peer closed the connection (with or without `close_notify`).
714    eof: Cell<bool>,
715    /// The peer ended its side with a `close_notify` alert, so nothing it
716    /// sent was cut off.
717    close_notify: Cell<bool>,
718    /// A task is writing TLS records to the socket. Records must not
719    /// interleave, so other tasks wait for it in `waiters`.
720    sending: Cell<bool>,
721    /// A write to the socket failed or was cancelled half way: the record
722    /// stream is cut in the middle and nothing more can be sent.
723    broken: Cell<bool>,
724    /// A receive error held back until the data before it has been handed out.
725    failed: Cell<Option<io::Error>>,
726    /// Tasks waiting for `sending` to clear.
727    waiters: RefCell<Vec<Waker>>,
728}
729
730/// Who encrypts and decrypts a [`TlsStream`].
731// Both variants are large and a stream holds one for its whole life; a box
732// would cost an allocation and a pointer to follow on every call.
733#[allow(clippy::large_enum_variant)]
734enum Engine {
735    /// rustls, in the process.
736    User(Connection),
737    /// The kernel; rustls keeps what it needs for key updates and session
738    /// tickets.
739    Kernel(ktls::Kernel),
740}
741
742/// Held while TLS records are being written to the socket. Dropped without
743/// [`done`](Self::done), as when the future writing is cancelled, it marks
744/// the stream broken.
745struct Sending<'a> {
746    stream: &'a TlsStream,
747    complete: bool,
748}
749
750impl Sending<'_> {
751    /// The records went out whole (or none did).
752    fn done(mut self) {
753        self.complete = true;
754    }
755}
756
757impl Drop for Sending<'_> {
758    fn drop(&mut self) {
759        if !self.complete {
760            self.stream.broken.set(true);
761        }
762        self.stream.sending.set(false);
763        let waiters = mem::take(&mut *self.stream.waiters.borrow_mut());
764        for waker in waiters {
765            waker.wake();
766        }
767    }
768}
769
770impl TlsStream {
771    fn new(tcp: TcpStream, conn: Connection) -> Self {
772        Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
773    }
774
775    /// A stream the kernel encrypts. `plain` is application data that arrived
776    /// with the end of the handshake; `peer_closed` says `close_notify` did
777    /// too.
778    fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
779        Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
780    }
781
782    fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
783        Self {
784            tcp,
785            engine: RefCell::new(engine),
786            plain: RefCell::new(plain),
787            wire: RefCell::new(Vec::new()),
788            eof: Cell::new(peer_closed),
789            close_notify: Cell::new(peer_closed),
790            sending: Cell::new(false),
791            broken: Cell::new(false),
792            failed: Cell::new(None),
793            waiters: RefCell::new(Vec::new()),
794        }
795    }
796
797    /// rustls' connection, on a stream rustls encrypts. Never held across
798    /// an `.await`.
799    fn conn(&self) -> RefMut<'_, Connection> {
800        RefMut::map(self.engine.borrow_mut(), |e| match e {
801            Engine::User(c) => c,
802            Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
803        })
804    }
805
806    /// `true` if the kernel encrypts and decrypts this connection (kernel
807    /// TLS, see [`TlsAcceptor::ktls`]); `false` if rustls does, in the
808    /// process.
809    pub fn is_ktls(&self) -> bool {
810        matches!(*self.engine.borrow(), Engine::Kernel(_))
811    }
812
813    /// Waits until no other task is writing records.
814    async fn wait_for_sender(&self) {
815        poll_fn(|cx| {
816            if !self.sending.get() {
817                return Poll::Ready(());
818            }
819            // A task polled again while it waits is listed once.
820            let mut waiters = self.waiters.borrow_mut();
821            if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
822                waiters.push(cx.waker().clone());
823            }
824            Poll::Pending
825        })
826        .await;
827    }
828
829    /// Waits for other writers, then makes this task the one writing records
830    /// until the guard is dropped.
831    async fn lock_send(&self) -> Sending<'_> {
832        while self.sending.get() {
833            self.wait_for_sender().await;
834        }
835        self.sending.set(true);
836        Sending {
837            stream: self,
838            complete: false,
839        }
840    }
841
842    /// Runs the handshake, either side, within `limit`.
843    async fn handshake(self, limit: Duration) -> io::Result<Self> {
844        let handshake = async {
845            while self.conn().is_handshaking() {
846                self.flush_tls().await?;
847                if !self.conn().is_handshaking() {
848                    break;
849                }
850                if self.eof.get() {
851                    return Err(handshake_eof());
852                }
853                self.pump().await?;
854            }
855            self.flush_tls().await
856        };
857        match timeout(limit, handshake).await {
858            Ok(Ok(())) => Ok(self),
859            Ok(Err(e)) => Err(e),
860            Err(_) => Err(handshake_timed_out(limit)),
861        }
862    }
863
864    /// Sends every TLS record rustls has queued.
865    async fn flush_tls(&self) -> io::Result<()> {
866        loop {
867            if !self.conn().wants_write() {
868                return Ok(());
869            }
870            if self.broken.get() {
871                return Err(broken());
872            }
873            if self.sending.get() {
874                // Another task is sending. Wait for it, then send what is
875                // left (it may already have sent this task's records too).
876                self.wait_for_sender().await;
877                continue;
878            }
879            let mut wire = mem::take(&mut *self.wire.borrow_mut());
880            {
881                let mut conn = self.conn();
882                while conn.wants_write() {
883                    conn.write_tls(&mut wire)?;
884                }
885            }
886            let sending = self.lock_send().await;
887            let (res, mut wire) = self.tcp.write_all(wire).await;
888            res?;
889            sending.done();
890            wire.clear();
891            *self.wire.borrow_mut() = wire;
892        }
893    }
894
895    /// Receives one chunk of TLS data, decrypts it into `plain`, and sends
896    /// whatever the protocol wants to send in response.
897    async fn pump(&self) -> io::Result<()> {
898        // Cancelling here loses nothing: `recv` is cancel safe.
899        let chunk = self.tcp.recv().await?;
900        if chunk.is_empty() {
901            self.eof.set(true);
902            return Ok(());
903        }
904        let result = {
905            let mut conn = self.conn();
906            let mut plain = self.plain.borrow_mut();
907            let mut input = &chunk[..];
908            let mut result = Ok(());
909            while !input.is_empty() {
910                // rustls buffers a bounded amount of plaintext, so it has to
911                // be drained as the records are fed in.
912                match conn.read_tls(&mut input) {
913                    Ok(0) => {
914                        result = Err(coded(
915                            Code::TlsProtocol,
916                            "rustls accepted no more TLS data",
917                            "this is a bug in giong-tls; please report it at \
918                             https://github.com/giong-run/Giong/issues.",
919                        ));
920                        break;
921                    }
922                    Ok(_) => {}
923                    Err(e) => {
924                        result = Err(e);
925                        break;
926                    }
927                }
928                match conn.process_new_packets() {
929                    Ok(state) => {
930                        let n = state.plaintext_bytes_to_read();
931                        if n > 0 {
932                            let at = plain.len();
933                            plain.resize(at + n, 0);
934                            if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
935                                plain.truncate(at);
936                                result = Err(e);
937                                break;
938                            }
939                        }
940                        if state.peer_has_closed() {
941                            self.close_notify.set(true);
942                            self.eof.set(true);
943                            break;
944                        }
945                    }
946                    Err(e) => {
947                        result = Err(tls_error(e));
948                        break;
949                    }
950                }
951            }
952            result
953        };
954        drop(chunk);
955        // Handshake messages, key updates, or the alert describing `result`.
956        // Not being able to send them is no reason to withhold what was
957        // received, if sending has failed before.
958        if self.broken.get() {
959            return result;
960        }
961        let flushed = self.flush_tls().await;
962        result.and(flushed)
963    }
964
965    /// Receives decrypted data. An empty buffer means that the peer has closed
966    /// the connection, with a `close_notify` alert or by closing the socket.
967    ///
968    /// The two are not the same when the end of the stream is what marks
969    /// the end of the data, as in an HTTP response without a length: only
970    /// `close_notify` is authenticated, while anyone on the network path can
971    /// close a TCP connection early and cut the data short (a truncation
972    /// attack). Check [`received_close_notify`](Self::received_close_notify)
973    /// before trusting such data to be complete.
974    ///
975    /// Cancel safe: dropping the future loses no data. (If it is dropped at
976    /// the rare moment a TLS protocol message is being sent, sending fails
977    /// from then on instead of continuing on a broken stream.)
978    ///
979    /// One task may receive while another one sends.
980    pub async fn recv(&self) -> io::Result<Vec<u8>> {
981        if self.is_ktls() {
982            return self.kernel_recv().await;
983        }
984        loop {
985            {
986                let mut plain = self.plain.borrow_mut();
987                if !plain.is_empty() {
988                    return Ok(mem::take(&mut *plain));
989                }
990            }
991            if let Some(e) = self.failed.take() {
992                return Err(e);
993            }
994            if self.eof.get() {
995                return Ok(Vec::new());
996            }
997            if let Err(e) = self.pump().await {
998                // Data that arrived intact before the failure comes first.
999                if self.plain.borrow().is_empty() {
1000                    return Err(e);
1001                }
1002                self.failed.set(Some(e));
1003            }
1004        }
1005    }
1006
1007    /// Encrypts and sends all of `buf`, then hands the buffer back.
1008    ///
1009    /// Not cancel safe: if the future is dropped, part of `buf` may have been
1010    /// sent, and if that happened in the middle of a TLS record the
1011    /// connection cannot send any more: later writes return an error, while
1012    /// data the peer already sent can still be received.
1013    pub async fn write_all(&self, buf: Vec<u8>) -> (io::Result<()>, Vec<u8>) {
1014        if self.is_ktls() {
1015            return self.kernel_write_all(buf).await;
1016        }
1017        let mut sent = 0;
1018        while sent < buf.len() {
1019            // rustls accepts a bounded amount per call; send as it fills up.
1020            let accepted = self.conn().writer().write(&buf[sent..]);
1021            match accepted {
1022                Ok(n) => sent += n,
1023                Err(e) => return (Err(e), buf),
1024            }
1025            if let Err(e) = self.flush_tls().await {
1026                return (Err(e), buf);
1027            }
1028        }
1029        (Ok(()), buf)
1030    }
1031
1032    /// Encrypts and sends all of `bufs`, one after the other, without
1033    /// copying them into one buffer first, then hands them back.
1034    ///
1035    /// Use it to send a header and a large body that live in different
1036    /// buffers. In the process, rustls takes the pieces one by one, so a
1037    /// small header goes out in the same write as the start of the body;
1038    /// with kernel TLS they go to the kernel in vectored writes, as with
1039    /// [`TcpStream::write_all_vectored`].
1040    ///
1041    /// Not cancel safe, as [`write_all`](Self::write_all).
1042    pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1043    where
1044        B: giong::IoBuf + AsRef<[u8]>,
1045    {
1046        if self.is_ktls() {
1047            return self.kernel_write_all_vectored(bufs).await;
1048        }
1049        for buf in &bufs {
1050            let buf = buf.as_ref();
1051            let mut sent = 0;
1052            while sent < buf.len() {
1053                let accepted = self.conn().writer().write(&buf[sent..]);
1054                match accepted {
1055                    Ok(n) => sent += n,
1056                    Err(e) => return (Err(e), bufs),
1057                }
1058                // rustls takes a bounded amount: send what it holds once it
1059                // is full, and the rest at the end.
1060                if sent < buf.len() {
1061                    if let Err(e) = self.flush_tls().await {
1062                        return (Err(e), bufs);
1063                    }
1064                }
1065            }
1066        }
1067        match self.flush_tls().await {
1068            Ok(()) => (Ok(()), bufs),
1069            Err(e) => (Err(e), bufs),
1070        }
1071    }
1072
1073    /// Encrypts and sends `len` bytes of `file`, starting at `offset`.
1074    ///
1075    /// With kernel TLS (see [`is_ktls`](Self::is_ktls)) this is
1076    /// [`TcpStream::send_file`]: the kernel encrypts the file straight from
1077    /// its page cache, and the bytes never pass through the program. This is
1078    /// where kernel TLS is faster than encrypting in the process. Without
1079    /// it, the file is read in pieces of up to 256 KiB and encrypted by
1080    /// rustls. Either way, the file's own position is neither used nor
1081    /// moved.
1082    ///
1083    /// Fails with `FileTooShort` (`GIONG-E0201`) if the file ends before
1084    /// `offset + len`, after sending what it had; the stream can still send.
1085    /// The notes of [`TcpStream::send_file`] on cold files apply to kernel
1086    /// TLS.
1087    ///
1088    /// Not cancel safe, as [`write_all`](Self::write_all).
1089    pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1090        if offset
1091            .checked_add(len)
1092            .map_or(true, |end| end > i64::MAX as u64)
1093        {
1094            return Err(file_too_short(offset, len, offset));
1095        }
1096        if self.is_ktls() {
1097            return self.kernel_send_file(file, offset, len).await;
1098        }
1099        const PIECE: u64 = 256 * 1024;
1100        let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1101        let (mut at, mut left) = (offset, len);
1102        while left > 0 {
1103            let (res, b) = file.read_at(buf, at).await;
1104            buf = b;
1105            let n = match res {
1106                Ok(0) => {
1107                    self.flush_tls().await?;
1108                    return Err(file_too_short(offset, len, at));
1109                }
1110                Ok(n) => (n as u64).min(left) as usize,
1111                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1112                Err(e) => return Err(e),
1113            };
1114            let mut sent = 0;
1115            while sent < n {
1116                let accepted = self.conn().writer().write(&buf[sent..n]);
1117                sent += accepted?;
1118                self.flush_tls().await?;
1119            }
1120            at += n as u64;
1121            left -= n as u64;
1122        }
1123        Ok(())
1124    }
1125
1126    /// Sends the TLS `close_notify` alert and closes the sending direction.
1127    pub async fn shutdown(&self) -> io::Result<()> {
1128        if self.is_ktls() {
1129            return self.kernel_shutdown().await;
1130        }
1131        self.conn().send_close_notify();
1132        self.flush_tls().await?;
1133        self.tcp.shutdown(Shutdown::Write)
1134    }
1135
1136    /// `true` once the peer has ended the connection with a TLS
1137    /// `close_notify` alert. `false` while it is open, and if the peer, or
1138    /// something on the network path, closed the TCP connection without
1139    /// one: data that ends there may have been cut short. See
1140    /// [`recv`](Self::recv).
1141    pub fn received_close_notify(&self) -> bool {
1142        self.close_notify.get()
1143    }
1144
1145    /// The protocol agreed on through ALPN, if any (for example `http/1.1`).
1146    pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
1147        match &*self.engine.borrow() {
1148            Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
1149            Engine::Kernel(k) => k.negotiated.alpn.clone(),
1150        }
1151    }
1152
1153    /// The certificate chain the peer presented, its own certificate first:
1154    /// the server's on a client connection; on a server connection, the
1155    /// client's if client authentication is configured and the client sent
1156    /// one.
1157    pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
1158        match &*self.engine.borrow() {
1159            Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
1160            Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
1161        }
1162    }
1163
1164    /// `true` if the handshake resumed an earlier session instead of doing a
1165    /// full one.
1166    pub fn resumed(&self) -> bool {
1167        match &*self.engine.borrow() {
1168            Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
1169            Engine::Kernel(k) => k.negotiated.resumed,
1170        }
1171    }
1172
1173    /// The underlying TCP connection.
1174    pub fn tcp(&self) -> &TcpStream {
1175        &self.tcp
1176    }
1177}
1178
1179impl std::fmt::Debug for TlsStream {
1180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1181        f.debug_struct("TlsStream")
1182            .field("tcp", &self.tcp)
1183            .field("ktls", &self.is_ktls())
1184            .finish_non_exhaustive()
1185    }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190    use super::*;
1191
1192    fn ca_pem(name: &str) -> String {
1193        let key = rcgen::KeyPair::generate().unwrap();
1194        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1195        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1196        params
1197            .distinguished_name
1198            .push(rcgen::DnType::CommonName, name);
1199        params.self_signed(&key).unwrap().pem()
1200    }
1201
1202    /// A fresh, empty directory under the system's temporary directory.
1203    fn scratch(name: &str) -> PathBuf {
1204        let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
1205        let _ = std::fs::remove_dir_all(&dir);
1206        std::fs::create_dir_all(&dir).unwrap();
1207        dir
1208    }
1209
1210    fn os(path: &Path) -> &OsStr {
1211        path.as_os_str()
1212    }
1213
1214    #[test]
1215    fn server_names_are_dns_names_or_ip_addresses() {
1216        let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
1217        let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
1218        assert!(dns("example.com"));
1219        assert!(dns("db.prod.svc.cluster.local"));
1220        assert!(ip("10.0.0.1"));
1221        assert!(ip("::1"));
1222        assert!(ip("[::1]"));
1223        for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
1224            let err = parse_server_name(bad).unwrap_err();
1225            assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
1226        }
1227    }
1228
1229    #[test]
1230    fn the_first_bundle_that_exists_is_read() {
1231        let dir = scratch("bundle");
1232        let bundle = dir.join("bundle.pem");
1233        let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
1234        std::fs::write(&bundle, two).unwrap();
1235        let missing = dir.join("missing.pem");
1236        let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
1237        let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
1238        assert_eq!(roots.len(), 2);
1239        std::fs::remove_dir_all(dir).unwrap();
1240    }
1241
1242    #[test]
1243    fn ssl_cert_file_and_dir_replace_the_system_locations() {
1244        let dir = scratch("env");
1245        let file = dir.join("file.pem");
1246        std::fs::write(&file, ca_pem("from file")).unwrap();
1247        let certs = dir.join("certs");
1248        std::fs::create_dir(&certs).unwrap();
1249        std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
1250        std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
1251        std::fs::write(certs.join("README"), "not a certificate").unwrap();
1252        // OpenSSL's hashed names are links to the same files.
1253        std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
1254        let system = dir.join("system.pem");
1255        std::fs::write(&system, ca_pem("system")).unwrap();
1256        let bundles = [system.to_str().unwrap()];
1257
1258        let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
1259        assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
1260        let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
1261        assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
1262        let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
1263        let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
1264        assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
1265
1266        let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
1267        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1268        assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
1269        std::fs::remove_dir_all(dir).unwrap();
1270    }
1271
1272    #[test]
1273    fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
1274        let dir = scratch("dir");
1275        std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
1276        let roots = load_roots(
1277            None,
1278            None,
1279            &["/nonexistent/bundle.crt"],
1280            dir.to_str().unwrap(),
1281        );
1282        assert_eq!(roots.unwrap().len(), 1);
1283
1284        let empty = scratch("empty");
1285        let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
1286        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1287        assert!(err.to_string().contains("webpki-roots"), "{err}");
1288        std::fs::remove_dir_all(dir).unwrap();
1289        std::fs::remove_dir_all(empty).unwrap();
1290    }
1291
1292    #[test]
1293    fn this_machines_roots_load() {
1294        // Every machine the tests run on (CI included) has a CA bundle.
1295        TlsConnector::with_system_roots().unwrap();
1296    }
1297
1298    #[cfg(feature = "webpki-roots")]
1299    #[test]
1300    fn mozillas_roots_are_compiled_in() {
1301        TlsConnector::with_webpki_roots();
1302    }
1303}