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