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