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#![warn(missing_docs)]
71
72use std::cell::{Cell, RefCell};
73use std::collections::HashSet;
74use std::ffi::OsStr;
75use std::future::poll_fn;
76use std::io::{self, Read, Write};
77use std::mem;
78use std::net::Shutdown;
79use std::path::{Path, PathBuf};
80use std::sync::Arc;
81use std::task::{Poll, Waker};
82use std::time::Duration;
83
84use giong::error::Code;
85use giong::net::TcpStream;
86use giong::time::timeout;
87use rustls::client::ResolvesClientCert;
88use rustls::pki_types::pem::PemObject;
89use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
90use rustls::sign::CertifiedKey;
91use rustls::{
92    ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
93    SignatureScheme,
94};
95
96pub use rustls;
97
98fn coded(
99    code: Code,
100    message: impl Into<std::borrow::Cow<'static, str>>,
101    fix: &'static str,
102) -> io::Error {
103    giong::error::Error::new(code, message, fix).into()
104}
105
106/// PEM data or a certificate file that cannot be used.
107fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
108    coded(
109        Code::BadCertificateData,
110        e.to_string(),
111        "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
112         at least one certificate.",
113    )
114}
115
116/// A private key that cannot be read.
117fn bad_key(e: impl std::fmt::Display) -> io::Error {
118    coded(
119        Code::BadCertificateData,
120        format!("cannot read the private key: {e}"),
121        "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
122         EC forms).",
123    )
124}
125
126/// A certificate and a key that cannot be used together.
127fn mismatched_key(e: rustls::Error) -> io::Error {
128    coded(
129        Code::BadCertificateData,
130        format!("the certificate and the private key cannot be used together: {e}"),
131        "check that the key belongs to the first certificate of the chain, and that its type \
132         (RSA, ECDSA, Ed25519) is supported.",
133    )
134}
135
136/// What rustls reported, with the code that says what to do about it.
137fn tls_error(e: rustls::Error) -> io::Error {
138    match e {
139        rustls::Error::InvalidCertificate(_) => coded(
140            Code::TlsCertificate,
141            format!("the peer's certificate was rejected: {e}"),
142            "check the name you connect to, the certificate's expiry and its chain; a \
143             private authority has to be trusted with TlsConnector::with_roots.",
144        ),
145        e => coded(
146            Code::TlsProtocol,
147            format!("TLS error: {e}"),
148            "check that the other side speaks TLS on this port, and that both sides share a \
149             protocol version and cipher suite.",
150        ),
151    }
152}
153
154/// How long a handshake may take unless configured otherwise.
155const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
156
157/// Every certificate in `pem`, or an error if there is none.
158fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
159    let certs = CertificateDer::pem_slice_iter(pem)
160        .collect::<Result<Vec<_>, _>>()
161        .map_err(bad_certificate_data)?;
162    if certs.is_empty() {
163        return Err(bad_certificate_data("no certificate found in the PEM data"));
164    }
165    Ok(certs)
166}
167
168fn ring() -> Arc<rustls::crypto::CryptoProvider> {
169    Arc::new(rustls::crypto::ring::default_provider())
170}
171
172/// Turns accepted TCP connections into TLS connections.
173///
174/// Cheap to clone; share one between all workers.
175#[derive(Clone)]
176pub struct TlsAcceptor {
177    config: Arc<ServerConfig>,
178    handshake_timeout: Duration,
179}
180
181impl TlsAcceptor {
182    /// An acceptor using an existing rustls configuration.
183    pub fn new(config: Arc<ServerConfig>) -> Self {
184        Self {
185            config,
186            handshake_timeout: HANDSHAKE_TIMEOUT,
187        }
188    }
189
190    /// An acceptor for one certificate chain and its private key, both in PEM
191    /// format. TLS 1.2 and 1.3 with rustls' default cipher suites, no client
192    /// authentication, and `http/1.1` offered through ALPN.
193    pub fn from_pem(cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
194        let certs = pem_certs(cert_chain)?;
195        let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
196        let mut config = ServerConfig::builder_with_provider(ring())
197            .with_safe_default_protocol_versions()
198            .map_err(tls_error)?
199            .with_no_client_auth()
200            .with_single_cert(certs, key)
201            .map_err(mismatched_key)?;
202        config.alpn_protocols = vec![b"http/1.1".to_vec()];
203        Ok(Self::new(Arc::new(config)))
204    }
205
206    /// How long a client may take to complete the TLS handshake (default:
207    /// 10 s).
208    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
209        self.handshake_timeout = timeout;
210        self
211    }
212
213    /// Performs the TLS handshake on an accepted connection.
214    pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
215        let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
216        TlsStream::new(tcp, conn.into())
217            .handshake(self.handshake_timeout)
218            .await
219    }
220}
221
222impl std::fmt::Debug for TlsAcceptor {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        f.debug_struct("TlsAcceptor")
225            .field("handshake_timeout", &self.handshake_timeout)
226            .finish_non_exhaustive()
227    }
228}
229
230/// Opens TLS connections to servers, checking their certificates.
231///
232/// Cheap to clone; share one between all workers. Clones share the session
233/// cache, so reconnecting to a server resumes the earlier session and skips
234/// most of the handshake.
235///
236/// ```no_run
237/// use std::time::Duration;
238/// use giong_tls::TlsConnector;
239///
240/// # fn main() -> std::io::Result<()> {
241/// // A private certificate authority, a client certificate for mutual TLS,
242/// // and HTTP/1.1 through ALPN.
243/// let connector = TlsConnector::with_root_pem(&std::fs::read("ca.pem")?)?
244///     .client_auth(&std::fs::read("client.pem")?, &std::fs::read("client.key")?)?
245///     .alpn(&[b"http/1.1"])
246///     .handshake_timeout(Duration::from_secs(5));
247/// # Ok(())
248/// # }
249/// ```
250#[derive(Clone)]
251pub struct TlsConnector {
252    config: Arc<ClientConfig>,
253    handshake_timeout: Duration,
254}
255
256impl TlsConnector {
257    /// A connector using an existing rustls configuration.
258    pub fn new(config: Arc<ClientConfig>) -> Self {
259        Self {
260            config,
261            handshake_timeout: HANDSHAKE_TIMEOUT,
262        }
263    }
264
265    /// A connector that trusts the given certificate authorities. TLS 1.2
266    /// and 1.3 with rustls' default cipher suites.
267    pub fn with_roots(roots: RootCertStore) -> io::Result<Self> {
268        if roots.is_empty() {
269            return Err(io::Error::new(
270                io::ErrorKind::InvalidData,
271                giong::error::Error::new(
272                    Code::NoTrustedRoots,
273                    "no trusted certificate authority given",
274                    "pass at least one certificate, or use TlsConnector::with_system_roots.",
275                ),
276            ));
277        }
278        let config = ClientConfig::builder_with_provider(ring())
279            .with_safe_default_protocol_versions()
280            .map_err(tls_error)?
281            .with_root_certificates(roots)
282            .with_no_client_auth();
283        Ok(Self::new(Arc::new(config)))
284    }
285
286    /// A connector that trusts the certificate authorities in `pem`: a
287    /// private CA, or a server's own self-signed certificate.
288    pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
289        let mut roots = RootCertStore::empty();
290        for cert in pem_certs(pem)? {
291            roots.add(cert).map_err(bad_certificate_data)?;
292        }
293        Self::with_roots(roots)
294    }
295
296    /// A connector that trusts the certificate authorities installed on this
297    /// machine, read once, now.
298    ///
299    /// They are read from the file named by the `SSL_CERT_FILE` environment
300    /// variable and the directories named by `SSL_CERT_DIR` (separated by
301    /// `:`) if either is set, the way OpenSSL does. Otherwise from the first
302    /// bundle found among the places Linux distributions keep it
303    /// (`/etc/ssl/certs/ca-certificates.crt` on Debian, Ubuntu, Alpine and
304    /// Arch, `/etc/pki/tls/certs/ca-bundle.crt` on Fedora and RHEL, and so
305    /// on), or else from the files in `/etc/ssl/certs`.
306    ///
307    /// Fails with [`io::ErrorKind::NotFound`] if there are none, as in a
308    /// container image built `FROM scratch` or without the `ca-certificates`
309    /// package. Install that package, or enable the `webpki-roots` feature and
310    /// use `TlsConnector::with_webpki_roots`.
311    pub fn with_system_roots() -> io::Result<Self> {
312        let file = std::env::var_os("SSL_CERT_FILE");
313        let dirs = std::env::var_os("SSL_CERT_DIR");
314        let roots = load_roots(
315            file.as_deref(),
316            dirs.as_deref(),
317            SYSTEM_CA_BUNDLES,
318            SYSTEM_CA_DIR,
319        )?;
320        Self::with_roots(roots)
321    }
322
323    /// A connector that trusts the certificate authorities in Mozilla's root
324    /// program, compiled into the program by the `webpki-roots` crate. Useful
325    /// where the machine has none installed; they change only when this
326    /// crate's dependency is updated.
327    ///
328    /// Needs the `webpki-roots` feature.
329    #[cfg(feature = "webpki-roots")]
330    pub fn with_webpki_roots() -> Self {
331        let roots = RootCertStore {
332            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
333        };
334        Self::with_roots(roots).expect("the webpki-roots crate provides roots")
335    }
336
337    /// The protocols to offer through ALPN, most preferred first, for example
338    /// `&[b"h2", b"http/1.1"]`. None by default. The one the server picked is
339    /// [`TlsStream::alpn_protocol`].
340    pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
341        Arc::make_mut(&mut self.config).alpn_protocols =
342            protocols.iter().map(|p| p.to_vec()).collect();
343        self
344    }
345
346    /// Presents a client certificate to servers that ask for one (mutual
347    /// TLS): a certificate chain and its private key, both in PEM format.
348    pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
349        let certs = pem_certs(cert_chain)?;
350        let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
351        let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
352            .map_err(mismatched_key)?;
353        Arc::make_mut(&mut self.config).client_auth_cert_resolver =
354            Arc::new(ClientCert(Arc::new(key)));
355        Ok(self)
356    }
357
358    /// How long a server may take to complete the TLS handshake (default:
359    /// 10 s).
360    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
361        self.handshake_timeout = timeout;
362        self
363    }
364
365    /// Performs the TLS handshake on a connection to `server_name`, which the
366    /// server's certificate must be valid for. `server_name` is a DNS name,
367    /// sent to the server through SNI, or an IP address (`[...]` brackets
368    /// around an IPv6 address are allowed), which is not.
369    ///
370    /// A certificate that is not valid for the name, expired, or not issued
371    /// by a trusted authority fails the handshake with
372    /// [`io::ErrorKind::InvalidData`] and a message saying which it was.
373    pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
374        let name = parse_server_name(server_name)?;
375        let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
376        TlsStream::new(tcp, conn.into())
377            .handshake(self.handshake_timeout)
378            .await
379    }
380}
381
382impl std::fmt::Debug for TlsConnector {
383    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384        f.debug_struct("TlsConnector")
385            .field("handshake_timeout", &self.handshake_timeout)
386            .finish_non_exhaustive()
387    }
388}
389
390/// The name a client checks the server's certificate against.
391fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
392    let ipv6 = name
393        .strip_prefix('[')
394        .and_then(|n| n.strip_suffix(']'))
395        .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
396    if let Some(ip) = ipv6 {
397        return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
398    }
399    ServerName::try_from(name.to_owned()).map_err(|_| {
400        coded(
401            Code::InvalidServerName,
402            format!("{name:?} is neither a DNS name nor an IP address"),
403            "pass the host name the certificate is for (\"example.com\"), or an IP address, \
404             without a port or a scheme.",
405        )
406    })
407}
408
409/// Always presents the same client certificate.
410#[derive(Debug)]
411struct ClientCert(Arc<CertifiedKey>);
412
413impl ResolvesClientCert for ClientCert {
414    fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
415        Some(self.0.clone())
416    }
417
418    fn has_certs(&self) -> bool {
419        true
420    }
421}
422
423/// Where Linux distributions keep the bundle of trusted CA certificates.
424const SYSTEM_CA_BUNDLES: &[&str] = &[
425    // Debian, Ubuntu, Alpine, Arch, Gentoo
426    "/etc/ssl/certs/ca-certificates.crt",
427    // Fedora, RHEL, CentOS
428    "/etc/pki/tls/certs/ca-bundle.crt",
429    "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
430    // openSUSE, SLES
431    "/etc/ssl/ca-bundle.pem",
432    // Alpine, Void
433    "/etc/ssl/cert.pem",
434];
435
436/// Where they are kept one per file, when there is no bundle.
437const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
438
439/// Reads trusted certificates the way OpenSSL finds them: `file` and `dirs`
440/// (the `SSL_CERT_FILE` and `SSL_CERT_DIR` variables) if either is set,
441/// otherwise the first of `bundles` that exists, otherwise the files in
442/// `dir`. Certificates rustls cannot use are skipped.
443fn load_roots(
444    file: Option<&OsStr>,
445    dirs: Option<&OsStr>,
446    bundles: &[&str],
447    dir: &str,
448) -> io::Result<RootCertStore> {
449    let mut roots = Roots {
450        store: RootCertStore::empty(),
451        seen: HashSet::new(),
452    };
453    if file.is_some() || dirs.is_some() {
454        if let Some(file) = file {
455            roots.add_file(Path::new(file)).map_err(|e| {
456                io::Error::new(
457                    e.kind(),
458                    giong::error::Error::new(
459                        Code::BadCertificateData,
460                        format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
461                        "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
462                         it to use the system's.",
463                    )
464                    .with_source(e),
465                )
466            })?;
467        }
468        for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
469            roots.add_dir(&dir);
470        }
471    } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
472        roots.add_file(bundle)?;
473    } else {
474        roots.add_dir(Path::new(dir));
475    }
476    if roots.store.is_empty() {
477        return Err(coded(
478            Code::NoTrustedRoots,
479            "no trusted CA certificates found on this machine",
480            "install the ca-certificates package, set SSL_CERT_FILE, or use \
481             TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
482        ));
483    }
484    Ok(roots.store)
485}
486
487struct Roots {
488    store: RootCertStore,
489    /// Files already read. The hashed names in certificate directories are
490    /// links to other files there.
491    seen: HashSet<PathBuf>,
492}
493
494impl Roots {
495    fn add_file(&mut self, path: &Path) -> io::Result<()> {
496        let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
497        if !self.seen.insert(real) {
498            return Ok(());
499        }
500        let pem = std::fs::read(path)?;
501        let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
502        self.store.add_parsable_certificates(certs);
503        Ok(())
504    }
505
506    fn add_dir(&mut self, dir: &Path) {
507        let Ok(entries) = std::fs::read_dir(dir) else {
508            return;
509        };
510        let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
511        paths.sort();
512        for path in paths.iter().filter(|p| p.is_file()) {
513            // One unreadable file does not spoil the others.
514            let _ = self.add_file(path);
515        }
516    }
517}
518
519/// A TLS connection over a [`TcpStream`], made by [`TlsAcceptor::accept`] on
520/// the server side or [`TlsConnector::connect`] on the client side.
521pub struct TlsStream {
522    tcp: TcpStream,
523    conn: RefCell<Connection>,
524    /// Decrypted data not handed out yet.
525    plain: RefCell<Vec<u8>>,
526    /// Scratch buffer for outgoing TLS records, reused between writes.
527    wire: RefCell<Vec<u8>>,
528    /// The peer closed the connection (with or without `close_notify`).
529    eof: Cell<bool>,
530    /// The peer ended its side with a `close_notify` alert, so nothing it
531    /// sent was cut off.
532    close_notify: Cell<bool>,
533    /// A task is writing TLS records to the socket. Records must not
534    /// interleave, so other tasks wait for it in `waiters`.
535    sending: Cell<bool>,
536    /// A write to the socket failed or was cancelled half way: the record
537    /// stream is cut in the middle and nothing more can be sent.
538    broken: Cell<bool>,
539    /// A receive error held back until the data before it has been handed out.
540    failed: Cell<Option<io::Error>>,
541    /// Tasks waiting for `sending` to clear.
542    waiters: RefCell<Vec<Waker>>,
543}
544
545/// Held while TLS records are being written to the socket.
546struct Sending<'a> {
547    stream: &'a TlsStream,
548    complete: bool,
549}
550
551impl Drop for Sending<'_> {
552    fn drop(&mut self) {
553        if !self.complete {
554            self.stream.broken.set(true);
555        }
556        self.stream.sending.set(false);
557        let waiters = mem::take(&mut *self.stream.waiters.borrow_mut());
558        for waker in waiters {
559            waker.wake();
560        }
561    }
562}
563
564impl TlsStream {
565    fn new(tcp: TcpStream, conn: Connection) -> Self {
566        Self {
567            tcp,
568            conn: RefCell::new(conn),
569            plain: RefCell::new(Vec::new()),
570            wire: RefCell::new(Vec::new()),
571            eof: Cell::new(false),
572            close_notify: Cell::new(false),
573            sending: Cell::new(false),
574            broken: Cell::new(false),
575            failed: Cell::new(None),
576            waiters: RefCell::new(Vec::new()),
577        }
578    }
579
580    /// Runs the handshake, either side, within `limit`.
581    async fn handshake(self, limit: Duration) -> io::Result<Self> {
582        let handshake = async {
583            while self.conn.borrow().is_handshaking() {
584                self.flush_tls().await?;
585                if !self.conn.borrow().is_handshaking() {
586                    break;
587                }
588                if self.eof.get() {
589                    return Err(coded(
590                        Code::TlsHandshakeEof,
591                        "the peer closed the connection during the TLS handshake",
592                        "check that the other side speaks TLS on this port, and whether it \
593                         wants a client certificate or another server name.",
594                    ));
595                }
596                self.pump().await?;
597            }
598            self.flush_tls().await
599        };
600        match timeout(limit, handshake).await {
601            Ok(Ok(())) => Ok(self),
602            Ok(Err(e)) => Err(e),
603            Err(_) => Err(coded(
604                Code::TlsHandshakeTimeout,
605                format!("the TLS handshake did not finish within {limit:?}"),
606                "check that the other side speaks TLS on this port and is not overloaded, or \
607                 raise handshake_timeout.",
608            )),
609        }
610    }
611
612    /// Sends every TLS record rustls has queued.
613    async fn flush_tls(&self) -> io::Result<()> {
614        loop {
615            if !self.conn.borrow().wants_write() {
616                return Ok(());
617            }
618            if self.broken.get() {
619                return Err(coded(
620                    Code::TlsBroken,
621                    "a TLS write failed or was cancelled; nothing more can be sent",
622                    "open a new connection. A write cancelled half-way (a dropped future, a \
623                     timeout) leaves a partial record behind, so the stream cannot go on.",
624                ));
625            }
626            if self.sending.get() {
627                // Another task is sending. Wait for it, then send what is
628                // left (it may already have sent this task's records too).
629                poll_fn(|cx| {
630                    if !self.sending.get() {
631                        return Poll::Ready(());
632                    }
633                    // A task polled again while it waits is listed once.
634                    let mut waiters = self.waiters.borrow_mut();
635                    if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
636                        waiters.push(cx.waker().clone());
637                    }
638                    Poll::Pending
639                })
640                .await;
641                continue;
642            }
643            let mut wire = mem::take(&mut *self.wire.borrow_mut());
644            {
645                let mut conn = self.conn.borrow_mut();
646                while conn.wants_write() {
647                    conn.write_tls(&mut wire)?;
648                }
649            }
650            self.sending.set(true);
651            let mut sending = Sending {
652                stream: self,
653                complete: false,
654            };
655            let (res, mut wire) = self.tcp.write_all(wire).await;
656            res?;
657            sending.complete = true;
658            drop(sending);
659            wire.clear();
660            *self.wire.borrow_mut() = wire;
661        }
662    }
663
664    /// Receives one chunk of TLS data, decrypts it into `plain`, and sends
665    /// whatever the protocol wants to send in response.
666    async fn pump(&self) -> io::Result<()> {
667        // Cancelling here loses nothing: `recv` is cancel safe.
668        let chunk = self.tcp.recv().await?;
669        if chunk.is_empty() {
670            self.eof.set(true);
671            return Ok(());
672        }
673        let result = {
674            let mut conn = self.conn.borrow_mut();
675            let mut plain = self.plain.borrow_mut();
676            let mut input = &chunk[..];
677            let mut result = Ok(());
678            while !input.is_empty() {
679                // rustls buffers a bounded amount of plaintext, so it has to
680                // be drained as the records are fed in.
681                match conn.read_tls(&mut input) {
682                    Ok(0) => {
683                        result = Err(coded(
684                            Code::TlsProtocol,
685                            "rustls accepted no more TLS data",
686                            "this is a bug in giong-tls; please report it at \
687                             https://github.com/giong-run/Giong/issues.",
688                        ));
689                        break;
690                    }
691                    Ok(_) => {}
692                    Err(e) => {
693                        result = Err(e);
694                        break;
695                    }
696                }
697                match conn.process_new_packets() {
698                    Ok(state) => {
699                        let n = state.plaintext_bytes_to_read();
700                        if n > 0 {
701                            let at = plain.len();
702                            plain.resize(at + n, 0);
703                            if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
704                                plain.truncate(at);
705                                result = Err(e);
706                                break;
707                            }
708                        }
709                        if state.peer_has_closed() {
710                            self.close_notify.set(true);
711                            self.eof.set(true);
712                            break;
713                        }
714                    }
715                    Err(e) => {
716                        result = Err(tls_error(e));
717                        break;
718                    }
719                }
720            }
721            result
722        };
723        drop(chunk);
724        // Handshake messages, key updates, or the alert describing `result`.
725        // Not being able to send them is no reason to withhold what was
726        // received, if sending has failed before.
727        if self.broken.get() {
728            return result;
729        }
730        let flushed = self.flush_tls().await;
731        result.and(flushed)
732    }
733
734    /// Receives decrypted data. An empty buffer means that the peer has closed
735    /// the connection, with a `close_notify` alert or by closing the socket.
736    ///
737    /// The two are not the same when the end of the stream is what marks
738    /// the end of the data, as in an HTTP response without a length: only
739    /// `close_notify` is authenticated, while anyone on the network path can
740    /// close a TCP connection early and cut the data short (a truncation
741    /// attack). Check [`received_close_notify`](Self::received_close_notify)
742    /// before trusting such data to be complete.
743    ///
744    /// Cancel safe: dropping the future loses no data. (If it is dropped at
745    /// the rare moment a TLS protocol message is being sent, sending fails
746    /// from then on instead of continuing on a broken stream.)
747    ///
748    /// One task may receive while another one sends.
749    pub async fn recv(&self) -> io::Result<Vec<u8>> {
750        loop {
751            {
752                let mut plain = self.plain.borrow_mut();
753                if !plain.is_empty() {
754                    return Ok(mem::take(&mut *plain));
755                }
756            }
757            if let Some(e) = self.failed.take() {
758                return Err(e);
759            }
760            if self.eof.get() {
761                return Ok(Vec::new());
762            }
763            if let Err(e) = self.pump().await {
764                // Data that arrived intact before the failure comes first.
765                if self.plain.borrow().is_empty() {
766                    return Err(e);
767                }
768                self.failed.set(Some(e));
769            }
770        }
771    }
772
773    /// Encrypts and sends all of `buf`, then hands the buffer back.
774    ///
775    /// Not cancel safe: if the future is dropped, part of `buf` may have been
776    /// sent, and if that happened in the middle of a TLS record the
777    /// connection cannot send any more: later writes return an error, while
778    /// data the peer already sent can still be received.
779    pub async fn write_all(&self, buf: Vec<u8>) -> (io::Result<()>, Vec<u8>) {
780        let mut sent = 0;
781        while sent < buf.len() {
782            // rustls accepts a bounded amount per call; send as it fills up.
783            let accepted = self.conn.borrow_mut().writer().write(&buf[sent..]);
784            match accepted {
785                Ok(n) => sent += n,
786                Err(e) => return (Err(e), buf),
787            }
788            if let Err(e) = self.flush_tls().await {
789                return (Err(e), buf);
790            }
791        }
792        (Ok(()), buf)
793    }
794
795    /// Sends the TLS `close_notify` alert and closes the sending direction.
796    pub async fn shutdown(&self) -> io::Result<()> {
797        self.conn.borrow_mut().send_close_notify();
798        self.flush_tls().await?;
799        self.tcp.shutdown(Shutdown::Write)
800    }
801
802    /// `true` once the peer has ended the connection with a TLS
803    /// `close_notify` alert. `false` while it is open, and if the peer, or
804    /// something on the network path, closed the TCP connection without
805    /// one: data that ends there may have been cut short. See
806    /// [`recv`](Self::recv).
807    pub fn received_close_notify(&self) -> bool {
808        self.close_notify.get()
809    }
810
811    /// The protocol agreed on through ALPN, if any (for example `http/1.1`).
812    pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
813        self.conn.borrow().alpn_protocol().map(<[u8]>::to_vec)
814    }
815
816    /// The certificate chain the peer presented, its own certificate first:
817    /// the server's on a client connection; on a server connection, the
818    /// client's if client authentication is configured and the client sent
819    /// one.
820    pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
821        self.conn.borrow().peer_certificates().map(<[_]>::to_vec)
822    }
823
824    /// `true` if the handshake resumed an earlier session instead of doing a
825    /// full one.
826    pub fn resumed(&self) -> bool {
827        self.conn.borrow().handshake_kind() == Some(rustls::HandshakeKind::Resumed)
828    }
829
830    /// The underlying TCP connection.
831    pub fn tcp(&self) -> &TcpStream {
832        &self.tcp
833    }
834}
835
836impl std::fmt::Debug for TlsStream {
837    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
838        f.debug_struct("TlsStream")
839            .field("tcp", &self.tcp)
840            .finish_non_exhaustive()
841    }
842}
843
844#[cfg(test)]
845mod tests {
846    use super::*;
847
848    fn ca_pem(name: &str) -> String {
849        let key = rcgen::KeyPair::generate().unwrap();
850        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
851        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
852        params
853            .distinguished_name
854            .push(rcgen::DnType::CommonName, name);
855        params.self_signed(&key).unwrap().pem()
856    }
857
858    /// A fresh, empty directory under the system's temporary directory.
859    fn scratch(name: &str) -> PathBuf {
860        let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
861        let _ = std::fs::remove_dir_all(&dir);
862        std::fs::create_dir_all(&dir).unwrap();
863        dir
864    }
865
866    fn os(path: &Path) -> &OsStr {
867        path.as_os_str()
868    }
869
870    #[test]
871    fn server_names_are_dns_names_or_ip_addresses() {
872        let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
873        let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
874        assert!(dns("example.com"));
875        assert!(dns("db.prod.svc.cluster.local"));
876        assert!(ip("10.0.0.1"));
877        assert!(ip("::1"));
878        assert!(ip("[::1]"));
879        for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
880            let err = parse_server_name(bad).unwrap_err();
881            assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
882        }
883    }
884
885    #[test]
886    fn the_first_bundle_that_exists_is_read() {
887        let dir = scratch("bundle");
888        let bundle = dir.join("bundle.pem");
889        let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
890        std::fs::write(&bundle, two).unwrap();
891        let missing = dir.join("missing.pem");
892        let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
893        let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
894        assert_eq!(roots.len(), 2);
895        std::fs::remove_dir_all(dir).unwrap();
896    }
897
898    #[test]
899    fn ssl_cert_file_and_dir_replace_the_system_locations() {
900        let dir = scratch("env");
901        let file = dir.join("file.pem");
902        std::fs::write(&file, ca_pem("from file")).unwrap();
903        let certs = dir.join("certs");
904        std::fs::create_dir(&certs).unwrap();
905        std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
906        std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
907        std::fs::write(certs.join("README"), "not a certificate").unwrap();
908        // OpenSSL's hashed names are links to the same files.
909        std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
910        let system = dir.join("system.pem");
911        std::fs::write(&system, ca_pem("system")).unwrap();
912        let bundles = [system.to_str().unwrap()];
913
914        let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
915        assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
916        let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
917        assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
918        let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
919        let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
920        assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
921
922        let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
923        assert_eq!(err.kind(), io::ErrorKind::NotFound);
924        assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
925        std::fs::remove_dir_all(dir).unwrap();
926    }
927
928    #[test]
929    fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
930        let dir = scratch("dir");
931        std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
932        let roots = load_roots(
933            None,
934            None,
935            &["/nonexistent/bundle.crt"],
936            dir.to_str().unwrap(),
937        );
938        assert_eq!(roots.unwrap().len(), 1);
939
940        let empty = scratch("empty");
941        let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
942        assert_eq!(err.kind(), io::ErrorKind::NotFound);
943        assert!(err.to_string().contains("webpki-roots"), "{err}");
944        std::fs::remove_dir_all(dir).unwrap();
945        std::fs::remove_dir_all(empty).unwrap();
946    }
947
948    #[test]
949    fn this_machines_roots_load() {
950        // Every machine the tests run on (CI included) has a CA bundle.
951        TlsConnector::with_system_roots().unwrap();
952    }
953
954    #[cfg(feature = "webpki-roots")]
955    #[test]
956    fn mozillas_roots_are_compiled_in() {
957        TlsConnector::with_webpki_roots();
958    }
959}