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::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::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 ktls;
82
83pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
84
85/// Entry points for the fuzz targets in `giong-tls/fuzz`. Only built by
86/// `cargo fuzz` (`--cfg fuzzing`); not part of the API.
87#[cfg(fuzzing)]
88#[doc(hidden)]
89pub mod fuzzing {
90    pub use crate::ktls::{check_handshake_messages, check_record_framing};
91}
92
93use std::cell::{Cell, RefCell, RefMut};
94use std::collections::HashSet;
95use std::ffi::OsStr;
96use std::future::poll_fn;
97use std::io::{self, Read, Write};
98use std::mem;
99use std::net::Shutdown;
100use std::path::{Path, PathBuf};
101use std::sync::Arc;
102use std::task::{Poll, Waker};
103use std::time::Duration;
104
105use giong::error::Code;
106use giong::net::TcpStream;
107use giong::time::timeout;
108use rustls::client::ResolvesClientCert;
109use rustls::pki_types::pem::PemObject;
110use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
111use rustls::sign::CertifiedKey;
112use rustls::{
113    ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
114    SignatureScheme,
115};
116
117pub use rustls;
118
119fn coded(
120    code: Code,
121    message: impl Into<std::borrow::Cow<'static, str>>,
122    fix: &'static str,
123) -> io::Error {
124    giong::error::Error::new(code, message, fix).into()
125}
126
127/// `send_file` was asked for bytes past the end of the file; it stopped at
128/// `at`.
129fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
130    let end = offset.saturating_add(len);
131    coded(
132        Code::FileTooShort,
133        format!(
134            "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
135            end - at
136        ),
137        "take the length from the open file (File::len), and replace a file that is being \
138         served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
139         than announced, so close the connection.",
140    )
141}
142
143/// PEM data or a certificate file that cannot be used.
144fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
145    coded(
146        Code::BadCertificateData,
147        e.to_string(),
148        "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
149         at least one certificate.",
150    )
151}
152
153/// A private key that cannot be read.
154fn bad_key(e: impl std::fmt::Display) -> io::Error {
155    coded(
156        Code::BadCertificateData,
157        format!("cannot read the private key: {e}"),
158        "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
159         EC forms).",
160    )
161}
162
163/// A certificate and a key that cannot be used together.
164fn mismatched_key(e: rustls::Error) -> io::Error {
165    coded(
166        Code::BadCertificateData,
167        format!("the certificate and the private key cannot be used together: {e}"),
168        "check that the key belongs to the first certificate of the chain, and that its type \
169         (RSA, ECDSA, Ed25519) is supported.",
170    )
171}
172
173/// What rustls reported, with the code that says what to do about it.
174fn tls_error(e: rustls::Error) -> io::Error {
175    match e {
176        rustls::Error::InvalidCertificate(_) => coded(
177            Code::TlsCertificate,
178            format!("the peer's certificate was rejected: {e}"),
179            "check the name you connect to, the certificate's expiry and its chain; a \
180             private authority has to be trusted with TlsConnector::with_roots.",
181        ),
182        e => coded(
183            Code::TlsProtocol,
184            format!("TLS error: {e}"),
185            "check that the other side speaks TLS on this port, and that both sides share a \
186             protocol version and cipher suite.",
187        ),
188    }
189}
190
191/// How long a handshake may take unless configured otherwise.
192const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
193
194fn handshake_timed_out(limit: Duration) -> io::Error {
195    coded(
196        Code::TlsHandshakeTimeout,
197        format!("the TLS handshake did not finish within {limit:?}"),
198        "check that the other side speaks TLS on this port and is not overloaded, or raise \
199         handshake_timeout.",
200    )
201}
202
203fn handshake_eof() -> io::Error {
204    coded(
205        Code::TlsHandshakeEof,
206        "the peer closed the connection during the TLS handshake",
207        "check that the other side speaks TLS on this port, and whether it wants a client \
208         certificate or another server name.",
209    )
210}
211
212/// Most capacity the scratch buffer for outgoing records keeps between
213/// writes. rustls hands over up to 64 KiB of records per call; a buffer that
214/// grew to that is dropped after the write instead of being kept for the
215/// connection's whole life (about 64 KiB per idle connection otherwise).
216const WIRE_KEPT: usize = 16 * 1024;
217
218/// `true` if `records`, whole TLS records as rustls writes them, hold one
219/// of application data (content type 23; under TLS 1.3 every encrypted
220/// record says so).
221fn has_application_data(records: &[u8]) -> bool {
222    let mut at = 0;
223    while let Some(header) = records.get(at..at + 5) {
224        if header[0] == 23 {
225            return true;
226        }
227        at += 5 + usize::from(u16::from_be_bytes([header[3], header[4]]));
228    }
229    false
230}
231
232/// The error a send fails with once the sending direction has ended for
233/// `code`'s reason.
234fn sending_closed(code: Code) -> io::Error {
235    match code {
236        Code::TlsKeysExhausted => coded(
237            Code::TlsKeysExhausted,
238            "this connection has sent as many TLS records as its cipher allows under one key, \
239             and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
240             close_notify was sent",
241            "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
242             kernel TLS on Linux 6.14 or newer).",
243        ),
244        _ => coded(
245            Code::TlsBroken,
246            "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
247            "open a new connection.",
248        ),
249    }
250}
251
252fn broken() -> io::Error {
253    coded(
254        Code::TlsBroken,
255        "a TLS write failed or was cancelled; nothing more can be sent",
256        "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
257         leaves a partial record or message behind, so the stream cannot go on.",
258    )
259}
260
261/// Every certificate in `pem`, or an error if there is none.
262fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
263    let certs = CertificateDer::pem_slice_iter(pem)
264        .collect::<Result<Vec<_>, _>>()
265        .map_err(bad_certificate_data)?;
266    if certs.is_empty() {
267        return Err(bad_certificate_data("no certificate found in the PEM data"));
268    }
269    Ok(certs)
270}
271
272fn ring() -> Arc<rustls::crypto::CryptoProvider> {
273    Arc::new(rustls::crypto::ring::default_provider())
274}
275
276/// Turns accepted TCP connections into TLS connections.
277///
278/// Cheap to clone; share one between all workers.
279#[derive(Clone)]
280pub struct TlsAcceptor {
281    config: Arc<ServerConfig>,
282    handshake_timeout: Duration,
283    ktls: ktls::Plan,
284}
285
286impl TlsAcceptor {
287    /// An acceptor using an existing rustls configuration.
288    pub fn new(config: Arc<ServerConfig>) -> Self {
289        Self {
290            config,
291            handshake_timeout: HANDSHAKE_TIMEOUT,
292            ktls: ktls::Plan::Off,
293        }
294    }
295
296    /// An acceptor for one certificate chain and its private key, both in PEM
297    /// format. TLS 1.2 and 1.3 with rustls' default cipher suites, no client
298    /// authentication, and no protocol offered through ALPN: set them with
299    /// [`alpn`](Self::alpn). (giong-http's `Server::serve_tls` sets its own.)
300    pub fn from_pem(cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
301        let certs = pem_certs(cert_chain)?;
302        let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
303        let config = ServerConfig::builder_with_provider(ring())
304            .with_safe_default_protocol_versions()
305            .map_err(tls_error)?
306            .with_no_client_auth()
307            .with_single_cert(certs, key)
308            .map_err(mismatched_key)?;
309        Ok(Self::new(Arc::new(config)))
310    }
311
312    /// The protocols to accept through ALPN, most preferred first, for
313    /// example `&[b"h2", b"http/1.1"]`. A client that offers none of them
314    /// fails the handshake; one that offers no ALPN at all is accepted.
315    /// The protocol agreed on is [`TlsStream::alpn_protocol`].
316    ///
317    /// giong-http's `Server::serve_tls` sets this itself, to the protocols
318    /// the server speaks.
319    pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
320        Arc::make_mut(&mut self.config).alpn_protocols =
321            protocols.iter().map(|p| p.to_vec()).collect();
322        self
323    }
324
325    /// How long a client may take to complete the TLS handshake (default:
326    /// 10 s).
327    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
328        self.handshake_timeout = timeout;
329        self
330    }
331
332    /// Whether connections hand their keys to the kernel after the
333    /// handshake, so that the kernel encrypts and decrypts (kernel TLS).
334    /// [`Ktls::Off`] by default. See [`Ktls`] for what each mode does, and
335    /// the crate README for when it pays off.
336    ///
337    /// Decided here, once: the running kernel is probed (see
338    /// [`ktls_support`]) and checked against every cipher suite the
339    /// configuration allows. [`Ktls::Required`] fails here with `GIONG-E2009`
340    /// if the kernel cannot take them; [`Ktls::Auto`] then leaves every
341    /// connection in the process instead. A configuration that allows 0-RTT
342    /// data (`max_early_data_size` above 0) cannot use kTLS.
343    ///
344    /// Turns on rustls' `enable_secret_extraction`, which kTLS needs, in this
345    /// acceptor's copy of the configuration, when connections will try the
346    /// kernel (not when `Auto` finds the kernel unable).
347    ///
348    /// ```no_run
349    /// use giong_tls::{Ktls, TlsAcceptor};
350    ///
351    /// # fn main() -> std::io::Result<()> {
352    /// let acceptor = TlsAcceptor::from_pem(&std::fs::read("cert.pem")?, &std::fs::read("key.pem")?)?
353    ///     .ktls(Ktls::Auto)?;
354    /// # Ok(())
355    /// # }
356    /// ```
357    pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
358        let early_data = self.config.max_early_data_size > 0;
359        self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
360        // Extractable secrets only where they will be handed to the kernel.
361        let extract = self.ktls.tries();
362        if self.config.enable_secret_extraction != extract {
363            Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
364        }
365        Ok(self)
366    }
367
368    /// Why connections stay in the process although [`Ktls::Auto`] asked for
369    /// kernel TLS, if they all do: the kernel has no `tls` module, lacks a
370    /// cipher suite the configuration allows, or cannot change TLS 1.3 keys.
371    /// `None` otherwise. Worth a line in the log at startup.
372    pub fn ktls_unavailable(&self) -> Option<&str> {
373        self.ktls.unavailable()
374    }
375
376    /// Performs the TLS handshake on an accepted connection.
377    ///
378    /// With kernel TLS (see [`ktls`](Self::ktls)), the keys go to the kernel
379    /// once the handshake is done. Under [`Ktls::Required`], a stream that
380    /// cannot take them fails with `GIONG-E2009` before anything is sent.
381    pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
382        let tcp = match &self.ktls {
383            ktls::Plan::Off => tcp,
384            ktls::Plan::Try { required } => {
385                let start = ktls::Start::Server(self.config.clone());
386                match ktls::handshake(tcp, start, self.handshake_timeout).await? {
387                    ktls::Outcome::Kernel(tls) => return Ok(*tls),
388                    ktls::Outcome::Declined(_, e) if *required => return Err(e),
389                    ktls::Outcome::Declined(tcp, _) => {
390                        self.ktls.stayed();
391                        tcp
392                    }
393                }
394            }
395            ktls::Plan::Unavailable(_) => {
396                self.ktls.stayed();
397                tcp
398            }
399        };
400        let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
401        TlsStream::new(tcp, conn.into())
402            .handshake(self.handshake_timeout)
403            .await
404    }
405}
406
407impl std::fmt::Debug for TlsAcceptor {
408    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409        f.debug_struct("TlsAcceptor")
410            .field("handshake_timeout", &self.handshake_timeout)
411            .field("ktls", &self.ktls)
412            .finish_non_exhaustive()
413    }
414}
415
416/// Opens TLS connections to servers, checking their certificates.
417///
418/// Cheap to clone; share one between all workers. Clones share the session
419/// cache, so reconnecting to a server resumes the earlier session and skips
420/// most of the handshake.
421///
422/// ```no_run
423/// use std::time::Duration;
424/// use giong_tls::TlsConnector;
425///
426/// # fn main() -> std::io::Result<()> {
427/// // A private certificate authority, a client certificate for mutual TLS,
428/// // and HTTP/1.1 through ALPN.
429/// let connector = TlsConnector::with_root_pem(&std::fs::read("ca.pem")?)?
430///     .client_auth(&std::fs::read("client.pem")?, &std::fs::read("client.key")?)?
431///     .alpn(&[b"http/1.1"])
432///     .handshake_timeout(Duration::from_secs(5));
433/// # Ok(())
434/// # }
435/// ```
436#[derive(Clone)]
437pub struct TlsConnector {
438    config: Arc<ClientConfig>,
439    handshake_timeout: Duration,
440    ktls: ktls::Plan,
441}
442
443impl TlsConnector {
444    /// A connector using an existing rustls configuration.
445    pub fn new(config: Arc<ClientConfig>) -> Self {
446        Self {
447            config,
448            handshake_timeout: HANDSHAKE_TIMEOUT,
449            ktls: ktls::Plan::Off,
450        }
451    }
452
453    /// A connector that trusts the given certificate authorities. TLS 1.2
454    /// and 1.3 with rustls' default cipher suites.
455    pub fn with_roots(roots: RootCertStore) -> io::Result<Self> {
456        if roots.is_empty() {
457            return Err(coded(
458                Code::NoTrustedRoots,
459                "no trusted certificate authority given",
460                "pass at least one certificate, or use TlsConnector::with_system_roots.",
461            ));
462        }
463        let config = ClientConfig::builder_with_provider(ring())
464            .with_safe_default_protocol_versions()
465            .map_err(tls_error)?
466            .with_root_certificates(roots)
467            .with_no_client_auth();
468        Ok(Self::new(Arc::new(config)))
469    }
470
471    /// A connector that trusts the certificate authorities in `pem`: a
472    /// private CA, or a server's own self-signed certificate.
473    pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
474        let mut roots = RootCertStore::empty();
475        for cert in pem_certs(pem)? {
476            roots.add(cert).map_err(bad_certificate_data)?;
477        }
478        Self::with_roots(roots)
479    }
480
481    /// A connector that trusts the certificate authorities installed on this
482    /// machine, read once, now.
483    ///
484    /// They are read from the file named by the `SSL_CERT_FILE` environment
485    /// variable and the directories named by `SSL_CERT_DIR` (separated by
486    /// `:`) if either is set, the way OpenSSL does. Otherwise from the first
487    /// bundle found among the places Linux distributions keep it
488    /// (`/etc/ssl/certs/ca-certificates.crt` on Debian, Ubuntu, Alpine and
489    /// Arch, `/etc/pki/tls/certs/ca-bundle.crt` on Fedora and RHEL, and so
490    /// on), or else from the files in `/etc/ssl/certs`.
491    ///
492    /// Fails with [`io::ErrorKind::NotFound`] if there are none, as in a
493    /// container image built `FROM scratch` or without the `ca-certificates`
494    /// package. Install that package, or enable the `webpki-roots` feature and
495    /// use `TlsConnector::with_webpki_roots`.
496    pub fn with_system_roots() -> io::Result<Self> {
497        let file = std::env::var_os("SSL_CERT_FILE");
498        let dirs = std::env::var_os("SSL_CERT_DIR");
499        let roots = load_roots(
500            file.as_deref(),
501            dirs.as_deref(),
502            SYSTEM_CA_BUNDLES,
503            SYSTEM_CA_DIR,
504        )?;
505        Self::with_roots(roots)
506    }
507
508    /// A connector that trusts the certificate authorities in Mozilla's root
509    /// program, compiled into the program by the `webpki-roots` crate. Useful
510    /// where the machine has none installed; they change only when this
511    /// crate's dependency is updated.
512    ///
513    /// Needs the `webpki-roots` feature.
514    #[cfg(feature = "webpki-roots")]
515    pub fn with_webpki_roots() -> Self {
516        let roots = RootCertStore {
517            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
518        };
519        Self::with_roots(roots).expect("the webpki-roots crate provides roots")
520    }
521
522    /// The protocols to offer through ALPN, most preferred first, for example
523    /// `&[b"h2", b"http/1.1"]`. None by default. The one the server picked is
524    /// [`TlsStream::alpn_protocol`].
525    pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
526        Arc::make_mut(&mut self.config).alpn_protocols =
527            protocols.iter().map(|p| p.to_vec()).collect();
528        self
529    }
530
531    /// Presents a client certificate to servers that ask for one (mutual
532    /// TLS): a certificate chain and its private key, both in PEM format.
533    pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
534        let certs = pem_certs(cert_chain)?;
535        let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
536        let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
537            .map_err(mismatched_key)?;
538        Arc::make_mut(&mut self.config).client_auth_cert_resolver =
539            Arc::new(ClientCert(Arc::new(key)));
540        Ok(self)
541    }
542
543    /// How long a server may take to complete the TLS handshake (default:
544    /// 10 s).
545    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
546        self.handshake_timeout = timeout;
547        self
548    }
549
550    /// Whether connections hand their keys to the kernel after the
551    /// handshake, so that the kernel encrypts and decrypts (kernel TLS).
552    /// [`Ktls::Off`] by default; see [`TlsAcceptor::ktls`], which works the
553    /// same way. Session tickets the server sends later still reach the
554    /// session cache, so reconnecting resumes as without kTLS. A
555    /// configuration that allows 0-RTT data (`enable_early_data`) cannot use
556    /// kTLS.
557    ///
558    /// A stream on which [`TcpStream::recv`] was already used, as by a
559    /// protocol that reads a plaintext greeting before TLS starts, cannot
560    /// take kTLS: under [`Ktls::Auto`] it stays in the process, under
561    /// [`Ktls::Required`] it fails with `GIONG-E2009`. Use
562    /// [`TcpStream::read`] for such greetings.
563    pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
564        let early_data = self.config.enable_early_data;
565        self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
566        let extract = self.ktls.tries();
567        if self.config.enable_secret_extraction != extract {
568            Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
569        }
570        Ok(self)
571    }
572
573    /// Why connections stay in the process although [`Ktls::Auto`] asked for
574    /// kernel TLS, if they all do; see [`TlsAcceptor::ktls_unavailable`].
575    pub fn ktls_unavailable(&self) -> Option<&str> {
576        self.ktls.unavailable()
577    }
578
579    /// Performs the TLS handshake on a connection to `server_name`, which the
580    /// server's certificate must be valid for. `server_name` is a DNS name,
581    /// sent to the server through SNI, or an IP address (`[...]` brackets
582    /// around an IPv6 address are allowed), which is not.
583    ///
584    /// A certificate that is not valid for the name, expired, or not issued
585    /// by a trusted authority fails the handshake with
586    /// [`io::ErrorKind::InvalidData`] and a message saying which it was.
587    pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
588        let name = parse_server_name(server_name)?;
589        let tcp = match &self.ktls {
590            ktls::Plan::Off => tcp,
591            ktls::Plan::Try { required } => {
592                let start = ktls::Start::Client(self.config.clone(), name.clone());
593                match ktls::handshake(tcp, start, self.handshake_timeout).await? {
594                    ktls::Outcome::Kernel(tls) => return Ok(*tls),
595                    ktls::Outcome::Declined(_, e) if *required => return Err(e),
596                    ktls::Outcome::Declined(tcp, _) => {
597                        self.ktls.stayed();
598                        tcp
599                    }
600                }
601            }
602            ktls::Plan::Unavailable(_) => {
603                self.ktls.stayed();
604                tcp
605            }
606        };
607        let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
608        TlsStream::new(tcp, conn.into())
609            .handshake(self.handshake_timeout)
610            .await
611    }
612}
613
614impl std::fmt::Debug for TlsConnector {
615    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
616        f.debug_struct("TlsConnector")
617            .field("handshake_timeout", &self.handshake_timeout)
618            .field("ktls", &self.ktls)
619            .finish_non_exhaustive()
620    }
621}
622
623/// The name a client checks the server's certificate against.
624fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
625    let ipv6 = name
626        .strip_prefix('[')
627        .and_then(|n| n.strip_suffix(']'))
628        .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
629    if let Some(ip) = ipv6 {
630        return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
631    }
632    ServerName::try_from(name.to_owned()).map_err(|_| {
633        coded(
634            Code::InvalidServerName,
635            format!("{name:?} is neither a DNS name nor an IP address"),
636            "pass the host name the certificate is for (\"example.com\"), or an IP address, \
637             without a port or a scheme.",
638        )
639    })
640}
641
642/// Always presents the same client certificate.
643#[derive(Debug)]
644struct ClientCert(Arc<CertifiedKey>);
645
646impl ResolvesClientCert for ClientCert {
647    fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
648        Some(self.0.clone())
649    }
650
651    fn has_certs(&self) -> bool {
652        true
653    }
654}
655
656/// Where Linux distributions keep the bundle of trusted CA certificates.
657const SYSTEM_CA_BUNDLES: &[&str] = &[
658    // Debian, Ubuntu, Alpine, Arch, Gentoo
659    "/etc/ssl/certs/ca-certificates.crt",
660    // Fedora, RHEL, CentOS
661    "/etc/pki/tls/certs/ca-bundle.crt",
662    "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
663    // openSUSE, SLES
664    "/etc/ssl/ca-bundle.pem",
665    // Alpine, Void
666    "/etc/ssl/cert.pem",
667];
668
669/// Where they are kept one per file, when there is no bundle.
670const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
671
672/// Reads trusted certificates the way OpenSSL finds them: `file` and `dirs`
673/// (the `SSL_CERT_FILE` and `SSL_CERT_DIR` variables) if either is set,
674/// otherwise the first of `bundles` that exists, otherwise the files in
675/// `dir`. Certificates rustls cannot use are skipped.
676fn load_roots(
677    file: Option<&OsStr>,
678    dirs: Option<&OsStr>,
679    bundles: &[&str],
680    dir: &str,
681) -> io::Result<RootCertStore> {
682    let mut roots = Roots {
683        store: RootCertStore::empty(),
684        seen: HashSet::new(),
685    };
686    if file.is_some() || dirs.is_some() {
687        if let Some(file) = file {
688            roots.add_file(Path::new(file)).map_err(|e| {
689                io::Error::new(
690                    e.kind(),
691                    giong::error::Error::new(
692                        Code::BadCertificateData,
693                        format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
694                        "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
695                         it to use the system's.",
696                    )
697                    .with_source(e),
698                )
699            })?;
700        }
701        for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
702            roots.add_dir(&dir);
703        }
704    } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
705        roots.add_file(bundle)?;
706    } else {
707        roots.add_dir(Path::new(dir));
708    }
709    if roots.store.is_empty() {
710        return Err(coded(
711            Code::NoTrustedRoots,
712            "no trusted CA certificates found on this machine",
713            "install the ca-certificates package, set SSL_CERT_FILE, or use \
714             TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
715        ));
716    }
717    Ok(roots.store)
718}
719
720struct Roots {
721    store: RootCertStore,
722    /// Files already read. The hashed names in certificate directories are
723    /// links to other files there.
724    seen: HashSet<PathBuf>,
725}
726
727impl Roots {
728    fn add_file(&mut self, path: &Path) -> io::Result<()> {
729        let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
730        if !self.seen.insert(real) {
731            return Ok(());
732        }
733        let pem = std::fs::read(path)?;
734        let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
735        self.store.add_parsable_certificates(certs);
736        Ok(())
737    }
738
739    fn add_dir(&mut self, dir: &Path) {
740        let Ok(entries) = std::fs::read_dir(dir) else {
741            return;
742        };
743        let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
744        paths.sort();
745        for path in paths.iter().filter(|p| p.is_file()) {
746            // One unreadable file does not spoil the others.
747            let _ = self.add_file(path);
748        }
749    }
750}
751
752/// A TLS connection over a [`TcpStream`], made by [`TlsAcceptor::accept`] on
753/// the server side or [`TlsConnector::connect`] on the client side.
754pub struct TlsStream {
755    tcp: TcpStream,
756    /// Who encrypts: rustls in the process, or the kernel.
757    engine: RefCell<Engine>,
758    /// Decrypted data not handed out yet.
759    plain: RefCell<Vec<u8>>,
760    /// Scratch buffer for outgoing TLS records, reused between writes while
761    /// it is small (see [`WIRE_KEPT`]).
762    wire: RefCell<Vec<u8>>,
763    /// The peer closed the connection (with or without `close_notify`).
764    eof: Cell<bool>,
765    /// The peer ended its side with a `close_notify` alert, so nothing it
766    /// sent was cut off.
767    close_notify: Cell<bool>,
768    /// A task is writing TLS records to the socket: one `write_all` (or
769    /// vectored write, or file) at a time, so that neither records nor two
770    /// tasks' data interleave. Other tasks wait for it in `waiters`.
771    sending: Cell<bool>,
772    /// A write to the socket failed or was cancelled half way: the record
773    /// stream is cut in the middle and nothing more can be sent.
774    broken: Cell<bool>,
775    /// The sending direction ended cleanly, and why: `TlsBroken` after
776    /// `shutdown` or a fatal alert, `TlsKeysExhausted` when the key may
777    /// encrypt no more records and cannot be changed.
778    closed: Cell<Option<Code>>,
779    /// A receive error held back until the data before it has been handed out.
780    failed: Cell<Option<io::Error>>,
781    /// Tasks waiting for `sending` to clear.
782    waiters: RefCell<Vec<Waker>>,
783}
784
785/// Who encrypts and decrypts a [`TlsStream`].
786// Both variants are large and a stream holds one for its whole life; a box
787// would cost an allocation and a pointer to follow on every call.
788#[allow(clippy::large_enum_variant)]
789enum Engine {
790    /// rustls, in the process.
791    User(Connection),
792    /// The kernel; rustls keeps what it needs for key updates and session
793    /// tickets.
794    Kernel(ktls::Kernel),
795}
796
797/// Held while TLS records are being written to the socket. Dropped without
798/// [`done`](Self::done), as when the future writing is cancelled, it marks
799/// the stream broken.
800struct Sending<'a> {
801    stream: &'a TlsStream,
802    complete: bool,
803}
804
805impl Sending<'_> {
806    /// The records went out whole (or none did).
807    fn done(mut self) {
808        self.complete = true;
809    }
810}
811
812impl Drop for Sending<'_> {
813    fn drop(&mut self) {
814        if !self.complete {
815            self.stream.broken.set(true);
816        }
817        self.stream.sending.set(false);
818        self.stream.wake_waiters();
819    }
820}
821
822impl TlsStream {
823    fn new(tcp: TcpStream, conn: Connection) -> Self {
824        Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
825    }
826
827    /// A stream the kernel encrypts. `plain` is application data that arrived
828    /// with the end of the handshake; `peer_closed` says `close_notify` did
829    /// too.
830    fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
831        Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
832    }
833
834    fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
835        Self {
836            tcp,
837            engine: RefCell::new(engine),
838            plain: RefCell::new(plain),
839            wire: RefCell::new(Vec::new()),
840            eof: Cell::new(peer_closed),
841            close_notify: Cell::new(peer_closed),
842            sending: Cell::new(false),
843            broken: Cell::new(false),
844            closed: Cell::new(None),
845            failed: Cell::new(None),
846            waiters: RefCell::new(Vec::new()),
847        }
848    }
849
850    /// rustls' connection, on a stream rustls encrypts. Never held across
851    /// an `.await`.
852    fn conn(&self) -> RefMut<'_, Connection> {
853        RefMut::map(self.engine.borrow_mut(), |e| match e {
854            Engine::User(c) => c,
855            Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
856        })
857    }
858
859    /// `true` if the kernel encrypts and decrypts this connection (kernel
860    /// TLS, see [`TlsAcceptor::ktls`]); `false` if rustls does, in the
861    /// process.
862    pub fn is_ktls(&self) -> bool {
863        matches!(*self.engine.borrow(), Engine::Kernel(_))
864    }
865
866    /// Waits until no other task is writing records.
867    async fn wait_for_sender(&self) {
868        poll_fn(|cx| {
869            if !self.sending.get() {
870                return Poll::Ready(());
871            }
872            // A task polled again while it waits is listed once.
873            let mut waiters = self.waiters.borrow_mut();
874            if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
875                waiters.push(cx.waker().clone());
876            }
877            Poll::Pending
878        })
879        .await;
880    }
881
882    /// Waits for other writers, then makes this task the one writing records
883    /// until the guard is dropped.
884    async fn lock_send(&self) -> Sending<'_> {
885        while self.sending.get() {
886            self.wait_for_sender().await;
887        }
888        self.sending.set(true);
889        Sending {
890            stream: self,
891            complete: false,
892        }
893    }
894
895    /// Runs the handshake, either side, within `limit`.
896    async fn handshake(self, limit: Duration) -> io::Result<Self> {
897        let handshake = async {
898            while self.conn().is_handshaking() {
899                self.flush_tls().await?;
900                if !self.conn().is_handshaking() {
901                    break;
902                }
903                if self.eof.get() {
904                    return Err(handshake_eof());
905                }
906                self.pump().await?;
907            }
908            self.flush_tls().await
909        };
910        match timeout(limit, handshake).await {
911            Ok(Ok(())) => Ok(self),
912            Ok(Err(e)) => Err(e),
913            Err(_) => Err(handshake_timed_out(limit)),
914        }
915    }
916
917    /// Wakes the tasks waiting for the send lock, or for their records to
918    /// be sent (see [`flush_tls`](Self::flush_tls)).
919    fn wake_waiters(&self) {
920        let waiters = mem::take(&mut *self.waiters.borrow_mut());
921        for waker in waiters {
922            waker.wake();
923        }
924    }
925
926    /// Takes the scratch buffer for outgoing records.
927    fn take_wire(&self) -> Vec<u8> {
928        mem::take(&mut *self.wire.borrow_mut())
929    }
930
931    /// Keeps `wire` for the next write, unless a large write grew it: a
932    /// connection that once sent a large response should not hold that much
933    /// for the rest of its life.
934    fn keep_wire(&self, mut wire: Vec<u8>) {
935        if wire.capacity() <= WIRE_KEPT {
936            wire.clear();
937            *self.wire.borrow_mut() = wire;
938        }
939    }
940
941    /// The error a send fails with before it starts, if the stream cannot
942    /// send any more.
943    fn cannot_send(&self) -> Option<io::Error> {
944        if self.broken.get() {
945            return Some(broken());
946        }
947        self.closed.get().map(sending_closed)
948    }
949
950    /// Sends every TLS record rustls has queued: handshake messages, key
951    /// updates, alerts. A task that is writing sends them with its own data
952    /// (see [`send_plain`](Self::send_plain)); this waits for it.
953    async fn flush_tls(&self) -> io::Result<()> {
954        loop {
955            if !self.conn().wants_write() {
956                return Ok(());
957            }
958            if self.broken.get() {
959                return Err(broken());
960            }
961            if self.sending.get() {
962                // The writer sends these records before its next piece of
963                // data, and wakes us then; or it finishes and frees the lock.
964                self.wait_for_sender().await;
965                continue;
966            }
967            let sending = self.lock_send().await;
968            let mut wire = self.take_wire();
969            let res = self.send_queued(&mut wire).await;
970            self.keep_wire(wire);
971            sending.done();
972            res?;
973        }
974    }
975
976    /// Moves every record rustls has queued into `wire` and sends them. The
977    /// caller holds the send lock.
978    async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
979        loop {
980            {
981                let mut conn = self.conn();
982                if !conn.wants_write() {
983                    return Ok(());
984                }
985                while conn.wants_write() {
986                    conn.write_tls(wire)?;
987                }
988            }
989            self.send_wire(wire).await?;
990        }
991    }
992
993    /// Writes all of `wire` to the socket and empties it, keeping its
994    /// capacity for the rest of this write. A failure may have cut a record
995    /// in two, so it marks the stream broken.
996    async fn send_wire(&self, wire: &mut Vec<u8>) -> io::Result<()> {
997        let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
998        sent.clear();
999        *wire = sent;
1000        if res.is_err() {
1001            self.broken.set(true);
1002        }
1003        res
1004    }
1005
1006    /// Encrypts all of `data` and sends it, in the process. The caller holds
1007    /// the send lock.
1008    ///
1009    /// rustls takes up to its buffer limit (64 KiB) per call. Records a
1010    /// receive queued in the meantime (a key update, an alert) go out first.
1011    async fn send_plain(&self, wire: &mut Vec<u8>, data: &[u8]) -> io::Result<()> {
1012        let mut sent = 0;
1013        while sent < data.len() {
1014            let (carried, refused) = {
1015                let mut conn = self.conn();
1016                while conn.wants_write() {
1017                    conn.write_tls(wire)?;
1018                }
1019                let carried = !wire.is_empty();
1020                let start = wire.len();
1021                let n = conn.writer().write(&data[sent..])?;
1022                while conn.wants_write() {
1023                    conn.write_tls(wire)?;
1024                }
1025                sent += n;
1026                // rustls took the bytes and encrypted none of them: the key
1027                // has encrypted as many records as its cipher allows and,
1028                // on TLS 1.2, cannot be changed. rustls queued close_notify
1029                // instead and drops everything it is given from then on.
1030                (carried, n > 0 && !has_application_data(&wire[start..]))
1031            };
1032            if !wire.is_empty() {
1033                self.send_wire(wire).await?;
1034            }
1035            if carried {
1036                // Receivers waiting in `flush_tls` for these records.
1037                self.wake_waiters();
1038            }
1039            if refused {
1040                self.closed.set(Some(Code::TlsKeysExhausted));
1041                return Err(sending_closed(Code::TlsKeysExhausted));
1042            }
1043        }
1044        Ok(())
1045    }
1046
1047    /// One write in the process: `pieces` encrypted and sent in order,
1048    /// holding the send lock throughout, so that no other task's write comes
1049    /// between them.
1050    async fn write_in_process(&self, pieces: &[&[u8]]) -> io::Result<()> {
1051        let sending = self.lock_send().await;
1052        if let Some(e) = self.cannot_send() {
1053            sending.done();
1054            return Err(e);
1055        }
1056        let mut wire = self.take_wire();
1057        let mut res = Ok(());
1058        for piece in pieces {
1059            res = self.send_plain(&mut wire, piece).await;
1060            if res.is_err() {
1061                break;
1062            }
1063        }
1064        self.keep_wire(wire);
1065        // A failure on the socket has marked the stream broken already; one
1066        // before anything was sent (rustls refusing the data, keys used up,
1067        // a file read) leaves it whole.
1068        sending.done();
1069        res
1070    }
1071
1072    /// Receives one chunk of TLS data, decrypts it into `plain`, and sends
1073    /// whatever the protocol wants to send in response.
1074    async fn pump(&self) -> io::Result<()> {
1075        // Cancelling here loses nothing: `recv` is cancel safe.
1076        let chunk = self.tcp.recv().await?;
1077        if chunk.is_empty() {
1078            self.eof.set(true);
1079            return Ok(());
1080        }
1081        let result = {
1082            let mut conn = self.conn();
1083            let mut plain = self.plain.borrow_mut();
1084            let mut input = &chunk[..];
1085            let mut result = Ok(());
1086            while !input.is_empty() {
1087                // rustls buffers a bounded amount of plaintext, so it has to
1088                // be drained as the records are fed in.
1089                match conn.read_tls(&mut input) {
1090                    Ok(0) => {
1091                        result = Err(coded(
1092                            Code::TlsProtocol,
1093                            "rustls accepted no more TLS data",
1094                            "this is a bug in giong-tls; please report it at \
1095                             https://github.com/giong-run/Giong/issues.",
1096                        ));
1097                        break;
1098                    }
1099                    Ok(_) => {}
1100                    Err(e) => {
1101                        result = Err(e);
1102                        break;
1103                    }
1104                }
1105                match conn.process_new_packets() {
1106                    Ok(state) => {
1107                        let n = state.plaintext_bytes_to_read();
1108                        if n > 0 {
1109                            let at = plain.len();
1110                            plain.resize(at + n, 0);
1111                            if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
1112                                plain.truncate(at);
1113                                result = Err(e);
1114                                break;
1115                            }
1116                        }
1117                        if state.peer_has_closed() {
1118                            self.close_notify.set(true);
1119                            self.eof.set(true);
1120                            break;
1121                        }
1122                    }
1123                    Err(e) => {
1124                        result = Err(tls_error(e));
1125                        break;
1126                    }
1127                }
1128            }
1129            result
1130        };
1131        drop(chunk);
1132        // Handshake messages, key updates, or the alert describing `result`.
1133        // Not being able to send them is no reason to withhold what was
1134        // received, if sending has failed before.
1135        if self.broken.get() {
1136            return result;
1137        }
1138        let flushed = self.flush_tls().await;
1139        result.and(flushed)
1140    }
1141
1142    /// Receives decrypted data. An empty buffer means that the peer has closed
1143    /// the connection, with a `close_notify` alert or by closing the socket.
1144    ///
1145    /// The two are not the same when the end of the stream is what marks
1146    /// the end of the data, as in an HTTP response without a length: only
1147    /// `close_notify` is authenticated, while anyone on the network path can
1148    /// close a TCP connection early and cut the data short (a truncation
1149    /// attack). Check [`received_close_notify`](Self::received_close_notify)
1150    /// before trusting such data to be complete.
1151    ///
1152    /// Cancel safe: dropping the future loses no data. (If it is dropped at
1153    /// the rare moment a TLS protocol message is being sent, sending fails
1154    /// from then on instead of continuing on a broken stream.)
1155    ///
1156    /// One task may receive while others send. Only one task may receive at
1157    /// a time: like [`TcpStream::recv`], the stream wakes only the task that
1158    /// waited last, so a second receiver can wait forever.
1159    pub async fn recv(&self) -> io::Result<Vec<u8>> {
1160        if self.is_ktls() {
1161            return self.kernel_recv().await;
1162        }
1163        loop {
1164            {
1165                let mut plain = self.plain.borrow_mut();
1166                if !plain.is_empty() {
1167                    return Ok(mem::take(&mut *plain));
1168                }
1169            }
1170            if let Some(e) = self.failed.take() {
1171                return Err(e);
1172            }
1173            if self.eof.get() {
1174                return Ok(Vec::new());
1175            }
1176            if let Err(e) = self.pump().await {
1177                // Data that arrived intact before the failure comes first.
1178                if self.plain.borrow().is_empty() {
1179                    return Err(e);
1180                }
1181                self.failed.set(Some(e));
1182            }
1183        }
1184    }
1185
1186    /// Encrypts and sends all of `buf`, then hands the buffer back.
1187    ///
1188    /// Takes any buffer giong can send, as [`TcpStream::write_all`] does:
1189    /// a `Vec<u8>`, a `Box<[u8]>`, an `Rc<[u8]>`, a `&'static [u8]`, ...
1190    ///
1191    /// Each write goes out whole: another task's `write_all`,
1192    /// [`write_all_vectored`](Self::write_all_vectored) or
1193    /// [`send_file`](Self::send_file) on the same stream waits for it, and
1194    /// their data never interleave.
1195    ///
1196    /// Fails with `TlsKeysExhausted` (`GIONG-E2012`) once the connection has
1197    /// sent as many records as its cipher allows under one key and cannot
1198    /// change keys (TLS 1.2 with AES-GCM after 2^24 records: rustls sends
1199    /// `close_notify`, and nothing more can be sent); with `TlsBroken`
1200    /// (`GIONG-E2008`) after [`shutdown`](Self::shutdown) or a failed write.
1201    ///
1202    /// Not cancel safe: if the future is dropped, part of `buf` may have been
1203    /// sent, and if that happened in the middle of a TLS record the
1204    /// connection cannot send any more: later writes return an error, while
1205    /// data the peer already sent can still be received.
1206    pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1207    where
1208        B: giong::IoBuf + AsRef<[u8]>,
1209    {
1210        if self.is_ktls() {
1211            return self.kernel_write_all(buf).await;
1212        }
1213        let res = self.write_in_process(&[buf.as_ref()]).await;
1214        (res, buf)
1215    }
1216
1217    /// Encrypts and sends all of `bufs`, one after the other, without
1218    /// copying them into one buffer first, then hands them back.
1219    ///
1220    /// Use it to send a header and a large body that live in different
1221    /// buffers. In the process, rustls takes the pieces one by one, so a
1222    /// small header goes out in the same write as the start of the body;
1223    /// with kernel TLS they go to the kernel in vectored writes, as with
1224    /// [`TcpStream::write_all_vectored`]. All of them go out as one write,
1225    /// as with [`write_all`](Self::write_all), which also has the errors.
1226    ///
1227    /// Not cancel safe, as [`write_all`](Self::write_all).
1228    pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1229    where
1230        B: giong::IoBuf + AsRef<[u8]>,
1231    {
1232        if self.is_ktls() {
1233            return self.kernel_write_all_vectored(bufs).await;
1234        }
1235        let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1236        let res = self.write_in_process(&pieces).await;
1237        drop(pieces);
1238        (res, bufs)
1239    }
1240
1241    /// Encrypts and sends `len` bytes of `file`, starting at `offset`.
1242    ///
1243    /// With kernel TLS (see [`is_ktls`](Self::is_ktls)) this is
1244    /// [`TcpStream::send_file`]: the kernel encrypts the file straight from
1245    /// its page cache, and the bytes never pass through the program. This is
1246    /// where kernel TLS is faster than encrypting in the process. Without
1247    /// it, the file is read in pieces of up to 256 KiB and encrypted by
1248    /// rustls. Either way, the file's own position is neither used nor
1249    /// moved.
1250    ///
1251    /// Fails with `FileTooShort` (`GIONG-E0201`) if the file ends before
1252    /// `offset + len`, after sending what it had; the stream can still send.
1253    /// The notes of [`TcpStream::send_file`] on cold files apply to kernel
1254    /// TLS.
1255    ///
1256    /// Not cancel safe, as [`write_all`](Self::write_all).
1257    pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1258        if offset
1259            .checked_add(len)
1260            .map_or(true, |end| end > i64::MAX as u64)
1261        {
1262            return Err(file_too_short(offset, len, offset));
1263        }
1264        if self.is_ktls() {
1265            return self.kernel_send_file(file, offset, len).await;
1266        }
1267        let sending = self.lock_send().await;
1268        if let Some(e) = self.cannot_send() {
1269            sending.done();
1270            return Err(e);
1271        }
1272        let mut wire = self.take_wire();
1273        let res = self
1274            .send_file_in_process(&mut wire, file, offset, len)
1275            .await;
1276        self.keep_wire(wire);
1277        sending.done();
1278        res
1279    }
1280
1281    /// `send_file` in the process: read and encrypt the file in pieces. The
1282    /// caller holds the send lock.
1283    async fn send_file_in_process(
1284        &self,
1285        wire: &mut Vec<u8>,
1286        file: &giong::fs::File,
1287        offset: u64,
1288        len: u64,
1289    ) -> io::Result<()> {
1290        const PIECE: u64 = 256 * 1024;
1291        let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1292        let (mut at, mut left) = (offset, len);
1293        while left > 0 {
1294            let (res, b) = file.read_at(buf, at).await;
1295            buf = b;
1296            let n = match res {
1297                Ok(0) => return Err(file_too_short(offset, len, at)),
1298                Ok(n) => (n as u64).min(left) as usize,
1299                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1300                Err(e) => return Err(e),
1301            };
1302            self.send_plain(wire, &buf[..n]).await?;
1303            at += n as u64;
1304            left -= n as u64;
1305        }
1306        Ok(())
1307    }
1308
1309    /// Sends the TLS `close_notify` alert and closes the sending direction.
1310    ///
1311    /// Waits for a write in progress. After that, writes fail with
1312    /// `TlsBroken` (`GIONG-E2008`). On a stream that can no longer send (a
1313    /// failed or cancelled write, keys used up, a second `shutdown`), only
1314    /// the TCP sending direction is closed, with no alert.
1315    pub async fn shutdown(&self) -> io::Result<()> {
1316        if self.is_ktls() {
1317            return self.kernel_shutdown().await;
1318        }
1319        let sending = self.lock_send().await;
1320        if self.cannot_send().is_none() {
1321            self.conn().send_close_notify();
1322            self.closed.set(Some(Code::TlsBroken));
1323            let mut wire = self.take_wire();
1324            let res = self.send_queued(&mut wire).await;
1325            self.keep_wire(wire);
1326            if let Err(e) = res {
1327                // Close the TCP side anyway, so the peer is not left waiting.
1328                sending.done();
1329                let _ = self.tcp.shutdown(Shutdown::Write);
1330                return Err(e);
1331            }
1332        }
1333        sending.done();
1334        self.tcp.shutdown(Shutdown::Write)
1335    }
1336
1337    /// `true` once the peer has ended the connection with a TLS
1338    /// `close_notify` alert. `false` while it is open, and if the peer, or
1339    /// something on the network path, closed the TCP connection without
1340    /// one: data that ends there may have been cut short. See
1341    /// [`recv`](Self::recv).
1342    pub fn received_close_notify(&self) -> bool {
1343        self.close_notify.get()
1344    }
1345
1346    /// The protocol agreed on through ALPN, if any (for example `http/1.1`).
1347    pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
1348        match &*self.engine.borrow() {
1349            Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
1350            Engine::Kernel(k) => k.negotiated.alpn.clone(),
1351        }
1352    }
1353
1354    /// The certificate chain the peer presented, its own certificate first:
1355    /// the server's on a client connection; on a server connection, the
1356    /// client's if client authentication is configured and the client sent
1357    /// one.
1358    pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
1359        match &*self.engine.borrow() {
1360            Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
1361            Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
1362        }
1363    }
1364
1365    /// `true` if the handshake resumed an earlier session instead of doing a
1366    /// full one.
1367    pub fn resumed(&self) -> bool {
1368        match &*self.engine.borrow() {
1369            Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
1370            Engine::Kernel(k) => k.negotiated.resumed,
1371        }
1372    }
1373
1374    /// The underlying TCP connection, for its addresses and socket options
1375    /// (`peer_addr`, `set_nodelay`, ...).
1376    ///
1377    /// Do not send or receive on it: in the process that corrupts the TLS
1378    /// record stream, and under kernel TLS it bypasses the record limits
1379    /// and the ordering of writes this type keeps.
1380    pub fn tcp(&self) -> &TcpStream {
1381        &self.tcp
1382    }
1383}
1384
1385impl std::fmt::Debug for TlsStream {
1386    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1387        f.debug_struct("TlsStream")
1388            .field("tcp", &self.tcp)
1389            .field("ktls", &self.is_ktls())
1390            .finish_non_exhaustive()
1391    }
1392}
1393
1394#[cfg(test)]
1395mod tests {
1396    use super::*;
1397
1398    fn ca_pem(name: &str) -> String {
1399        let key = rcgen::KeyPair::generate().unwrap();
1400        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1401        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1402        params
1403            .distinguished_name
1404            .push(rcgen::DnType::CommonName, name);
1405        params.self_signed(&key).unwrap().pem()
1406    }
1407
1408    /// A fresh, empty directory under the system's temporary directory.
1409    fn scratch(name: &str) -> PathBuf {
1410        let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
1411        let _ = std::fs::remove_dir_all(&dir);
1412        std::fs::create_dir_all(&dir).unwrap();
1413        dir
1414    }
1415
1416    fn os(path: &Path) -> &OsStr {
1417        path.as_os_str()
1418    }
1419
1420    #[test]
1421    fn server_names_are_dns_names_or_ip_addresses() {
1422        let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
1423        let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
1424        assert!(dns("example.com"));
1425        assert!(dns("db.prod.svc.cluster.local"));
1426        assert!(ip("10.0.0.1"));
1427        assert!(ip("::1"));
1428        assert!(ip("[::1]"));
1429        for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
1430            let err = parse_server_name(bad).unwrap_err();
1431            assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
1432        }
1433    }
1434
1435    #[test]
1436    fn the_first_bundle_that_exists_is_read() {
1437        let dir = scratch("bundle");
1438        let bundle = dir.join("bundle.pem");
1439        let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
1440        std::fs::write(&bundle, two).unwrap();
1441        let missing = dir.join("missing.pem");
1442        let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
1443        let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
1444        assert_eq!(roots.len(), 2);
1445        std::fs::remove_dir_all(dir).unwrap();
1446    }
1447
1448    #[test]
1449    fn ssl_cert_file_and_dir_replace_the_system_locations() {
1450        let dir = scratch("env");
1451        let file = dir.join("file.pem");
1452        std::fs::write(&file, ca_pem("from file")).unwrap();
1453        let certs = dir.join("certs");
1454        std::fs::create_dir(&certs).unwrap();
1455        std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
1456        std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
1457        std::fs::write(certs.join("README"), "not a certificate").unwrap();
1458        // OpenSSL's hashed names are links to the same files.
1459        std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
1460        let system = dir.join("system.pem");
1461        std::fs::write(&system, ca_pem("system")).unwrap();
1462        let bundles = [system.to_str().unwrap()];
1463
1464        let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
1465        assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
1466        let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
1467        assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
1468        let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
1469        let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
1470        assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
1471
1472        let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
1473        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1474        assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
1475        std::fs::remove_dir_all(dir).unwrap();
1476    }
1477
1478    #[test]
1479    fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
1480        let dir = scratch("dir");
1481        std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
1482        let roots = load_roots(
1483            None,
1484            None,
1485            &["/nonexistent/bundle.crt"],
1486            dir.to_str().unwrap(),
1487        );
1488        assert_eq!(roots.unwrap().len(), 1);
1489
1490        let empty = scratch("empty");
1491        let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
1492        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1493        assert!(err.to_string().contains("webpki-roots"), "{err}");
1494        std::fs::remove_dir_all(dir).unwrap();
1495        std::fs::remove_dir_all(empty).unwrap();
1496    }
1497
1498    #[test]
1499    fn records_are_scanned_for_application_data() {
1500        // Header: type, version, length; then that many bytes.
1501        let record = |typ: u8, len: u16| {
1502            let mut r = vec![typ, 3, 3];
1503            r.extend_from_slice(&len.to_be_bytes());
1504            r.resize(5 + len as usize, 0xAA);
1505            r
1506        };
1507        assert!(!has_application_data(&[]));
1508        assert!(!has_application_data(&record(21, 26)));
1509        assert!(has_application_data(&record(23, 0)));
1510        let mut alert_then_data = record(21, 26);
1511        alert_then_data.extend(record(23, 300));
1512        assert!(has_application_data(&alert_then_data));
1513        // A data record's body never counts as a header.
1514        let mut alert = record(21, 26);
1515        alert[5] = 23;
1516        assert!(!has_application_data(&alert));
1517    }
1518
1519    #[test]
1520    fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
1521        let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
1522        let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
1523        for mode in [Ktls::Off, Ktls::Auto] {
1524            let acceptor = TlsAcceptor::from_pem(cert.as_bytes(), key.as_bytes())
1525                .unwrap()
1526                .ktls(mode)
1527                .unwrap();
1528            let tries = acceptor.ktls.tries();
1529            assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
1530            let connector = TlsConnector::with_root_pem(cert.as_bytes())
1531                .unwrap()
1532                .ktls(mode)
1533                .unwrap();
1534            let tries = connector.ktls.tries();
1535            assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
1536        }
1537    }
1538
1539    #[test]
1540    fn this_machines_roots_load() {
1541        // Every machine the tests run on (CI included) has a CA bundle.
1542        TlsConnector::with_system_roots().unwrap();
1543    }
1544
1545    #[cfg(feature = "webpki-roots")]
1546    #[test]
1547    fn mozillas_roots_are_compiled_in() {
1548        TlsConnector::with_webpki_roots();
1549    }
1550}