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