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::{Certificates, 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::with_certificates(&Certificates::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 certs;
82#[cfg(target_os = "macos")]
83mod keychain;
84mod ktls;
85
86/// The flag that makes a send to a closed peer fail with `EPIPE` instead of
87/// raising `SIGPIPE`. macOS has none: giong's sockets carry `SO_NOSIGPIPE`.
88#[cfg(target_os = "linux")]
89const NO_SIGNAL: libc::c_int = libc::MSG_NOSIGNAL;
90#[cfg(target_os = "macos")]
91const NO_SIGNAL: libc::c_int = 0;
92mod received;
93
94pub use certs::Certificates;
95pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
96pub use received::Received;
97/// A certificate in DER form, as [`TlsStream::peer_certificates`] returns
98/// it: from `rustls-pki-types` 1.x, which stays at 1.x whatever rustls does.
99pub use rustls_pki_types::CertificateDer;
100
101/// Entry points for the fuzz targets in `giong-tls/fuzz`. Only built by
102/// `cargo fuzz` (`--cfg fuzzing`); not part of the API.
103#[cfg(fuzzing)]
104#[doc(hidden)]
105pub mod fuzzing {
106    pub use crate::ktls::{check_handshake_messages, check_record_framing};
107}
108
109use std::cell::{Cell, RefCell, RefMut};
110use std::collections::HashSet;
111use std::ffi::OsStr;
112use std::future::poll_fn;
113use std::io::{self, Read, Write};
114use std::mem;
115use std::net::Shutdown;
116use std::path::{Path, PathBuf};
117use std::sync::Arc;
118use std::task::{Poll, Waker};
119use std::time::Duration;
120
121use giong::error::Code;
122use giong::net::TcpStream;
123use giong::time::timeout;
124use rustls::client::ResolvesClientCert;
125use rustls::pki_types::pem::PemObject;
126use rustls::pki_types::{PrivateKeyDer, ServerName};
127use rustls::sign::CertifiedKey;
128use rustls::{
129    ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
130    SignatureScheme,
131};
132
133/// The rustls crate, for building the configurations that
134/// [`TlsAcceptor::from_rustls`] and [`TlsConnector::from_rustls`] take.
135///
136/// Needs the `unstable-rustls` feature. Outside the semver promise: it is
137/// the rustls version giong-tls uses, which a minor release may raise.
138#[cfg(feature = "unstable-rustls")]
139pub use rustls;
140
141fn coded(
142    code: Code,
143    message: impl Into<std::borrow::Cow<'static, str>>,
144    fix: &'static str,
145) -> io::Error {
146    giong::error::Error::new(code, message, fix).into()
147}
148
149/// `send_file` was asked for bytes past the end of the file; it stopped at
150/// `at`.
151fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
152    let end = offset.saturating_add(len);
153    coded(
154        Code::FileTooShort,
155        format!(
156            "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
157            end - at
158        ),
159        "take the length from the open file (File::len), and replace a file that is being \
160         served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
161         than announced, so close the connection.",
162    )
163}
164
165/// PEM data or a certificate file that cannot be used.
166pub(crate) fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
167    coded(
168        Code::BadCertificateData,
169        e.to_string(),
170        "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
171         at least one certificate.",
172    )
173}
174
175/// A private key that cannot be read.
176pub(crate) fn bad_key(e: impl std::fmt::Display) -> io::Error {
177    coded(
178        Code::BadCertificateData,
179        format!("cannot read the private key: {e}"),
180        "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
181         EC forms).",
182    )
183}
184
185/// A certificate and a key that cannot be used together.
186pub(crate) fn mismatched_key(e: rustls::Error) -> io::Error {
187    coded(
188        Code::BadCertificateData,
189        format!("the certificate and the private key cannot be used together: {e}"),
190        "check that the key belongs to the first certificate of the chain, and that its type \
191         (RSA, ECDSA, Ed25519) is supported.",
192    )
193}
194
195/// What rustls reported, with the code that says what to do about it.
196fn tls_error(e: rustls::Error) -> io::Error {
197    match e {
198        // What `openssl req -x509` makes unless told otherwise, and what
199        // rustls reports only as a debug value.
200        rustls::Error::InvalidCertificate(_) if e.to_string().contains("CaUsedAsEndEntity") => {
201            coded(
202                Code::TlsCertificate,
203                "the peer's certificate was rejected: it is marked as a certificate authority \
204                 (basicConstraints CA:TRUE), and an authority's certificate cannot be the \
205                 peer's own (CaUsedAsEndEntity)",
206                "issue the peer's certificate with CA:FALSE: a self-signed one made with \
207                 `openssl req -x509` needs -addext \"basicConstraints=critical,CA:FALSE\"; or \
208                 have the authority sign a separate certificate for the peer.",
209            )
210        }
211        rustls::Error::InvalidCertificate(_) => coded(
212            Code::TlsCertificate,
213            format!("the peer's certificate was rejected: {e}"),
214            "check the name you connect to, the certificate's expiry and its chain; a \
215             private authority has to be trusted with TlsConnector::with_root_pem.",
216        ),
217        e => coded(
218            Code::TlsProtocol,
219            format!("TLS error: {e}"),
220            "check that the other side speaks TLS on this port, and that both sides share a \
221             protocol version and cipher suite.",
222        ),
223    }
224}
225
226/// How long a handshake may take unless configured otherwise.
227const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
228
229fn handshake_timed_out(limit: Duration) -> io::Error {
230    coded(
231        Code::TlsHandshakeTimeout,
232        format!("the TLS handshake did not finish within {limit:?}"),
233        "check that the other side speaks TLS on this port and is not overloaded, or raise \
234         handshake_timeout.",
235    )
236}
237
238fn handshake_eof() -> io::Error {
239    coded(
240        Code::TlsHandshakeEof,
241        "the peer closed the connection during the TLS handshake",
242        "check that the other side speaks TLS on this port, and whether it wants a client \
243         certificate or another server name.",
244    )
245}
246
247/// Most capacity the scratch buffer for outgoing records keeps between
248/// writes. rustls hands over up to 64 KiB of records per call; a buffer that
249/// grew to that is dropped after the write instead of being kept for the
250/// connection's whole life (about 64 KiB per idle connection otherwise).
251const WIRE_KEPT: usize = 16 * 1024;
252
253/// Encrypted records of one write that are sent as soon as this many have
254/// gathered, even if more pieces of the write follow.
255const SEND_AT: usize = 64 * 1024;
256
257#[cfg(test)]
258thread_local! {
259    /// How many bytes one [`TlsStream::flush_now`] may hand to the socket,
260    /// for tests of a socket that takes a record in pieces.
261    static FLUSH_ROOM: Cell<usize> = const { Cell::new(usize::MAX) };
262}
263
264/// How many bytes one `flush_now` may hand to the socket: no limit outside
265/// tests.
266fn flush_room() -> usize {
267    #[cfg(test)]
268    return FLUSH_ROOM.with(Cell::get);
269    #[cfg(not(test))]
270    usize::MAX
271}
272
273/// `true` if `records`, whole TLS records as rustls writes them, hold one
274/// of application data (content type 23; under TLS 1.3 every encrypted
275/// record says so).
276fn has_application_data(records: &[u8]) -> bool {
277    let mut at = 0;
278    while let Some(header) = records.get(at..at + 5) {
279        if header[0] == 23 {
280            return true;
281        }
282        at += 5 + usize::from(u16::from_be_bytes([header[3], header[4]]));
283    }
284    false
285}
286
287/// The error a send fails with once the sending direction has ended for
288/// `code`'s reason.
289fn sending_closed(code: Code) -> io::Error {
290    match code {
291        Code::TlsKeysExhausted => coded(
292            Code::TlsKeysExhausted,
293            "this connection has sent as many TLS records as its cipher allows under one key, \
294             and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
295             close_notify was sent",
296            "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
297             kernel TLS on Linux 6.14 or newer).",
298        ),
299        _ => coded(
300            Code::TlsBroken,
301            "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
302            "open a new connection.",
303        ),
304    }
305}
306
307fn broken() -> io::Error {
308    coded(
309        Code::TlsBroken,
310        "a TLS write failed or was cancelled; nothing more can be sent",
311        "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
312         leaves a partial record or message behind, so the stream cannot go on.",
313    )
314}
315
316/// `true` for `ENOBUFS` on macOS, which has no network buffer for the send
317/// at that moment: the send sent nothing, and giong's own sends wait for
318/// buffers (GIONG-E0028), so the sends here made without waiting treat it
319/// as a full socket. Linux makes a TCP sender wait instead.
320#[inline]
321fn no_buffers(e: &io::Error) -> bool {
322    cfg!(target_os = "macos") && e.raw_os_error() == Some(libc::ENOBUFS)
323}
324
325/// Every certificate in `pem`, or an error if there is none.
326pub(crate) fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
327    let certs = CertificateDer::pem_slice_iter(pem)
328        .collect::<Result<Vec<_>, _>>()
329        .map_err(bad_certificate_data)?;
330    if certs.is_empty() {
331        return Err(bad_certificate_data("no certificate found in the PEM data"));
332    }
333    Ok(certs)
334}
335
336/// The cryptography every configuration giong-tls builds uses: *ring*, or
337/// aws-lc-rs with the `post-quantum` feature, whose key exchange offers
338/// X25519MLKEM768 (a post-quantum hybrid) first.
339pub(crate) fn provider() -> Arc<rustls::crypto::CryptoProvider> {
340    Arc::new(base_provider())
341}
342
343#[cfg(not(feature = "post-quantum"))]
344fn base_provider() -> rustls::crypto::CryptoProvider {
345    rustls::crypto::ring::default_provider()
346}
347
348#[cfg(feature = "post-quantum")]
349fn base_provider() -> rustls::crypto::CryptoProvider {
350    rustls::crypto::aws_lc_rs::default_provider()
351}
352
353/// [`provider`] with AES-128-GCM first, then ChaCha20-Poly1305, then AES-256-GCM,
354/// in each protocol version: the order of [`TlsAcceptor::with_certificates`].
355///
356/// AES-128-GCM is as safe in practice and cheaper: its suites hash with
357/// SHA-256, which processors run in hardware, where AES-256-GCM's TLS 1.3
358/// suite and TLS 1.2 ECDHE suites hash with SHA-384 (about a sixth of a
359/// resumed handshake's CPU time goes to SHA-384 otherwise). Go's and
360/// BoringSSL's servers prefer it the same way. Browsers list it first
361/// already; OpenSSL clients (curl, wrk, Python) list AES-256-GCM first.
362fn provider_aes128_first() -> Arc<rustls::crypto::CryptoProvider> {
363    use rustls::CipherSuite as S;
364    let mut provider = base_provider();
365    // A stable sort: TLS 1.3 suites stay ahead of TLS 1.2 ones, and the
366    // signature algorithms keep their order.
367    provider.cipher_suites.sort_by_key(|suite| {
368        let rank = match suite.suite() {
369            S::TLS13_AES_128_GCM_SHA256
370            | S::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
371            | S::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 => 0,
372            S::TLS13_CHACHA20_POLY1305_SHA256
373            | S::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
374            | S::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 => 1,
375            _ => 2,
376        };
377        (
378            suite.version().version != rustls::ProtocolVersion::TLSv1_3,
379            rank,
380        )
381    });
382    Arc::new(provider)
383}
384
385/// `true` if a ClientHello lists a ChaCha20-Poly1305 suite before every
386/// AES-GCM one: a client without AES instructions (a low-end phone) says
387/// so, and then gets ChaCha20, which it runs several times faster. (The
388/// same test as Go's server.) OpenSSL's clients list AES-256-GCM, then
389/// ChaCha20, then AES-128-GCM, and get AES-128-GCM.
390/// `hello` is the start of what the client sent; `false` if it is not a
391/// ClientHello or ends before the list of cipher suites does.
392fn prefers_chacha(hello: &[u8]) -> bool {
393    // Record header (5), handshake header (4), version (2), random (32).
394    const SESSION_ID: usize = 5 + 4 + 2 + 32;
395    if hello.first() != Some(&22) || hello.get(5) != Some(&1) {
396        return false;
397    }
398    let Some(&id_len) = hello.get(SESSION_ID) else {
399        return false;
400    };
401    let at = SESSION_ID + 1 + usize::from(id_len);
402    let Some(len) = hello.get(at..at + 2) else {
403        return false;
404    };
405    let len = usize::from(u16::from_be_bytes([len[0], len[1]]));
406    let Some(suites) = hello.get(at + 2..at + 2 + len) else {
407        return false;
408    };
409    for suite in suites.chunks_exact(2) {
410        match [suite[0], suite[1]] {
411            // TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384,
412            // ECDHE_ECDSA_/ECDHE_RSA_WITH_AES_128_GCM_SHA256 and _256_GCM_SHA384
413            [0x13, 0x01]
414            | [0x13, 0x02]
415            | [0xc0, 0x2b]
416            | [0xc0, 0x2f]
417            | [0xc0, 0x2c]
418            | [0xc0, 0x30] => return false,
419            // TLS_CHACHA20_POLY1305_SHA256, ECDHE_ECDSA_/ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
420            [0x13, 0x03] | [0xcc, 0xa9] | [0xcc, 0xa8] => return true,
421            _ => {}
422        }
423    }
424    false
425}
426
427/// The two configurations of a [`TlsAcceptor`] built from `certificates`:
428/// the server's cipher suite order (AES-128-GCM first), and a copy in the
429/// client's order, for clients that list ChaCha20 first (see
430/// [`prefers_chacha`]).
431fn server_configs(
432    certificates: &Certificates,
433    verifier: Arc<dyn rustls::server::danger::ClientCertVerifier>,
434) -> io::Result<(ServerConfig, ServerConfig)> {
435    let mut config = ServerConfig::builder_with_provider(provider_aes128_first())
436        .with_safe_default_protocol_versions()
437        .map_err(tls_error)?
438        .with_client_cert_verifier(verifier)
439        .with_cert_resolver(certificates.resolver());
440    let chacha = config.clone();
441    config.ignore_client_order = true;
442    Ok((config, chacha))
443}
444
445/// Turns accepted TCP connections into TLS connections.
446///
447/// Cheap to clone; share one between all workers.
448#[derive(Clone)]
449pub struct TlsAcceptor {
450    config: Arc<ServerConfig>,
451    /// From [`with_certificates`](Self::with_certificates): `config` picks the server's
452    /// favourite cipher suite (AES-128-GCM), and this copy of it the
453    /// client's, for clients that list ChaCha20 first (see
454    /// [`prefers_chacha`]).
455    chacha: Option<Arc<ServerConfig>>,
456    handshake_timeout: Duration,
457    ktls: ktls::Plan,
458    /// From [`with_certificates`](Self::with_certificates): what the
459    /// configurations were built from, to build them again with client
460    /// authentication. `None` for [`from_rustls`](Self::from_rustls).
461    certificates: Option<Certificates>,
462}
463
464impl TlsAcceptor {
465    /// An acceptor using an existing rustls configuration, for what
466    /// [`with_certificates`](Self::with_certificates) and the methods below
467    /// do not cover. The acceptor follows the configuration as given.
468    ///
469    /// Needs the `unstable-rustls` feature. Outside the semver promise: the
470    /// configuration is the rustls version giong-tls uses
471    /// ([`rustls`]), which a minor release may raise.
472    #[cfg(feature = "unstable-rustls")]
473    pub fn from_rustls(config: Arc<ServerConfig>) -> Self {
474        Self::with_config(config)
475    }
476
477    fn with_config(config: Arc<ServerConfig>) -> Self {
478        Self {
479            config,
480            chacha: None,
481            handshake_timeout: HANDSHAKE_TIMEOUT,
482            ktls: ktls::Plan::Off,
483            certificates: None,
484        }
485    }
486
487    /// An acceptor presenting `certificates`: one chain, or several chosen
488    /// by the name the client asks for (SNI), replaceable while the server
489    /// runs (see [`Certificates`]). TLS 1.2 and 1.3 with rustls' default
490    /// cipher suites, no client authentication, and no protocol offered
491    /// through ALPN: set them with [`alpn`](Self::alpn). (giong-http's
492    /// `Server::serve_tls` sets its own.)
493    ///
494    /// Of the suites both sides allow, the server picks AES-128-GCM first,
495    /// as Go's and BoringSSL's servers do: it costs less than AES-256-GCM,
496    /// whose suites hash with SHA-384. A client that lists ChaCha20-Poly1305
497    /// before AES-128-GCM, as clients without AES instructions do, gets
498    /// ChaCha20. An acceptor made with `from_rustls` follows its
499    /// configuration as given.
500    ///
501    /// ```no_run
502    /// use giong_tls::{Certificates, TlsAcceptor};
503    ///
504    /// # fn main() -> std::io::Result<()> {
505    /// let certs = Certificates::from_pem(&std::fs::read("cert.pem")?, &std::fs::read("key.pem")?)?;
506    /// let acceptor = TlsAcceptor::with_certificates(&certs)?.alpn(&[b"h2", b"http/1.1"]);
507    /// # let _ = acceptor;
508    /// # Ok(())
509    /// # }
510    /// ```
511    pub fn with_certificates(certificates: &Certificates) -> io::Result<Self> {
512        let verifier = rustls::server::WebPkiClientVerifier::no_client_auth();
513        let (config, chacha) = server_configs(certificates, verifier)?;
514        Ok(Self {
515            chacha: Some(Arc::new(chacha)),
516            certificates: Some(certificates.clone()),
517            ..Self::with_config(Arc::new(config))
518        })
519    }
520
521    /// Requires every client to present a certificate issued by one of the
522    /// authorities in `ca_pem` (mutual TLS): a client without one, or with
523    /// another, fails the handshake. The accepted client's certificates are
524    /// [`TlsStream::peer_certificates`], the client's own first.
525    ///
526    /// For acceptors made with
527    /// [`with_certificates`](Self::with_certificates); one made with
528    /// `from_rustls` sets client authentication in its configuration, and
529    /// gets `GIONG-E2013` here.
530    pub fn require_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
531        self.client_auth(ca_pem, true)
532    }
533
534    /// Asks clients for a certificate issued by one of the authorities in
535    /// `ca_pem`, and accepts clients that send none:
536    /// [`TlsStream::peer_certificates`] then says which did. A client that
537    /// sends a certificate the authorities did not issue still fails the
538    /// handshake. Otherwise as
539    /// [`require_client_cert`](Self::require_client_cert).
540    pub fn request_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
541        self.client_auth(ca_pem, false)
542    }
543
544    fn client_auth(mut self, ca_pem: &[u8], required: bool) -> io::Result<Self> {
545        let Some(certificates) = &self.certificates else {
546            return Err(coded(
547                Code::TlsConfig,
548                "client certificates cannot be set on an acceptor made with from_rustls",
549                "set client authentication in the rustls configuration given to from_rustls \
550                 (ServerConfig::builder().with_client_cert_verifier), or make the acceptor \
551                 with with_certificates.",
552            ));
553        };
554        let mut roots = RootCertStore::empty();
555        for cert in pem_certs(ca_pem)? {
556            roots.add(cert).map_err(bad_certificate_data)?;
557        }
558        let builder = rustls::server::WebPkiClientVerifier::builder_with_provider(
559            Arc::new(roots),
560            self.config.crypto_provider().clone(),
561        );
562        let builder = if required {
563            builder
564        } else {
565            builder.allow_unauthenticated()
566        };
567        let verifier = builder.build().map_err(bad_certificate_data)?;
568        let (mut config, mut chacha) = server_configs(certificates, verifier)?;
569        // What the other builder methods set: ALPN, and kTLS's secrets.
570        for new in [&mut config, &mut chacha] {
571            new.alpn_protocols = self.config.alpn_protocols.clone();
572            new.enable_secret_extraction = self.config.enable_secret_extraction;
573        }
574        self.config = Arc::new(config);
575        self.chacha = Some(Arc::new(chacha));
576        Ok(self)
577    }
578
579    /// The configuration for a client whose ClientHello starts with
580    /// `hello`.
581    fn config_for(&self, hello: &[u8]) -> Arc<ServerConfig> {
582        match &self.chacha {
583            Some(chacha) if prefers_chacha(hello) => chacha.clone(),
584            _ => self.config.clone(),
585        }
586    }
587
588    /// Applies `change` to every configuration this acceptor holds.
589    fn change_config(&mut self, change: impl Fn(&mut ServerConfig)) {
590        change(Arc::make_mut(&mut self.config));
591        if let Some(chacha) = &mut self.chacha {
592            change(Arc::make_mut(chacha));
593        }
594    }
595
596    /// The protocols to accept through ALPN, most preferred first, for
597    /// example `&[b"h2", b"http/1.1"]`. A client that offers none of them
598    /// fails the handshake; one that offers no ALPN at all is accepted.
599    /// The protocol agreed on is [`TlsStream::alpn_protocol`].
600    ///
601    /// giong-http's `Server::serve_tls` sets this itself, to the protocols
602    /// the server speaks.
603    pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
604        let protocols: Vec<Vec<u8>> = protocols.iter().map(|p| p.to_vec()).collect();
605        self.change_config(|config| config.alpn_protocols = protocols.clone());
606        self
607    }
608
609    /// How long a client may take to complete the TLS handshake (default:
610    /// 10 s).
611    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
612        self.handshake_timeout = timeout;
613        self
614    }
615
616    /// Whether connections hand their keys to the kernel after the
617    /// handshake, so that the kernel encrypts and decrypts (kernel TLS).
618    /// [`Ktls::Off`] by default. See [`Ktls`] for what each mode does, and
619    /// the crate README for when it pays off.
620    ///
621    /// Decided here, once: the running kernel is probed (see
622    /// [`ktls_support`]) and checked against every cipher suite the
623    /// configuration allows. [`Ktls::Required`] fails here with `GIONG-E2009`
624    /// if the kernel cannot take them; [`Ktls::Auto`] then leaves every
625    /// connection in the process instead. A configuration that allows 0-RTT
626    /// data (`max_early_data_size` above 0) cannot use kTLS.
627    ///
628    /// Turns on rustls' `enable_secret_extraction`, which kTLS needs, in this
629    /// acceptor's copy of the configuration, when connections will try the
630    /// kernel (not when `Auto` finds the kernel unable).
631    ///
632    /// ```no_run
633    /// use giong_tls::{Certificates, Ktls, TlsAcceptor};
634    ///
635    /// # fn main() -> std::io::Result<()> {
636    /// let certs = Certificates::from_pem(&std::fs::read("cert.pem")?, &std::fs::read("key.pem")?)?;
637    /// let acceptor = TlsAcceptor::with_certificates(&certs)?
638    ///     .ktls(Ktls::Auto)?;
639    /// # Ok(())
640    /// # }
641    /// ```
642    pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
643        let early_data = self.config.max_early_data_size > 0;
644        self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
645        // Extractable secrets only where they will be handed to the kernel.
646        let extract = self.ktls.tries();
647        if self.config.enable_secret_extraction != extract {
648            self.change_config(|config| config.enable_secret_extraction = extract);
649        }
650        Ok(self)
651    }
652
653    /// Why connections stay in the process although [`Ktls::Auto`] asked for
654    /// kernel TLS, if they all do: the kernel has no `tls` module, lacks a
655    /// cipher suite the configuration allows, or cannot change TLS 1.3 keys.
656    /// `None` otherwise. Worth a line in the log at startup.
657    pub fn ktls_unavailable(&self) -> Option<&str> {
658        self.ktls.unavailable()
659    }
660
661    /// Performs the TLS handshake on an accepted connection.
662    ///
663    /// With kernel TLS (see [`ktls`](Self::ktls)), the keys go to the kernel
664    /// once the handshake is done. Under [`Ktls::Required`], a stream that
665    /// cannot take them fails with `GIONG-E2009` before anything is sent.
666    ///
667    /// Cancel safe: if the future is dropped, the TCP connection it took is
668    /// closed; nothing else changes.
669    pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
670        let tcp = match &self.ktls {
671            ktls::Plan::Off => tcp,
672            ktls::Plan::Try { required } => {
673                let start = ktls::Start::Server(self.config.clone(), self.chacha.clone());
674                match ktls::handshake(tcp, start, self.handshake_timeout).await? {
675                    ktls::Outcome::Kernel(tls) => return Ok(*tls),
676                    ktls::Outcome::Declined(_, e) if *required => return Err(e),
677                    ktls::Outcome::Declined(tcp, _) => {
678                        self.ktls.stayed();
679                        tcp
680                    }
681                }
682            }
683            ktls::Plan::Unavailable(_) => {
684                self.ktls.stayed();
685                tcp
686            }
687        };
688        let Some(_) = &self.chacha else {
689            let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
690            return TlsStream::new(tcp, conn.into())
691                .handshake(self.handshake_timeout, Duration::ZERO, None)
692                .await;
693        };
694        // The configuration depends on the ClientHello: wait for its start,
695        // within the handshake's time.
696        let started = std::time::Instant::now();
697        let first = match timeout(self.handshake_timeout, tcp.recv()).await {
698            Ok(first) => first?,
699            Err(_) => return Err(handshake_timed_out(self.handshake_timeout)),
700        };
701        if first.is_empty() {
702            return Err(handshake_eof());
703        }
704        let conn = ServerConnection::new(self.config_for(&first)).map_err(tls_error)?;
705        TlsStream::new(tcp, conn.into())
706            .handshake(self.handshake_timeout, started.elapsed(), Some(first))
707            .await
708    }
709}
710
711impl std::fmt::Debug for TlsAcceptor {
712    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713        f.debug_struct("TlsAcceptor")
714            .field("handshake_timeout", &self.handshake_timeout)
715            .field("ktls", &self.ktls)
716            .finish_non_exhaustive()
717    }
718}
719
720/// Opens TLS connections to servers, checking their certificates.
721///
722/// Cheap to clone; share one between all workers. Clones share the session
723/// cache, so reconnecting to a server resumes the earlier session and skips
724/// most of the handshake.
725///
726/// ```no_run
727/// use std::time::Duration;
728/// use giong_tls::TlsConnector;
729///
730/// # fn main() -> std::io::Result<()> {
731/// // A private certificate authority, a client certificate for mutual TLS,
732/// // and HTTP/1.1 through ALPN.
733/// let connector = TlsConnector::with_root_pem(&std::fs::read("ca.pem")?)?
734///     .client_auth(&std::fs::read("client.pem")?, &std::fs::read("client.key")?)?
735///     .alpn(&[b"http/1.1"])
736///     .handshake_timeout(Duration::from_secs(5));
737/// # Ok(())
738/// # }
739/// ```
740#[derive(Clone)]
741pub struct TlsConnector {
742    config: Arc<ClientConfig>,
743    handshake_timeout: Duration,
744    ktls: ktls::Plan,
745}
746
747impl TlsConnector {
748    /// A connector using an existing rustls configuration, for what the
749    /// other constructors do not cover (a certificate verifier of its own,
750    /// other protocol versions).
751    ///
752    /// Needs the `unstable-rustls` feature. Outside the semver promise: the
753    /// configuration is the rustls version giong-tls uses
754    /// ([`rustls`]), which a minor release may raise.
755    #[cfg(feature = "unstable-rustls")]
756    pub fn from_rustls(config: Arc<ClientConfig>) -> Self {
757        Self::with_config(config)
758    }
759
760    fn with_config(config: Arc<ClientConfig>) -> Self {
761        Self {
762            config,
763            handshake_timeout: HANDSHAKE_TIMEOUT,
764            ktls: ktls::Plan::Off,
765        }
766    }
767
768    fn from_roots(roots: RootCertStore) -> io::Result<Self> {
769        if roots.is_empty() {
770            return Err(coded(
771                Code::NoTrustedRoots,
772                "no trusted certificate authority given",
773                "pass at least one certificate, or use TlsConnector::with_system_roots.",
774            ));
775        }
776        let config = ClientConfig::builder_with_provider(provider())
777            .with_safe_default_protocol_versions()
778            .map_err(tls_error)?
779            .with_root_certificates(roots)
780            .with_no_client_auth();
781        Ok(Self::with_config(Arc::new(config)))
782    }
783
784    /// A connector that trusts the certificate authorities in `pem`: a
785    /// private CA, or a server's own self-signed certificate.
786    ///
787    /// A self-signed certificate must not be marked as an authority
788    /// (`CA:TRUE`), which `openssl req -x509` does unless it is given
789    /// `-addext "basicConstraints=critical,CA:FALSE"`: a server that
790    /// presents an authority's certificate as its own is refused with
791    /// `GIONG-E2004`, whether the certificate is trusted or not.
792    pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
793        let mut roots = RootCertStore::empty();
794        for cert in pem_certs(pem)? {
795            roots.add(cert).map_err(bad_certificate_data)?;
796        }
797        Self::from_roots(roots)
798    }
799
800    /// A connector that trusts the certificate authorities in `pem` and
801    /// accepts a certificate they signed **whatever host name it is for**:
802    /// the chain, the validity period and the key usage are checked, the
803    /// name is not.
804    ///
805    /// For servers whose certificates name no host, such as the ones MySQL
806    /// generates when it is installed (`ssl-mode=VERIFY_CA`): pass the
807    /// server's own authority. Use it only with an authority that signs for
808    /// this server alone; with a public one, any certificate it issued, for
809    /// any name, would pass. Where the certificate names the host, use
810    /// [`with_root_pem`](Self::with_root_pem), which checks both.
811    pub fn with_root_pem_any_name(pem: &[u8]) -> io::Result<Self> {
812        let mut roots = RootCertStore::empty();
813        for cert in pem_certs(pem)? {
814            roots.add(cert).map_err(bad_certificate_data)?;
815        }
816        if roots.is_empty() {
817            return Err(coded(
818                Code::NoTrustedRoots,
819                "no trusted certificate authority given",
820                "pass at least one certificate authority in PEM form.",
821            ));
822        }
823        let provider = provider();
824        let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
825            Arc::new(roots),
826            provider.clone(),
827        )
828        .build()
829        .map_err(bad_certificate_data)?;
830        let config = ClientConfig::builder_with_provider(provider)
831            .with_safe_default_protocol_versions()
832            .map_err(tls_error)?
833            .dangerous()
834            .with_custom_certificate_verifier(Arc::new(AnyName(webpki)))
835            .with_no_client_auth();
836        Ok(Self::with_config(Arc::new(config)))
837    }
838
839    /// A connector that trusts the certificate authorities installed on this
840    /// machine, read once, now.
841    ///
842    /// They are read from the file named by the `SSL_CERT_FILE` environment
843    /// variable and the directories named by `SSL_CERT_DIR` (separated by
844    /// `:`) if either is set, the way OpenSSL does. Otherwise from the first
845    /// bundle found among the places Linux distributions keep it
846    /// (`/etc/ssl/certs/ca-certificates.crt` on Debian, Ubuntu, Alpine and
847    /// Arch, `/etc/pki/tls/certs/ca-bundle.crt` on Fedora and RHEL, and so
848    /// on), or else from the files in `/etc/ssl/certs`.
849    ///
850    /// On macOS, when neither variable is set, they are the certificates
851    /// the keychain trusts for TLS servers: the roots Apple ships and the
852    /// ones the administrator or the user added, without the ones either
853    /// turned off. If the keychain cannot be read, the bundle in
854    /// `/etc/ssl/cert.pem` is used.
855    ///
856    /// Fails with [`io::ErrorKind::NotFound`] if there are none, as in a
857    /// container image built `FROM scratch` or without the `ca-certificates`
858    /// package. Install that package, or enable the `webpki-roots` feature and
859    /// use `TlsConnector::with_webpki_roots`.
860    pub fn with_system_roots() -> io::Result<Self> {
861        let file = std::env::var_os("SSL_CERT_FILE");
862        let dirs = std::env::var_os("SSL_CERT_DIR");
863        #[cfg(target_os = "macos")]
864        if file.is_none() && dirs.is_none() {
865            let mut roots = RootCertStore::empty();
866            roots.add_parsable_certificates(keychain::trusted_roots());
867            if !roots.is_empty() {
868                return Self::from_roots(roots);
869            }
870        }
871        let roots = load_roots(
872            file.as_deref(),
873            dirs.as_deref(),
874            SYSTEM_CA_BUNDLES,
875            SYSTEM_CA_DIR,
876        )?;
877        Self::from_roots(roots)
878    }
879
880    /// A connector that trusts the certificate authorities in Mozilla's root
881    /// program, compiled into the program by the `webpki-roots` crate. Useful
882    /// where the machine has none installed; they change only when this
883    /// crate's dependency is updated.
884    ///
885    /// Needs the `webpki-roots` feature.
886    #[cfg(feature = "webpki-roots")]
887    pub fn with_webpki_roots() -> Self {
888        let roots = RootCertStore {
889            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
890        };
891        Self::from_roots(roots).expect("the webpki-roots crate provides roots")
892    }
893
894    /// The protocols to offer through ALPN, most preferred first, for example
895    /// `&[b"h2", b"http/1.1"]`. None by default. The one the server picked is
896    /// [`TlsStream::alpn_protocol`].
897    pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
898        Arc::make_mut(&mut self.config).alpn_protocols =
899            protocols.iter().map(|p| p.to_vec()).collect();
900        self
901    }
902
903    /// Presents a client certificate to servers that ask for one (mutual
904    /// TLS): a certificate chain and its private key, both in PEM format.
905    pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
906        let certs = pem_certs(cert_chain)?;
907        let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
908        let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
909            .map_err(mismatched_key)?;
910        Arc::make_mut(&mut self.config).client_auth_cert_resolver =
911            Arc::new(ClientCert(Arc::new(key)));
912        Ok(self)
913    }
914
915    /// How long a server may take to complete the TLS handshake (default:
916    /// 10 s).
917    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
918        self.handshake_timeout = timeout;
919        self
920    }
921
922    /// Whether connections hand their keys to the kernel after the
923    /// handshake, so that the kernel encrypts and decrypts (kernel TLS).
924    /// [`Ktls::Off`] by default; see [`TlsAcceptor::ktls`], which works the
925    /// same way. Session tickets the server sends later still reach the
926    /// session cache, so reconnecting resumes as without kTLS. A
927    /// configuration that allows 0-RTT data (`enable_early_data`) cannot use
928    /// kTLS.
929    ///
930    /// A stream on which [`TcpStream::recv`] was already used, as by a
931    /// protocol that reads a plaintext greeting before TLS starts, cannot
932    /// take kTLS: under [`Ktls::Auto`] it stays in the process, under
933    /// [`Ktls::Required`] it fails with `GIONG-E2009`. Use
934    /// [`TcpStream::read`] for such greetings.
935    pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
936        let early_data = self.config.enable_early_data;
937        self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
938        let extract = self.ktls.tries();
939        if self.config.enable_secret_extraction != extract {
940            Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
941        }
942        Ok(self)
943    }
944
945    /// Why connections stay in the process although [`Ktls::Auto`] asked for
946    /// kernel TLS, if they all do; see [`TlsAcceptor::ktls_unavailable`].
947    pub fn ktls_unavailable(&self) -> Option<&str> {
948        self.ktls.unavailable()
949    }
950
951    /// Performs the TLS handshake on a connection to `server_name`, which the
952    /// server's certificate must be valid for. `server_name` is a DNS name,
953    /// sent to the server through SNI, or an IP address (`[...]` brackets
954    /// around an IPv6 address are allowed), which is not.
955    ///
956    /// A certificate that is not valid for the name, expired, or not issued
957    /// by a trusted authority fails the handshake with
958    /// [`io::ErrorKind::InvalidData`] and a message saying which it was.
959    ///
960    /// Cancel safe: if the future is dropped, the TCP connection it took is
961    /// closed; nothing else changes.
962    pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
963        let name = parse_server_name(server_name)?;
964        let tcp = match &self.ktls {
965            ktls::Plan::Off => tcp,
966            ktls::Plan::Try { required } => {
967                let start = ktls::Start::Client(self.config.clone(), name.clone());
968                match ktls::handshake(tcp, start, self.handshake_timeout).await? {
969                    ktls::Outcome::Kernel(tls) => return Ok(*tls),
970                    ktls::Outcome::Declined(_, e) if *required => return Err(e),
971                    ktls::Outcome::Declined(tcp, _) => {
972                        self.ktls.stayed();
973                        tcp
974                    }
975                }
976            }
977            ktls::Plan::Unavailable(_) => {
978                self.ktls.stayed();
979                tcp
980            }
981        };
982        let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
983        TlsStream::new(tcp, conn.into())
984            .handshake(self.handshake_timeout, Duration::ZERO, None)
985            .await
986    }
987}
988
989impl std::fmt::Debug for TlsConnector {
990    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
991        f.debug_struct("TlsConnector")
992            .field("handshake_timeout", &self.handshake_timeout)
993            .field("ktls", &self.ktls)
994            .finish_non_exhaustive()
995    }
996}
997
998/// The verifier of [`TlsConnector::with_root_pem_any_name`]: checks the
999/// chain like rustls' own, and accepts a certificate whose only fault is that
1000/// it does not name the host.
1001struct AnyName(Arc<rustls::client::WebPkiServerVerifier>);
1002
1003impl std::fmt::Debug for AnyName {
1004    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1005        f.write_str("AnyName")
1006    }
1007}
1008
1009impl rustls::client::danger::ServerCertVerifier for AnyName {
1010    fn verify_server_cert(
1011        &self,
1012        end_entity: &CertificateDer<'_>,
1013        intermediates: &[CertificateDer<'_>],
1014        server_name: &ServerName<'_>,
1015        ocsp_response: &[u8],
1016        now: rustls::pki_types::UnixTime,
1017    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
1018        use rustls::CertificateError;
1019        match self
1020            .0
1021            .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
1022        {
1023            // rustls checks the name only once the chain, the validity
1024            // period and the key usage have passed (the test
1025            // `any_name_still_checks_the_chain` makes sure of it).
1026            Err(rustls::Error::InvalidCertificate(
1027                CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
1028            )) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
1029            other => other,
1030        }
1031    }
1032
1033    fn verify_tls12_signature(
1034        &self,
1035        message: &[u8],
1036        cert: &CertificateDer<'_>,
1037        dss: &rustls::DigitallySignedStruct,
1038    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1039        self.0.verify_tls12_signature(message, cert, dss)
1040    }
1041
1042    fn verify_tls13_signature(
1043        &self,
1044        message: &[u8],
1045        cert: &CertificateDer<'_>,
1046        dss: &rustls::DigitallySignedStruct,
1047    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1048        self.0.verify_tls13_signature(message, cert, dss)
1049    }
1050
1051    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1052        self.0.supported_verify_schemes()
1053    }
1054}
1055
1056/// The name a client checks the server's certificate against.
1057fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
1058    let ipv6 = name
1059        .strip_prefix('[')
1060        .and_then(|n| n.strip_suffix(']'))
1061        .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
1062    if let Some(ip) = ipv6 {
1063        return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
1064    }
1065    ServerName::try_from(name.to_owned()).map_err(|_| {
1066        coded(
1067            Code::InvalidServerName,
1068            format!("{name:?} is neither a DNS name nor an IP address"),
1069            "pass the host name the certificate is for (\"example.com\"), or an IP address, \
1070             without a port or a scheme.",
1071        )
1072    })
1073}
1074
1075/// Always presents the same client certificate.
1076#[derive(Debug)]
1077struct ClientCert(Arc<CertifiedKey>);
1078
1079impl ResolvesClientCert for ClientCert {
1080    fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
1081        Some(self.0.clone())
1082    }
1083
1084    fn has_certs(&self) -> bool {
1085        true
1086    }
1087}
1088
1089/// Where Linux distributions keep the bundle of trusted CA certificates.
1090const SYSTEM_CA_BUNDLES: &[&str] = &[
1091    // Debian, Ubuntu, Alpine, Arch, Gentoo
1092    "/etc/ssl/certs/ca-certificates.crt",
1093    // Fedora, RHEL, CentOS
1094    "/etc/pki/tls/certs/ca-bundle.crt",
1095    "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
1096    // openSUSE, SLES
1097    "/etc/ssl/ca-bundle.pem",
1098    // Alpine, Void
1099    "/etc/ssl/cert.pem",
1100];
1101
1102/// Where they are kept one per file, when there is no bundle.
1103const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
1104
1105/// Reads trusted certificates the way OpenSSL finds them: `file` and `dirs`
1106/// (the `SSL_CERT_FILE` and `SSL_CERT_DIR` variables) if either is set,
1107/// otherwise the first of `bundles` that exists, otherwise the files in
1108/// `dir`. Certificates rustls cannot use are skipped.
1109fn load_roots(
1110    file: Option<&OsStr>,
1111    dirs: Option<&OsStr>,
1112    bundles: &[&str],
1113    dir: &str,
1114) -> io::Result<RootCertStore> {
1115    let mut roots = Roots {
1116        store: RootCertStore::empty(),
1117        seen: HashSet::new(),
1118    };
1119    if file.is_some() || dirs.is_some() {
1120        if let Some(file) = file {
1121            roots.add_file(Path::new(file)).map_err(|e| {
1122                io::Error::new(
1123                    e.kind(),
1124                    giong::error::Error::new(
1125                        Code::BadCertificateData,
1126                        format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
1127                        "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
1128                         it to use the system's.",
1129                    )
1130                    .with_source(e),
1131                )
1132            })?;
1133        }
1134        for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
1135            roots.add_dir(&dir);
1136        }
1137    } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
1138        roots.add_file(bundle)?;
1139    } else {
1140        roots.add_dir(Path::new(dir));
1141    }
1142    if roots.store.is_empty() {
1143        return Err(coded(
1144            Code::NoTrustedRoots,
1145            "no trusted CA certificates found on this machine",
1146            "install the ca-certificates package, set SSL_CERT_FILE, or use \
1147             TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
1148        ));
1149    }
1150    Ok(roots.store)
1151}
1152
1153struct Roots {
1154    store: RootCertStore,
1155    /// Files already read. The hashed names in certificate directories are
1156    /// links to other files there.
1157    seen: HashSet<PathBuf>,
1158}
1159
1160impl Roots {
1161    fn add_file(&mut self, path: &Path) -> io::Result<()> {
1162        let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
1163        if !self.seen.insert(real) {
1164            return Ok(());
1165        }
1166        let pem = std::fs::read(path)?;
1167        let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
1168        self.store.add_parsable_certificates(certs);
1169        Ok(())
1170    }
1171
1172    fn add_dir(&mut self, dir: &Path) {
1173        let Ok(entries) = std::fs::read_dir(dir) else {
1174            return;
1175        };
1176        let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
1177        paths.sort();
1178        for path in paths.iter().filter(|p| p.is_file()) {
1179            // One unreadable file does not spoil the others.
1180            let _ = self.add_file(path);
1181        }
1182    }
1183}
1184
1185/// A TLS connection over a [`TcpStream`], made by [`TlsAcceptor::accept`] on
1186/// the server side or [`TlsConnector::connect`] on the client side.
1187pub struct TlsStream {
1188    tcp: TcpStream,
1189    /// Who encrypts: rustls in the process, or the kernel.
1190    engine: RefCell<Engine>,
1191    /// Decrypted data not handed out yet.
1192    plain: RefCell<Vec<u8>>,
1193    /// Scratch buffer for outgoing TLS records, reused between writes while
1194    /// it is small (see [`WIRE_KEPT`]).
1195    wire: RefCell<Vec<u8>>,
1196    /// The handshake has returned. From then on, records rustls queues in
1197    /// answer to what arrives (TLS 1.3 key updates) may wait for the next
1198    /// send instead of going out alone (see [`hold_output`](Self::hold_output)).
1199    established: Cell<bool>,
1200    /// The peer closed the connection (with or without `close_notify`).
1201    eof: Cell<bool>,
1202    /// The peer ended its side with a `close_notify` alert, so nothing it
1203    /// sent was cut off.
1204    close_notify: Cell<bool>,
1205    /// A task is writing TLS records to the socket: one `write_all` (or
1206    /// vectored write, or file) at a time, so that neither records nor two
1207    /// tasks' data interleave. Other tasks wait for it in `waiters`.
1208    sending: Cell<bool>,
1209    /// A write to the socket failed or was cancelled half way: the record
1210    /// stream is cut in the middle and nothing more can be sent.
1211    broken: Cell<bool>,
1212    /// The sending direction ended cleanly, and why: `TlsBroken` after
1213    /// `shutdown` or a fatal alert, `TlsKeysExhausted` when the key may
1214    /// encrypt no more records and cannot be changed.
1215    closed: Cell<Option<Code>>,
1216    /// A receive error held back until the data before it has been handed out.
1217    failed: Cell<Option<io::Error>>,
1218    /// Tasks waiting for `sending` to clear.
1219    waiters: RefCell<Vec<Waker>>,
1220    /// Whole or cut records a receive began to send and the socket did not
1221    /// take at once (see [`flush_now`](Self::flush_now)): the next bytes this
1222    /// stream sends, ahead of anything rustls has queued since.
1223    unsent: RefCell<Vec<u8>>,
1224}
1225
1226/// Who encrypts and decrypts a [`TlsStream`].
1227// Both variants are large and a stream holds one for its whole life; a box
1228// would cost an allocation and a pointer to follow on every call.
1229#[allow(clippy::large_enum_variant)]
1230enum Engine {
1231    /// rustls, in the process.
1232    User(Connection),
1233    /// The kernel; rustls keeps what it needs for key updates and session
1234    /// tickets.
1235    Kernel(ktls::Kernel),
1236}
1237
1238/// Held while TLS records are being written to the socket. Dropped without
1239/// [`done`](Self::done), as when the future writing is cancelled, it marks
1240/// the stream broken.
1241struct Sending<'a> {
1242    stream: &'a TlsStream,
1243    complete: bool,
1244}
1245
1246impl Sending<'_> {
1247    /// The records went out whole (or none did).
1248    fn done(mut self) {
1249        self.complete = true;
1250    }
1251}
1252
1253impl Drop for Sending<'_> {
1254    fn drop(&mut self) {
1255        if !self.complete {
1256            self.stream.broken.set(true);
1257        }
1258        self.stream.sending.set(false);
1259        self.stream.wake_waiters();
1260    }
1261}
1262
1263impl TlsStream {
1264    fn new(tcp: TcpStream, conn: Connection) -> Self {
1265        Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
1266    }
1267
1268    /// A stream the kernel encrypts. `plain` is application data that arrived
1269    /// with the end of the handshake; `peer_closed` says `close_notify` did
1270    /// too.
1271    fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
1272        Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
1273    }
1274
1275    fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
1276        Self {
1277            tcp,
1278            engine: RefCell::new(engine),
1279            plain: RefCell::new(plain),
1280            wire: RefCell::new(Vec::new()),
1281            established: Cell::new(false),
1282            eof: Cell::new(peer_closed),
1283            close_notify: Cell::new(peer_closed),
1284            sending: Cell::new(false),
1285            broken: Cell::new(false),
1286            closed: Cell::new(None),
1287            failed: Cell::new(None),
1288            waiters: RefCell::new(Vec::new()),
1289            unsent: RefCell::new(Vec::new()),
1290        }
1291    }
1292
1293    /// rustls' connection, on a stream rustls encrypts. Never held across
1294    /// an `.await`.
1295    fn conn(&self) -> RefMut<'_, Connection> {
1296        RefMut::map(self.engine.borrow_mut(), |e| match e {
1297            Engine::User(c) => c,
1298            Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
1299        })
1300    }
1301
1302    /// `true` if the kernel encrypts and decrypts this connection (kernel
1303    /// TLS, see [`TlsAcceptor::ktls`]); `false` if rustls does, in the
1304    /// process.
1305    pub fn is_ktls(&self) -> bool {
1306        matches!(*self.engine.borrow(), Engine::Kernel(_))
1307    }
1308
1309    /// Waits until no other task is writing records.
1310    async fn wait_for_sender(&self) {
1311        poll_fn(|cx| {
1312            if !self.sending.get() {
1313                return Poll::Ready(());
1314            }
1315            // A task polled again while it waits is listed once.
1316            let mut waiters = self.waiters.borrow_mut();
1317            if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
1318                waiters.push(cx.waker().clone());
1319            }
1320            Poll::Pending
1321        })
1322        .await;
1323    }
1324
1325    /// Waits for other writers, then makes this task the one writing records
1326    /// until the guard is dropped.
1327    async fn lock_send(&self) -> Sending<'_> {
1328        while self.sending.get() {
1329            self.wait_for_sender().await;
1330        }
1331        self.sending.set(true);
1332        Sending {
1333            stream: self,
1334            complete: false,
1335        }
1336    }
1337
1338    /// Runs the handshake, either side, within what is left of `limit`
1339    /// after `spent`. `first` is what the peer sent first, if the caller
1340    /// has received it already.
1341    async fn handshake(
1342        self,
1343        limit: Duration,
1344        spent: Duration,
1345        first: Option<giong::RecvBuf>,
1346    ) -> io::Result<Self> {
1347        let handshake = async {
1348            if let Some(first) = first {
1349                self.absorb(first).await?;
1350            }
1351            while self.conn().is_handshaking() {
1352                self.flush_tls().await?;
1353                if !self.conn().is_handshaking() {
1354                    break;
1355                }
1356                if self.eof.get() {
1357                    return Err(handshake_eof());
1358                }
1359                self.pump().await?;
1360            }
1361            if !self.hold_output() {
1362                self.flush_tls().await?;
1363            }
1364            self.established.set(true);
1365            Ok(())
1366        };
1367        match timeout(limit.saturating_sub(spent), handshake).await {
1368            Ok(Ok(())) => Ok(self),
1369            Ok(Err(e)) => Err(e),
1370            Err(_) => Err(handshake_timed_out(limit)),
1371        }
1372    }
1373
1374    /// Wakes the tasks waiting for the send lock, or for their records to
1375    /// be sent (see [`flush_tls`](Self::flush_tls)).
1376    fn wake_waiters(&self) {
1377        let waiters = mem::take(&mut *self.waiters.borrow_mut());
1378        for waker in waiters {
1379            waker.wake();
1380        }
1381    }
1382
1383    /// `true` if the records rustls has queued may wait for this stream's
1384    /// next send, or for a receive that has to wait (see
1385    /// [`pump`](Self::pump)), instead of going out alone now.
1386    ///
1387    /// That is the case once the handshake is over on a TLS 1.3 server,
1388    /// whose only records then are session tickets, and on either side after
1389    /// the handshake has returned, where they can only be key updates
1390    /// answering the peer's (which TLS 1.3 asks to be sent before the next
1391    /// data, not at once). A server's tickets then share a segment with its
1392    /// first response, the way most clients send their `Finished` with
1393    /// their first request. Never while handshaking, and never on TLS 1.2,
1394    /// whose server sends its last flight after the client's `Finished`:
1395    /// the peer waits for those records.
1396    fn hold_output(&self) -> bool {
1397        if self.established.get() {
1398            // TLS 1.3 has no second handshake, and rustls refuses TLS 1.2
1399            // renegotiation.
1400            return true;
1401        }
1402        let conn = self.conn();
1403        if conn.is_handshaking() {
1404            return false;
1405        }
1406        (matches!(*conn, Connection::Server(_))
1407            && conn.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3))
1408    }
1409
1410    /// Takes the scratch buffer for outgoing records. It starts with what
1411    /// a receive left unsent (see [`flush_now`](Self::flush_now)), which has
1412    /// to go out before anything else. The caller holds the send lock.
1413    fn take_wire(&self) -> Vec<u8> {
1414        let mut wire = mem::take(&mut *self.wire.borrow_mut());
1415        let mut unsent = self.unsent.borrow_mut();
1416        if unsent.capacity() > 0 {
1417            wire.extend_from_slice(&unsent);
1418            // Not `clear`: an idle connection keeps no buffer for this.
1419            *unsent = Vec::new();
1420        }
1421        wire
1422    }
1423
1424    /// Keeps `wire` for the next write, unless a large write grew it: a
1425    /// connection that once sent a large response should not hold that much
1426    /// for the rest of its life.
1427    fn keep_wire(&self, mut wire: Vec<u8>) {
1428        if !wire.is_empty() && !self.broken.get() {
1429            // The write ended before its first send (a file that could not
1430            // be read, say): what `take_wire` handed over is still owed.
1431            self.unsent.borrow_mut().append(&mut wire);
1432        }
1433        if wire.capacity() <= WIRE_KEPT {
1434            wire.clear();
1435            *self.wire.borrow_mut() = wire;
1436        }
1437    }
1438
1439    /// The error a send fails with before it starts, if the stream cannot
1440    /// send any more.
1441    fn cannot_send(&self) -> Option<io::Error> {
1442        if self.broken.get() {
1443            return Some(broken());
1444        }
1445        self.closed.get().map(sending_closed)
1446    }
1447
1448    /// Sends every TLS record rustls has queued: handshake messages, key
1449    /// updates, alerts. A task that is writing sends them with its own data
1450    /// (see [`send_plain`](Self::send_plain)); this waits for it.
1451    async fn flush_tls(&self) -> io::Result<()> {
1452        loop {
1453            if !self.wants_send() {
1454                return Ok(());
1455            }
1456            if self.broken.get() {
1457                return Err(broken());
1458            }
1459            if self.sending.get() {
1460                // The writer sends these records before its next piece of
1461                // data, and wakes us then; or it finishes and frees the lock.
1462                self.wait_for_sender().await;
1463                continue;
1464            }
1465            let sending = self.lock_send().await;
1466            let mut wire = self.take_wire();
1467            let res = self.send_queued(&mut wire).await;
1468            self.keep_wire(wire);
1469            sending.done();
1470            res?;
1471        }
1472    }
1473
1474    /// Moves every record rustls has queued into `wire`, after what it
1475    /// holds already, and sends them. The caller holds the send lock.
1476    async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1477        loop {
1478            {
1479                let mut conn = self.conn();
1480                while conn.wants_write() {
1481                    conn.write_tls(wire)?;
1482                }
1483            }
1484            if wire.is_empty() {
1485                return Ok(());
1486            }
1487            self.send_wire(wire).await?;
1488        }
1489    }
1490
1491    /// `true` if records wait to be sent: queued by rustls, or left unsent
1492    /// by a receive.
1493    fn wants_send(&self) -> bool {
1494        self.conn().wants_write() || !self.unsent.borrow().is_empty()
1495    }
1496
1497    /// Sends the records rustls has queued without waiting, for a receive on
1498    /// an established stream: a receive may be dropped at any `.await`, and a
1499    /// send dropped half way would cut a record in two and end the stream's
1500    /// sending for good. One `send(2)` that does not block has no half way:
1501    /// what the socket takes is sent, and what it does not take stays in
1502    /// `unsent`, in order, for the next send or the next receive to go on
1503    /// from. The peer waits for none of these records (key updates, session
1504    /// tickets, an alert), so they may be late.
1505    ///
1506    /// Does nothing while a task is writing: it sends queued records with
1507    /// its own data, and `unsent` is empty while it holds the lock.
1508    fn flush_now(&self) -> io::Result<()> {
1509        if self.broken.get() {
1510            return Err(broken());
1511        }
1512        if self.sending.get() {
1513            return Ok(());
1514        }
1515        let mut unsent = self.unsent.borrow_mut();
1516        {
1517            let mut conn = self.conn();
1518            while conn.wants_write() {
1519                conn.write_tls(&mut *unsent)?;
1520            }
1521        }
1522        loop {
1523            // All of it, or as much as a test lets the socket take.
1524            let len = unsent.len().min(flush_room());
1525            if len == 0 {
1526                return Ok(());
1527            }
1528            // SAFETY: `unsent` is valid for `len` bytes for the call.
1529            let n = unsafe {
1530                libc::send(
1531                    std::os::fd::AsRawFd::as_raw_fd(&self.tcp),
1532                    unsent.as_ptr().cast(),
1533                    len,
1534                    libc::MSG_DONTWAIT | NO_SIGNAL,
1535                )
1536            };
1537            if n >= 0 {
1538                if n as usize == unsent.len() {
1539                    // All sent: an idle connection keeps no buffer for this.
1540                    *unsent = Vec::new();
1541                } else {
1542                    // What the socket did not take waits in `unsent`.
1543                    unsent.drain(..n as usize);
1544                }
1545                return Ok(());
1546            }
1547            let e = io::Error::last_os_error();
1548            match e.kind() {
1549                io::ErrorKind::Interrupted => {}
1550                io::ErrorKind::WouldBlock => return Ok(()),
1551                // macOS out of network buffers: like a full socket, what was
1552                // not sent waits for the next send, which waits for them.
1553                _ if no_buffers(&e) => return Ok(()),
1554                _ => {
1555                    self.broken.set(true);
1556                    *unsent = Vec::new();
1557                    return Err(e);
1558                }
1559            }
1560        }
1561    }
1562
1563    /// Writes all of `wire` to the socket and empties it, keeping its
1564    /// capacity for the rest of this write. A failure may have cut a record
1565    /// in two, so it marks the stream broken.
1566    async fn send_wire(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1567        let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
1568        sent.clear();
1569        *wire = sent;
1570        if res.is_err() {
1571            self.broken.set(true);
1572        }
1573        res
1574    }
1575
1576    /// Encrypts all of `data` and sends it, in the process. The caller holds
1577    /// the send lock.
1578    ///
1579    /// rustls takes up to its buffer limit (64 KiB) per call. Records a
1580    /// receive queued in the meantime (a key update, an alert) go out first.
1581    ///
1582    /// With `last` false, the records of the end of `data` may stay in
1583    /// `wire` for the next piece of the same write to join them, so that a
1584    /// response's head and body share one send; the caller passes `last`
1585    /// true for the final piece. Records the caller found queued (`carried`)
1586    /// are followed by a send in the same call.
1587    async fn send_plain(&self, wire: &mut Vec<u8>, data: &[u8], last: bool) -> io::Result<()> {
1588        let mut sent = 0;
1589        while sent < data.len() {
1590            let (carried, refused) = {
1591                let mut conn = self.conn();
1592                while conn.wants_write() {
1593                    conn.write_tls(wire)?;
1594                }
1595                let carried = !wire.is_empty();
1596                let start = wire.len();
1597                let n = conn.writer().write(&data[sent..])?;
1598                while conn.wants_write() {
1599                    conn.write_tls(wire)?;
1600                }
1601                sent += n;
1602                // rustls took the bytes and encrypted none of them: the key
1603                // has encrypted as many records as its cipher allows and,
1604                // on TLS 1.2, cannot be changed. rustls queued close_notify
1605                // instead and drops everything it is given from then on.
1606                (carried, n > 0 && !has_application_data(&wire[start..]))
1607            };
1608            let more = sent < data.len() || !last;
1609            if !wire.is_empty() && (carried || refused || !more || wire.len() >= SEND_AT) {
1610                self.send_wire(wire).await?;
1611            }
1612            if carried {
1613                // Receivers waiting in `flush_tls` for these records.
1614                self.wake_waiters();
1615            }
1616            if refused {
1617                self.closed.set(Some(Code::TlsKeysExhausted));
1618                return Err(sending_closed(Code::TlsKeysExhausted));
1619            }
1620        }
1621        Ok(())
1622    }
1623
1624    /// One write in the process: `pieces` encrypted and sent in order,
1625    /// holding the send lock throughout, so that no other task's write comes
1626    /// between them.
1627    async fn write_in_process(&self, pieces: &[&[u8]]) -> io::Result<()> {
1628        let sending = self.lock_send().await;
1629        if let Some(e) = self.cannot_send() {
1630            sending.done();
1631            return Err(e);
1632        }
1633        let mut wire = self.take_wire();
1634        let mut res = Ok(());
1635        for (i, piece) in pieces.iter().enumerate() {
1636            res = self
1637                .send_plain(&mut wire, piece, i + 1 == pieces.len())
1638                .await;
1639            if res.is_err() {
1640                break;
1641            }
1642        }
1643        if res.is_ok() && !wire.is_empty() {
1644            // Records of pieces that came before empty last ones.
1645            res = self.send_wire(&mut wire).await;
1646        }
1647        self.keep_wire(wire);
1648        // A failure on the socket has marked the stream broken already; one
1649        // before anything was sent (rustls refusing the data, keys used up,
1650        // a file read) leaves it whole.
1651        sending.done();
1652        res
1653    }
1654
1655    /// Receives one chunk of TLS data, decrypts it into `plain`, and sends
1656    /// whatever the protocol wants to send in response.
1657    async fn pump(&self) -> io::Result<()> {
1658        // Records held back for the next send (see `hold_output`) go out
1659        // now if the receive has to wait: the peer may be waiting for them.
1660        let ready = if !self.broken.get() && self.wants_send() {
1661            poll_fn(|cx| Poll::Ready(self.tcp.poll_recv(cx))).await
1662        } else {
1663            Poll::Pending
1664        };
1665        let chunk = match ready {
1666            Poll::Ready(chunk) => chunk?,
1667            Poll::Pending => {
1668                if !self.broken.get() && self.wants_send() {
1669                    // A failure marks the stream broken, for the next write
1670                    // to report; it is no reason to withhold what arrives
1671                    // (the peer may have sent its last data and gone).
1672                    let _ = self.flush_for_recv().await;
1673                }
1674                // Cancelling here loses nothing: `recv` is cancel safe.
1675                self.tcp.recv().await?
1676            }
1677        };
1678        self.absorb(chunk).await
1679    }
1680
1681    /// Decrypts a received `chunk` into `plain`, and sends whatever the
1682    /// protocol wants to send in response (unless it may wait, see
1683    /// [`hold_output`](Self::hold_output)).
1684    async fn absorb(&self, chunk: giong::RecvBuf) -> io::Result<()> {
1685        if chunk.is_empty() {
1686            self.eof.set(true);
1687            return Ok(());
1688        }
1689        let result = {
1690            let mut conn = self.conn();
1691            let mut plain = self.plain.borrow_mut();
1692            let mut input = &chunk[..];
1693            let mut result = Ok(());
1694            while !input.is_empty() {
1695                // rustls buffers a bounded amount of plaintext, so it has to
1696                // be drained as the records are fed in.
1697                match conn.read_tls(&mut input) {
1698                    Ok(0) => {
1699                        result = Err(coded(
1700                            Code::TlsProtocol,
1701                            "rustls accepted no more TLS data",
1702                            "this is a bug in giong-tls; please report it at \
1703                             https://github.com/giong-run/Giong/issues.",
1704                        ));
1705                        break;
1706                    }
1707                    Ok(_) => {}
1708                    Err(e) => {
1709                        result = Err(e);
1710                        break;
1711                    }
1712                }
1713                match conn.process_new_packets() {
1714                    Ok(state) => {
1715                        let n = state.plaintext_bytes_to_read();
1716                        if n > 0 {
1717                            let at = plain.len();
1718                            plain.resize(at + n, 0);
1719                            if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
1720                                plain.truncate(at);
1721                                result = Err(e);
1722                                break;
1723                            }
1724                        }
1725                        if state.peer_has_closed() {
1726                            self.close_notify.set(true);
1727                            self.eof.set(true);
1728                            break;
1729                        }
1730                    }
1731                    Err(e) => {
1732                        result = Err(tls_error(e));
1733                        break;
1734                    }
1735                }
1736            }
1737            result
1738        };
1739        drop(chunk);
1740        // Handshake messages, key updates, or the alert describing `result`.
1741        // Not being able to send them is no reason to withhold what was
1742        // received, if sending has failed before.
1743        if self.broken.get() || (result.is_ok() && self.hold_output()) {
1744            return result;
1745        }
1746        let flushed = self.flush_for_recv().await;
1747        result.and(flushed)
1748    }
1749
1750    /// Sends queued records on behalf of a receive. During the handshake
1751    /// the peer waits for them and the future is the handshake's own, so
1752    /// they are sent in full. Afterwards the receive may be dropped at any
1753    /// moment and must leave the stream able to send: see
1754    /// [`flush_now`](Self::flush_now).
1755    async fn flush_for_recv(&self) -> io::Result<()> {
1756        if self.established.get() {
1757            self.flush_now()
1758        } else {
1759            self.flush_tls().await
1760        }
1761    }
1762
1763    /// Receives decrypted data. An empty buffer means that the peer has closed
1764    /// the connection, with a `close_notify` alert or by closing the socket.
1765    ///
1766    /// The two are not the same when the end of the stream is what marks
1767    /// the end of the data, as in an HTTP response without a length: only
1768    /// `close_notify` is authenticated, while anyone on the network path can
1769    /// close a TCP connection early and cut the data short (a truncation
1770    /// attack). Check [`received_close_notify`](Self::received_close_notify)
1771    /// before trusting such data to be complete.
1772    ///
1773    /// Cancel safe: dropping the future loses no data and leaves the stream
1774    /// able to send. A TLS protocol message the receive owes the peer (a key
1775    /// update, session tickets) is sent without waiting, and what the socket
1776    /// does not take at once goes out with the next send or receive.
1777    ///
1778    /// One task may receive while others send. Only one task may receive at
1779    /// a time: like [`TcpStream::recv`], the stream wakes only the task that
1780    /// waited last, so a second receiver can wait forever.
1781    pub async fn recv(&self) -> io::Result<Received> {
1782        if self.is_ktls() {
1783            return self.kernel_recv().await.map(Received);
1784        }
1785        self.user_recv().await.map(Received)
1786    }
1787
1788    async fn user_recv(&self) -> io::Result<Vec<u8>> {
1789        loop {
1790            {
1791                let mut plain = self.plain.borrow_mut();
1792                if !plain.is_empty() {
1793                    return Ok(mem::take(&mut *plain));
1794                }
1795            }
1796            if let Some(e) = self.failed.take() {
1797                return Err(e);
1798            }
1799            if self.eof.get() {
1800                return Ok(Vec::new());
1801            }
1802            if let Err(e) = self.pump().await {
1803                // Data that arrived intact before the failure comes first.
1804                if self.plain.borrow().is_empty() {
1805                    return Err(e);
1806                }
1807                self.failed.set(Some(e));
1808            }
1809        }
1810    }
1811
1812    /// Encrypts and sends all of `buf`, then hands the buffer back.
1813    ///
1814    /// Takes any buffer giong can send, as [`TcpStream::write_all`] does:
1815    /// a `Vec<u8>`, a `Box<[u8]>`, an `Rc<[u8]>`, a `&'static [u8]`, ...
1816    ///
1817    /// Each write goes out whole: another task's `write_all`,
1818    /// [`write_all_vectored`](Self::write_all_vectored) or
1819    /// [`send_file`](Self::send_file) on the same stream waits for it, and
1820    /// their data never interleave.
1821    ///
1822    /// Fails with `TlsKeysExhausted` (`GIONG-E2012`) once the connection has
1823    /// sent as many records as its cipher allows under one key and cannot
1824    /// change keys (TLS 1.2 with AES-GCM after 2^24 records: rustls sends
1825    /// `close_notify`, and nothing more can be sent); with `TlsBroken`
1826    /// (`GIONG-E2008`) after [`shutdown`](Self::shutdown) or a failed write.
1827    ///
1828    /// Not cancel safe: if the future is dropped, part of `buf` may have been
1829    /// sent, and if that happened in the middle of a TLS record the
1830    /// connection cannot send any more: later writes return an error, while
1831    /// data the peer already sent can still be received.
1832    pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1833    where
1834        B: giong::IoBuf + AsRef<[u8]>,
1835    {
1836        if self.is_ktls() {
1837            return self.kernel_write_all(buf).await;
1838        }
1839        let res = self.write_in_process(&[buf.as_ref()]).await;
1840        (res, buf)
1841    }
1842
1843    /// Encrypts and sends all of `bufs`, one after the other, without
1844    /// copying them into one buffer first, then hands them back.
1845    ///
1846    /// Use it to send a header and a large body that live in different
1847    /// buffers. In the process, rustls takes the pieces one by one, so a
1848    /// small header goes out in the same write as the start of the body;
1849    /// with kernel TLS they go to the kernel in vectored writes, as with
1850    /// [`TcpStream::write_all_vectored`]. All of them go out as one write,
1851    /// as with [`write_all`](Self::write_all), which also has the errors.
1852    ///
1853    /// Not cancel safe, as [`write_all`](Self::write_all).
1854    pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1855    where
1856        B: giong::IoBuf + AsRef<[u8]>,
1857    {
1858        if self.is_ktls() {
1859            return self.kernel_write_all_vectored(bufs).await;
1860        }
1861        let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1862        let res = self.write_in_process(&pieces).await;
1863        drop(pieces);
1864        (res, bufs)
1865    }
1866
1867    /// Encrypts and sends `len` bytes of `file`, starting at `offset`.
1868    ///
1869    /// With kernel TLS (see [`is_ktls`](Self::is_ktls)) this is
1870    /// [`TcpStream::send_file`]: the kernel encrypts the file straight from
1871    /// its page cache, and the bytes never pass through the program. This is
1872    /// where kernel TLS is faster than encrypting in the process. Without
1873    /// it, the file is read in pieces of up to 256 KiB and encrypted by
1874    /// rustls. Either way, the file's own position is neither used nor
1875    /// moved.
1876    ///
1877    /// Fails with `FileTooShort` (`GIONG-E0201`) if the file ends before
1878    /// `offset + len`, after sending what it had; the stream can still send.
1879    /// The notes of [`TcpStream::send_file`] on cold files apply to kernel
1880    /// TLS.
1881    ///
1882    /// Not cancel safe, as [`write_all`](Self::write_all).
1883    pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1884        if offset
1885            .checked_add(len)
1886            .map_or(true, |end| end > i64::MAX as u64)
1887        {
1888            return Err(file_too_short(offset, len, offset));
1889        }
1890        if self.is_ktls() {
1891            return self.kernel_send_file(file, offset, len).await;
1892        }
1893        let sending = self.lock_send().await;
1894        if let Some(e) = self.cannot_send() {
1895            sending.done();
1896            return Err(e);
1897        }
1898        let mut wire = self.take_wire();
1899        let res = self
1900            .send_file_in_process(&mut wire, file, offset, len)
1901            .await;
1902        self.keep_wire(wire);
1903        sending.done();
1904        res
1905    }
1906
1907    /// `send_file` in the process: read and encrypt the file in pieces. The
1908    /// caller holds the send lock.
1909    async fn send_file_in_process(
1910        &self,
1911        wire: &mut Vec<u8>,
1912        file: &giong::fs::File,
1913        offset: u64,
1914        len: u64,
1915    ) -> io::Result<()> {
1916        const PIECE: u64 = 256 * 1024;
1917        let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1918        let (mut at, mut left) = (offset, len);
1919        while left > 0 {
1920            let (res, b) = file.read_at(buf, at).await;
1921            buf = b;
1922            let n = match res {
1923                Ok(0) => return Err(file_too_short(offset, len, at)),
1924                Ok(n) => (n as u64).min(left) as usize,
1925                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1926                Err(e) => return Err(e),
1927            };
1928            self.send_plain(wire, &buf[..n], true).await?;
1929            at += n as u64;
1930            left -= n as u64;
1931        }
1932        Ok(())
1933    }
1934
1935    /// Sends the records `shutdown` queued (`close_notify`, and any held
1936    /// back before it) so that they share a segment with the FIN that
1937    /// follows: one `send(2)` with `MSG_MORE` holds them in the socket until
1938    /// `shutdown(2)` adds the FIN and pushes both. What that call cannot
1939    /// take at once goes the usual way. The caller holds the send lock, so
1940    /// no other send is in flight.
1941    async fn send_closing(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1942        {
1943            let mut conn = self.conn();
1944            while conn.wants_write() {
1945                conn.write_tls(wire)?;
1946            }
1947        }
1948        // Linux holds the bytes for the FIN (`MSG_MORE`) and takes
1949        // `MSG_NOSIGNAL`; elsewhere this is a plain send that does not wait,
1950        // on a socket giong made with `SO_NOSIGPIPE`.
1951        #[cfg(target_os = "linux")]
1952        const FLAGS: libc::c_int = libc::MSG_MORE | libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL;
1953        #[cfg(target_os = "macos")]
1954        const FLAGS: libc::c_int = libc::MSG_DONTWAIT;
1955        // SAFETY: `wire` is valid for `wire.len()` bytes for the call.
1956        let n = unsafe {
1957            libc::send(
1958                std::os::fd::AsRawFd::as_raw_fd(&self.tcp),
1959                wire.as_ptr().cast(),
1960                wire.len(),
1961                FLAGS,
1962            )
1963        };
1964        if n >= 0 {
1965            wire.drain(..n as usize);
1966        } else {
1967            let e = io::Error::last_os_error();
1968            // Out of network buffers (macOS): `send_wire` below waits for
1969            // them, as for room in the socket.
1970            if !matches!(
1971                e.kind(),
1972                io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
1973            ) && !no_buffers(&e)
1974            {
1975                self.broken.set(true);
1976                wire.clear();
1977                return Err(e);
1978            }
1979        }
1980        if !wire.is_empty() {
1981            self.send_wire(wire).await?;
1982        }
1983        self.send_queued(wire).await
1984    }
1985
1986    /// Sends the TLS `close_notify` alert and closes the sending direction.
1987    ///
1988    /// Waits for a write in progress. After that, writes fail with
1989    /// `TlsBroken` (`GIONG-E2008`). On a stream that can no longer send (a
1990    /// failed or cancelled write, keys used up, a second `shutdown`), only
1991    /// the TCP sending direction is closed, with no alert.
1992    ///
1993    /// If the peer has closed its socket already, so that the alert cannot
1994    /// be delivered (`EPIPE`, `ECONNRESET`: a client that sent its own
1995    /// `close_notify` and left, which the stream may not have read yet),
1996    /// this returns `Ok`: the sending direction is closed either way, and
1997    /// nobody is left to tell (Tokio's `TcpStream::shutdown` likewise
1998    /// returns `Ok` for `ENOTCONN` after a reset). A failure of an earlier
1999    /// write is still reported by that write.
2000    ///
2001    /// Not cancel safe: if the future is dropped, the `close_notify` alert may
2002    /// have been sent in part, and the stream can send nothing more.
2003    pub async fn shutdown(&self) -> io::Result<()> {
2004        if self.is_ktls() {
2005            return self.kernel_shutdown().await;
2006        }
2007        let sending = self.lock_send().await;
2008        if self.cannot_send().is_none() {
2009            self.conn().send_close_notify();
2010            self.closed.set(Some(Code::TlsBroken));
2011            let mut wire = self.take_wire();
2012            let res = self.send_closing(&mut wire).await;
2013            self.keep_wire(wire);
2014            if let Err(e) = res {
2015                // Close the TCP side anyway, so the peer is not left waiting.
2016                sending.done();
2017                let _ = self.tcp.shutdown(Shutdown::Write);
2018                return if self.peer_gone(&e) { Ok(()) } else { Err(e) };
2019            }
2020        }
2021        sending.done();
2022        self.tcp.shutdown(Shutdown::Write)
2023    }
2024
2025    /// `true` if `e`, from sending `close_notify`, only says that the peer
2026    /// has closed its socket.
2027    fn peer_gone(&self, e: &io::Error) -> bool {
2028        matches!(
2029            e.kind(),
2030            io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
2031        )
2032    }
2033
2034    /// `true` once the peer has ended the connection with a TLS
2035    /// `close_notify` alert. `false` while it is open, and if the peer, or
2036    /// something on the network path, closed the TCP connection without
2037    /// one: data that ends there may have been cut short. See
2038    /// [`recv`](Self::recv).
2039    pub fn received_close_notify(&self) -> bool {
2040        self.close_notify.get()
2041    }
2042
2043    /// The protocol agreed on through ALPN, if any (for example `http/1.1`).
2044    pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
2045        match &*self.engine.borrow() {
2046            Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
2047            Engine::Kernel(k) => k.negotiated.alpn.clone(),
2048        }
2049    }
2050
2051    /// The certificate chain the peer presented, its own certificate first:
2052    /// the server's on a client connection; on a server connection, the
2053    /// client's if client authentication is configured and the client sent
2054    /// one.
2055    pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
2056        match &*self.engine.borrow() {
2057            Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
2058            Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
2059        }
2060    }
2061
2062    /// `true` if the handshake resumed an earlier session instead of doing a
2063    /// full one.
2064    pub fn resumed(&self) -> bool {
2065        match &*self.engine.borrow() {
2066            Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
2067            Engine::Kernel(k) => k.negotiated.resumed,
2068        }
2069    }
2070
2071    /// The underlying TCP connection, for its addresses and socket options
2072    /// (`peer_addr`, `set_nodelay`, ...).
2073    ///
2074    /// Do not send or receive on it: in the process that corrupts the TLS
2075    /// record stream, and under kernel TLS it bypasses the record limits
2076    /// and the ordering of writes this type keeps.
2077    pub fn tcp(&self) -> &TcpStream {
2078        &self.tcp
2079    }
2080}
2081
2082impl std::fmt::Debug for TlsStream {
2083    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2084        f.debug_struct("TlsStream")
2085            .field("tcp", &self.tcp)
2086            .field("ktls", &self.is_ktls())
2087            .finish_non_exhaustive()
2088    }
2089}
2090
2091#[cfg(test)]
2092mod tests {
2093    use super::*;
2094    use std::future::Future;
2095
2096    #[test]
2097    fn a_connector_without_trusted_authorities_is_refused() {
2098        // The same kind as when the machine has none (`with_system_roots`).
2099        let err = TlsConnector::from_roots(RootCertStore::empty()).unwrap_err();
2100        assert_eq!(err.kind(), io::ErrorKind::NotFound, "{err}");
2101        assert_eq!(
2102            giong::error::code(&err),
2103            Some(Code::NoTrustedRoots),
2104            "{err}"
2105        );
2106    }
2107
2108    fn authority(name: &str) -> (rcgen::Certificate, rcgen::KeyPair) {
2109        let key = rcgen::KeyPair::generate().unwrap();
2110        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2111        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2112        params
2113            .distinguished_name
2114            .push(rcgen::DnType::CommonName, name);
2115        (params.self_signed(&key).unwrap(), key)
2116    }
2117
2118    fn signed_by(
2119        ca: &rcgen::Certificate,
2120        ca_key: &rcgen::KeyPair,
2121        names: &[&str],
2122        expired: bool,
2123    ) -> CertificateDer<'static> {
2124        let key = rcgen::KeyPair::generate().unwrap();
2125        let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
2126        let mut params = rcgen::CertificateParams::new(names).unwrap();
2127        // As MySQL names its own: in the common name only.
2128        params.distinguished_name.push(
2129            rcgen::DnType::CommonName,
2130            "MySQL_Server_8.0.46_Auto_Generated_Server_Certificate",
2131        );
2132        if expired {
2133            params.not_before = rcgen::date_time_ymd(2020, 1, 1);
2134            params.not_after = rcgen::date_time_ymd(2021, 1, 1);
2135        }
2136        let cert = params.signed_by(&key, ca, ca_key).unwrap();
2137        CertificateDer::from(cert.der().to_vec())
2138    }
2139
2140    /// `with_root_pem_any_name` skips the name and nothing else.
2141    #[test]
2142    fn any_name_still_checks_the_chain() {
2143        use rustls::client::danger::ServerCertVerifier;
2144        use rustls::pki_types::UnixTime;
2145        use rustls::CertificateError;
2146
2147        let (ca, ca_key) = authority("ours");
2148        let mut roots = RootCertStore::empty();
2149        roots.add(CertificateDer::from(ca.der().to_vec())).unwrap();
2150        let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
2151            Arc::new(roots),
2152            provider(),
2153        )
2154        .build()
2155        .unwrap();
2156        let verifier = AnyName(webpki);
2157        let name = ServerName::try_from("db.internal").unwrap();
2158        let check = |cert: &CertificateDer<'_>| {
2159            verifier.verify_server_cert(cert, &[], &name, &[], UnixTime::now())
2160        };
2161        // Signed by the authority: accepted, whatever names it has.
2162        for names in [&[][..], &["localhost"], &["db.internal"]] {
2163            check(&signed_by(&ca, &ca_key, names, false)).unwrap();
2164        }
2165        // Expired: refused.
2166        let e = check(&signed_by(&ca, &ca_key, &[], true)).unwrap_err();
2167        assert!(
2168            matches!(
2169                e,
2170                rustls::Error::InvalidCertificate(
2171                    CertificateError::Expired | CertificateError::ExpiredContext { .. }
2172                )
2173            ),
2174            "{e:?}"
2175        );
2176        // Another authority's, or self-signed: refused, even with the
2177        // right name.
2178        let (other, other_key) = authority("theirs");
2179        for cert in [
2180            signed_by(&other, &other_key, &["db.internal"], false),
2181            CertificateDer::from(other.der().to_vec()),
2182        ] {
2183            let e = check(&cert).unwrap_err();
2184            assert!(matches!(e, rustls::Error::InvalidCertificate(_)), "{e:?}");
2185        }
2186        // The authority itself, offered as the server's certificate.
2187        assert!(check(&CertificateDer::from(ca.der().to_vec())).is_err());
2188        // PEM that holds no certificate, or a broken one.
2189        assert!(TlsConnector::with_root_pem_any_name(b"").is_err());
2190        assert!(TlsConnector::with_root_pem_any_name(
2191            b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"
2192        )
2193        .is_err());
2194        assert!(TlsConnector::with_root_pem_any_name(ca.pem().as_bytes()).is_ok());
2195    }
2196
2197    /// The start of a ClientHello record listing `suites`, with a session
2198    /// id of `id_len` bytes, cut after `keep` bytes.
2199    fn client_hello(suites: &[u16], id_len: u8, keep: usize) -> Vec<u8> {
2200        let mut hello = vec![22, 3, 1, 0, 0, 1, 0, 0, 0, 3, 3];
2201        hello.extend_from_slice(&[7; 32]);
2202        hello.push(id_len);
2203        hello.extend(std::iter::repeat(9).take(id_len.into()));
2204        hello.extend_from_slice(&((suites.len() * 2) as u16).to_be_bytes());
2205        for suite in suites {
2206            hello.extend_from_slice(&suite.to_be_bytes());
2207        }
2208        hello.extend_from_slice(&[1, 0]); // no compression
2209        hello.truncate(keep);
2210        hello
2211    }
2212
2213    #[test]
2214    fn chacha20_first_clients_are_told_apart() {
2215        let all = usize::MAX;
2216        // OpenSSL: AES-256-GCM, ChaCha20, AES-128-GCM.
2217        assert!(!prefers_chacha(&client_hello(
2218            &[0x1302, 0x1303, 0x1301],
2219            32,
2220            all
2221        )));
2222        // Browsers: AES-128-GCM first.
2223        assert!(!prefers_chacha(&client_hello(
2224            &[0x1301, 0x1302, 0x1303],
2225            0,
2226            all
2227        )));
2228        // A phone without AES instructions, after a GREASE value.
2229        assert!(prefers_chacha(&client_hello(
2230            &[0x0a0a, 0x1303, 0x1301],
2231            32,
2232            all
2233        )));
2234        // TLS 1.2 only.
2235        assert!(prefers_chacha(&client_hello(&[0xcca9, 0xc02b], 0, all)));
2236        assert!(!prefers_chacha(&client_hello(&[0xc02c, 0xcca9], 0, all)));
2237        // Neither, cut short, or not a ClientHello: the server's order.
2238        assert!(!prefers_chacha(&client_hello(&[0x009c], 0, all)));
2239        let cut = client_hello(&[0x1303, 0x1301], 32, all).len() - 3;
2240        assert!(!prefers_chacha(&client_hello(&[0x1303, 0x1301], 32, cut)));
2241        assert!(!prefers_chacha(&client_hello(&[0x1303], 32, 40)));
2242        assert!(!prefers_chacha(&[]));
2243        let mut alert = client_hello(&[0x1303], 0, all);
2244        alert[0] = 21;
2245        assert!(!prefers_chacha(&alert));
2246    }
2247
2248    fn ca_pem(name: &str) -> String {
2249        let key = rcgen::KeyPair::generate().unwrap();
2250        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2251        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2252        params
2253            .distinguished_name
2254            .push(rcgen::DnType::CommonName, name);
2255        params.self_signed(&key).unwrap().pem()
2256    }
2257
2258    /// A fresh, empty directory under the system's temporary directory.
2259    fn scratch(name: &str) -> PathBuf {
2260        let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
2261        let _ = std::fs::remove_dir_all(&dir);
2262        std::fs::create_dir_all(&dir).unwrap();
2263        dir
2264    }
2265
2266    fn os(path: &Path) -> &OsStr {
2267        path.as_os_str()
2268    }
2269
2270    #[test]
2271    fn server_names_are_dns_names_or_ip_addresses() {
2272        let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
2273        let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
2274        assert!(dns("example.com"));
2275        assert!(dns("db.prod.svc.cluster.local"));
2276        assert!(ip("10.0.0.1"));
2277        assert!(ip("::1"));
2278        assert!(ip("[::1]"));
2279        for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
2280            let err = parse_server_name(bad).unwrap_err();
2281            assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
2282        }
2283    }
2284
2285    #[test]
2286    fn the_first_bundle_that_exists_is_read() {
2287        let dir = scratch("bundle");
2288        let bundle = dir.join("bundle.pem");
2289        let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
2290        std::fs::write(&bundle, two).unwrap();
2291        let missing = dir.join("missing.pem");
2292        let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
2293        let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
2294        assert_eq!(roots.len(), 2);
2295        std::fs::remove_dir_all(dir).unwrap();
2296    }
2297
2298    #[test]
2299    fn ssl_cert_file_and_dir_replace_the_system_locations() {
2300        let dir = scratch("env");
2301        let file = dir.join("file.pem");
2302        std::fs::write(&file, ca_pem("from file")).unwrap();
2303        let certs = dir.join("certs");
2304        std::fs::create_dir(&certs).unwrap();
2305        std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
2306        std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
2307        std::fs::write(certs.join("README"), "not a certificate").unwrap();
2308        // OpenSSL's hashed names are links to the same files.
2309        std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
2310        let system = dir.join("system.pem");
2311        std::fs::write(&system, ca_pem("system")).unwrap();
2312        let bundles = [system.to_str().unwrap()];
2313
2314        let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
2315        assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
2316        let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
2317        assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
2318        let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
2319        let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
2320        assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
2321
2322        let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
2323        assert_eq!(err.kind(), io::ErrorKind::NotFound);
2324        assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
2325        std::fs::remove_dir_all(dir).unwrap();
2326    }
2327
2328    #[test]
2329    fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
2330        let dir = scratch("dir");
2331        std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
2332        let roots = load_roots(
2333            None,
2334            None,
2335            &["/nonexistent/bundle.crt"],
2336            dir.to_str().unwrap(),
2337        );
2338        assert_eq!(roots.unwrap().len(), 1);
2339
2340        let empty = scratch("empty");
2341        let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
2342        assert_eq!(err.kind(), io::ErrorKind::NotFound);
2343        assert!(err.to_string().contains("webpki-roots"), "{err}");
2344        std::fs::remove_dir_all(dir).unwrap();
2345        std::fs::remove_dir_all(empty).unwrap();
2346    }
2347
2348    #[test]
2349    fn records_are_scanned_for_application_data() {
2350        // Header: type, version, length; then that many bytes.
2351        let record = |typ: u8, len: u16| {
2352            let mut r = vec![typ, 3, 3];
2353            r.extend_from_slice(&len.to_be_bytes());
2354            r.resize(5 + len as usize, 0xAA);
2355            r
2356        };
2357        assert!(!has_application_data(&[]));
2358        assert!(!has_application_data(&record(21, 26)));
2359        assert!(has_application_data(&record(23, 0)));
2360        let mut alert_then_data = record(21, 26);
2361        alert_then_data.extend(record(23, 300));
2362        assert!(has_application_data(&alert_then_data));
2363        // A data record's body never counts as a header.
2364        let mut alert = record(21, 26);
2365        alert[5] = 23;
2366        assert!(!has_application_data(&alert));
2367    }
2368
2369    #[test]
2370    fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
2371        let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2372        let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
2373        for mode in [Ktls::Off, Ktls::Auto] {
2374            let acceptor = TlsAcceptor::with_certificates(
2375                &Certificates::from_pem(cert.as_bytes(), key.as_bytes()).unwrap(),
2376            )
2377            .unwrap()
2378            .ktls(mode)
2379            .unwrap();
2380            let tries = acceptor.ktls.tries();
2381            assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
2382            let connector = TlsConnector::with_root_pem(cert.as_bytes())
2383                .unwrap()
2384                .ktls(mode)
2385                .unwrap();
2386            let tries = connector.ktls.tries();
2387            assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
2388        }
2389    }
2390
2391    #[test]
2392    fn this_machines_roots_load() {
2393        // Every machine the tests run on (CI included) has a CA bundle.
2394        TlsConnector::with_system_roots().unwrap();
2395    }
2396
2397    #[cfg(feature = "webpki-roots")]
2398    #[test]
2399    fn mozillas_roots_are_compiled_in() {
2400        TlsConnector::with_webpki_roots();
2401    }
2402
2403    #[test]
2404    fn records_a_receive_could_not_send_whole_go_out_first_and_in_order() {
2405        // The socket takes one byte per attempt, so the session tickets a
2406        // TLS 1.3 server owes after its handshake leave in pieces, each sent
2407        // by a receive that is then dropped. The write that follows has to
2408        // send the rest of them before its own record; a byte lost, repeated
2409        // or out of place fails the client's decryption.
2410        let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2411        let cert = key.cert.pem();
2412        let acceptor = TlsAcceptor::with_certificates(
2413            &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2414                .unwrap(),
2415        )
2416        .unwrap();
2417        let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2418        giong::block_on(async move {
2419            let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2420            let addr = listener.local_addr().unwrap();
2421            let server = giong::spawn(async move {
2422                let tcp = listener.accept().await.unwrap();
2423                let tls = acceptor.accept(tcp).await.unwrap();
2424                assert!(tls.conn().wants_write(), "tickets wait for the first send");
2425                FLUSH_ROOM.set(1);
2426                let mut left = None;
2427                for _ in 0..5 {
2428                    let mut recv = std::pin::pin!(tls.recv());
2429                    let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2430                    assert!(!ready);
2431                    let unsent = tls.unsent.borrow().len();
2432                    assert!(
2433                        left.map_or(unsent > 0, |l| unsent + 1 == l),
2434                        "{left:?} {unsent}"
2435                    );
2436                    left = Some(unsent);
2437                }
2438                FLUSH_ROOM.set(usize::MAX);
2439                tls.write_all(&b"after the tickets"[..]).await.0.unwrap();
2440                // Sent, and the buffer given back: an idle connection keeps
2441                // none for this.
2442                assert_eq!(tls.unsent.borrow().capacity(), 0);
2443                tls.shutdown().await.unwrap();
2444            });
2445            let tcp = TcpStream::connect(addr).await.unwrap();
2446            let tls = connector.connect("localhost", tcp).await.unwrap();
2447            let mut got = Vec::new();
2448            loop {
2449                let data = tls.recv().await.unwrap();
2450                if data.is_empty() {
2451                    break;
2452                }
2453                got.extend_from_slice(&data);
2454            }
2455            assert_eq!(got, b"after the tickets");
2456            assert!(tls.received_close_notify());
2457            server.await.unwrap();
2458        });
2459    }
2460
2461    #[test]
2462    fn a_receive_that_sent_what_was_owed_keeps_no_buffer_for_it() {
2463        // A TLS 1.3 server's first receive sends its session tickets. The
2464        // buffer they pass through is given back once they are sent: 2,000
2465        // idle connections held about 200 bytes each when it was kept.
2466        let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2467        let cert = key.cert.pem();
2468        let acceptor = TlsAcceptor::with_certificates(
2469            &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2470                .unwrap(),
2471        )
2472        .unwrap();
2473        let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2474        giong::block_on(async move {
2475            let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2476            let addr = listener.local_addr().unwrap();
2477            let server = giong::spawn(async move {
2478                let tcp = listener.accept().await.unwrap();
2479                let tls = acceptor.accept(tcp).await.unwrap();
2480                assert!(tls.conn().wants_write(), "tickets wait for the first send");
2481                // The client sends nothing, so this receive has to wait,
2482                // and sends them first.
2483                let mut recv = std::pin::pin!(tls.recv());
2484                let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2485                assert!(!ready);
2486                assert!(!tls.conn().wants_write());
2487                assert_eq!(tls.unsent.borrow().capacity(), 0);
2488                tls.shutdown().await.unwrap();
2489            });
2490            let tcp = TcpStream::connect(addr).await.unwrap();
2491            let tls = connector.connect("localhost", tcp).await.unwrap();
2492            assert!(tls.recv().await.unwrap().is_empty());
2493            assert!(tls.received_close_notify());
2494            server.await.unwrap();
2495        });
2496    }
2497
2498    #[test]
2499    fn the_key_exchange_offers_post_quantum_first_with_the_feature() {
2500        let first = provider().kx_groups[0].name();
2501        let pq = rustls::NamedGroup::X25519MLKEM768;
2502        assert_eq!(first == pq, cfg!(feature = "post-quantum"), "{first:?}");
2503        assert_eq!(provider_aes128_first().kx_groups[0].name(), first);
2504    }
2505}