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