Skip to main content

giong_tls/
lib.rs

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