1#![warn(missing_docs)]
80
81mod ktls;
82
83pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
84
85use std::cell::{Cell, RefCell, RefMut};
86use std::collections::HashSet;
87use std::ffi::OsStr;
88use std::future::poll_fn;
89use std::io::{self, Read, Write};
90use std::mem;
91use std::net::Shutdown;
92use std::path::{Path, PathBuf};
93use std::sync::Arc;
94use std::task::{Poll, Waker};
95use std::time::Duration;
96
97use giong::error::Code;
98use giong::net::TcpStream;
99use giong::time::timeout;
100use rustls::client::ResolvesClientCert;
101use rustls::pki_types::pem::PemObject;
102use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
103use rustls::sign::CertifiedKey;
104use rustls::{
105 ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
106 SignatureScheme,
107};
108
109pub use rustls;
110
111fn coded(
112 code: Code,
113 message: impl Into<std::borrow::Cow<'static, str>>,
114 fix: &'static str,
115) -> io::Error {
116 giong::error::Error::new(code, message, fix).into()
117}
118
119fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
122 let end = offset.saturating_add(len);
123 coded(
124 Code::FileTooShort,
125 format!(
126 "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
127 end - at
128 ),
129 "take the length from the open file (File::len), and replace a file that is being \
130 served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
131 than announced, so close the connection.",
132 )
133}
134
135fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
137 coded(
138 Code::BadCertificateData,
139 e.to_string(),
140 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
141 at least one certificate.",
142 )
143}
144
145fn bad_key(e: impl std::fmt::Display) -> io::Error {
147 coded(
148 Code::BadCertificateData,
149 format!("cannot read the private key: {e}"),
150 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
151 EC forms).",
152 )
153}
154
155fn mismatched_key(e: rustls::Error) -> io::Error {
157 coded(
158 Code::BadCertificateData,
159 format!("the certificate and the private key cannot be used together: {e}"),
160 "check that the key belongs to the first certificate of the chain, and that its type \
161 (RSA, ECDSA, Ed25519) is supported.",
162 )
163}
164
165fn tls_error(e: rustls::Error) -> io::Error {
167 match e {
168 rustls::Error::InvalidCertificate(_) => coded(
169 Code::TlsCertificate,
170 format!("the peer's certificate was rejected: {e}"),
171 "check the name you connect to, the certificate's expiry and its chain; a \
172 private authority has to be trusted with TlsConnector::with_roots.",
173 ),
174 e => coded(
175 Code::TlsProtocol,
176 format!("TLS error: {e}"),
177 "check that the other side speaks TLS on this port, and that both sides share a \
178 protocol version and cipher suite.",
179 ),
180 }
181}
182
183const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
185
186fn handshake_timed_out(limit: Duration) -> io::Error {
187 coded(
188 Code::TlsHandshakeTimeout,
189 format!("the TLS handshake did not finish within {limit:?}"),
190 "check that the other side speaks TLS on this port and is not overloaded, or raise \
191 handshake_timeout.",
192 )
193}
194
195fn handshake_eof() -> io::Error {
196 coded(
197 Code::TlsHandshakeEof,
198 "the peer closed the connection during the TLS handshake",
199 "check that the other side speaks TLS on this port, and whether it wants a client \
200 certificate or another server name.",
201 )
202}
203
204fn broken() -> io::Error {
205 coded(
206 Code::TlsBroken,
207 "a TLS write failed or was cancelled; nothing more can be sent",
208 "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
209 leaves a partial record or message behind, so the stream cannot go on.",
210 )
211}
212
213fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
215 let certs = CertificateDer::pem_slice_iter(pem)
216 .collect::<Result<Vec<_>, _>>()
217 .map_err(bad_certificate_data)?;
218 if certs.is_empty() {
219 return Err(bad_certificate_data("no certificate found in the PEM data"));
220 }
221 Ok(certs)
222}
223
224fn ring() -> Arc<rustls::crypto::CryptoProvider> {
225 Arc::new(rustls::crypto::ring::default_provider())
226}
227
228#[derive(Clone)]
232pub struct TlsAcceptor {
233 config: Arc<ServerConfig>,
234 handshake_timeout: Duration,
235 ktls: ktls::Plan,
236}
237
238impl TlsAcceptor {
239 pub fn new(config: Arc<ServerConfig>) -> Self {
241 Self {
242 config,
243 handshake_timeout: HANDSHAKE_TIMEOUT,
244 ktls: ktls::Plan::Off,
245 }
246 }
247
248 pub fn from_pem(cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
252 let certs = pem_certs(cert_chain)?;
253 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
254 let mut config = ServerConfig::builder_with_provider(ring())
255 .with_safe_default_protocol_versions()
256 .map_err(tls_error)?
257 .with_no_client_auth()
258 .with_single_cert(certs, key)
259 .map_err(mismatched_key)?;
260 config.alpn_protocols = vec![b"http/1.1".to_vec()];
261 Ok(Self::new(Arc::new(config)))
262 }
263
264 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
272 Arc::make_mut(&mut self.config).alpn_protocols =
273 protocols.iter().map(|p| p.to_vec()).collect();
274 self
275 }
276
277 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
280 self.handshake_timeout = timeout;
281 self
282 }
283
284 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
309 let early_data = self.config.max_early_data_size > 0;
310 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
311 if mode != Ktls::Off {
312 Arc::make_mut(&mut self.config).enable_secret_extraction = true;
313 }
314 Ok(self)
315 }
316
317 pub fn ktls_unavailable(&self) -> Option<&str> {
322 self.ktls.unavailable()
323 }
324
325 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
331 let tcp = match &self.ktls {
332 ktls::Plan::Off => tcp,
333 ktls::Plan::Try { required } => {
334 let start = ktls::Start::Server(self.config.clone());
335 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
336 ktls::Outcome::Kernel(tls) => return Ok(*tls),
337 ktls::Outcome::Declined(_, e) if *required => return Err(e),
338 ktls::Outcome::Declined(tcp, _) => {
339 self.ktls.stayed();
340 tcp
341 }
342 }
343 }
344 ktls::Plan::Unavailable(_) => {
345 self.ktls.stayed();
346 tcp
347 }
348 };
349 let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
350 TlsStream::new(tcp, conn.into())
351 .handshake(self.handshake_timeout)
352 .await
353 }
354}
355
356impl std::fmt::Debug for TlsAcceptor {
357 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358 f.debug_struct("TlsAcceptor")
359 .field("handshake_timeout", &self.handshake_timeout)
360 .field("ktls", &self.ktls)
361 .finish_non_exhaustive()
362 }
363}
364
365#[derive(Clone)]
386pub struct TlsConnector {
387 config: Arc<ClientConfig>,
388 handshake_timeout: Duration,
389 ktls: ktls::Plan,
390}
391
392impl TlsConnector {
393 pub fn new(config: Arc<ClientConfig>) -> Self {
395 Self {
396 config,
397 handshake_timeout: HANDSHAKE_TIMEOUT,
398 ktls: ktls::Plan::Off,
399 }
400 }
401
402 pub fn with_roots(roots: RootCertStore) -> io::Result<Self> {
405 if roots.is_empty() {
406 return Err(io::Error::new(
407 io::ErrorKind::InvalidData,
408 giong::error::Error::new(
409 Code::NoTrustedRoots,
410 "no trusted certificate authority given",
411 "pass at least one certificate, or use TlsConnector::with_system_roots.",
412 ),
413 ));
414 }
415 let config = ClientConfig::builder_with_provider(ring())
416 .with_safe_default_protocol_versions()
417 .map_err(tls_error)?
418 .with_root_certificates(roots)
419 .with_no_client_auth();
420 Ok(Self::new(Arc::new(config)))
421 }
422
423 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
426 let mut roots = RootCertStore::empty();
427 for cert in pem_certs(pem)? {
428 roots.add(cert).map_err(bad_certificate_data)?;
429 }
430 Self::with_roots(roots)
431 }
432
433 pub fn with_system_roots() -> io::Result<Self> {
449 let file = std::env::var_os("SSL_CERT_FILE");
450 let dirs = std::env::var_os("SSL_CERT_DIR");
451 let roots = load_roots(
452 file.as_deref(),
453 dirs.as_deref(),
454 SYSTEM_CA_BUNDLES,
455 SYSTEM_CA_DIR,
456 )?;
457 Self::with_roots(roots)
458 }
459
460 #[cfg(feature = "webpki-roots")]
467 pub fn with_webpki_roots() -> Self {
468 let roots = RootCertStore {
469 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
470 };
471 Self::with_roots(roots).expect("the webpki-roots crate provides roots")
472 }
473
474 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
478 Arc::make_mut(&mut self.config).alpn_protocols =
479 protocols.iter().map(|p| p.to_vec()).collect();
480 self
481 }
482
483 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
486 let certs = pem_certs(cert_chain)?;
487 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
488 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
489 .map_err(mismatched_key)?;
490 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
491 Arc::new(ClientCert(Arc::new(key)));
492 Ok(self)
493 }
494
495 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
498 self.handshake_timeout = timeout;
499 self
500 }
501
502 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
516 let early_data = self.config.enable_early_data;
517 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
518 if mode != Ktls::Off {
519 Arc::make_mut(&mut self.config).enable_secret_extraction = true;
520 }
521 Ok(self)
522 }
523
524 pub fn ktls_unavailable(&self) -> Option<&str> {
527 self.ktls.unavailable()
528 }
529
530 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
539 let name = parse_server_name(server_name)?;
540 let tcp = match &self.ktls {
541 ktls::Plan::Off => tcp,
542 ktls::Plan::Try { required } => {
543 let start = ktls::Start::Client(self.config.clone(), name.clone());
544 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
545 ktls::Outcome::Kernel(tls) => return Ok(*tls),
546 ktls::Outcome::Declined(_, e) if *required => return Err(e),
547 ktls::Outcome::Declined(tcp, _) => {
548 self.ktls.stayed();
549 tcp
550 }
551 }
552 }
553 ktls::Plan::Unavailable(_) => {
554 self.ktls.stayed();
555 tcp
556 }
557 };
558 let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
559 TlsStream::new(tcp, conn.into())
560 .handshake(self.handshake_timeout)
561 .await
562 }
563}
564
565impl std::fmt::Debug for TlsConnector {
566 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
567 f.debug_struct("TlsConnector")
568 .field("handshake_timeout", &self.handshake_timeout)
569 .field("ktls", &self.ktls)
570 .finish_non_exhaustive()
571 }
572}
573
574fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
576 let ipv6 = name
577 .strip_prefix('[')
578 .and_then(|n| n.strip_suffix(']'))
579 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
580 if let Some(ip) = ipv6 {
581 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
582 }
583 ServerName::try_from(name.to_owned()).map_err(|_| {
584 coded(
585 Code::InvalidServerName,
586 format!("{name:?} is neither a DNS name nor an IP address"),
587 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
588 without a port or a scheme.",
589 )
590 })
591}
592
593#[derive(Debug)]
595struct ClientCert(Arc<CertifiedKey>);
596
597impl ResolvesClientCert for ClientCert {
598 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
599 Some(self.0.clone())
600 }
601
602 fn has_certs(&self) -> bool {
603 true
604 }
605}
606
607const SYSTEM_CA_BUNDLES: &[&str] = &[
609 "/etc/ssl/certs/ca-certificates.crt",
611 "/etc/pki/tls/certs/ca-bundle.crt",
613 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
614 "/etc/ssl/ca-bundle.pem",
616 "/etc/ssl/cert.pem",
618];
619
620const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
622
623fn load_roots(
628 file: Option<&OsStr>,
629 dirs: Option<&OsStr>,
630 bundles: &[&str],
631 dir: &str,
632) -> io::Result<RootCertStore> {
633 let mut roots = Roots {
634 store: RootCertStore::empty(),
635 seen: HashSet::new(),
636 };
637 if file.is_some() || dirs.is_some() {
638 if let Some(file) = file {
639 roots.add_file(Path::new(file)).map_err(|e| {
640 io::Error::new(
641 e.kind(),
642 giong::error::Error::new(
643 Code::BadCertificateData,
644 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
645 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
646 it to use the system's.",
647 )
648 .with_source(e),
649 )
650 })?;
651 }
652 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
653 roots.add_dir(&dir);
654 }
655 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
656 roots.add_file(bundle)?;
657 } else {
658 roots.add_dir(Path::new(dir));
659 }
660 if roots.store.is_empty() {
661 return Err(coded(
662 Code::NoTrustedRoots,
663 "no trusted CA certificates found on this machine",
664 "install the ca-certificates package, set SSL_CERT_FILE, or use \
665 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
666 ));
667 }
668 Ok(roots.store)
669}
670
671struct Roots {
672 store: RootCertStore,
673 seen: HashSet<PathBuf>,
676}
677
678impl Roots {
679 fn add_file(&mut self, path: &Path) -> io::Result<()> {
680 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
681 if !self.seen.insert(real) {
682 return Ok(());
683 }
684 let pem = std::fs::read(path)?;
685 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
686 self.store.add_parsable_certificates(certs);
687 Ok(())
688 }
689
690 fn add_dir(&mut self, dir: &Path) {
691 let Ok(entries) = std::fs::read_dir(dir) else {
692 return;
693 };
694 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
695 paths.sort();
696 for path in paths.iter().filter(|p| p.is_file()) {
697 let _ = self.add_file(path);
699 }
700 }
701}
702
703pub struct TlsStream {
706 tcp: TcpStream,
707 engine: RefCell<Engine>,
709 plain: RefCell<Vec<u8>>,
711 wire: RefCell<Vec<u8>>,
713 eof: Cell<bool>,
715 close_notify: Cell<bool>,
718 sending: Cell<bool>,
721 broken: Cell<bool>,
724 failed: Cell<Option<io::Error>>,
726 waiters: RefCell<Vec<Waker>>,
728}
729
730#[allow(clippy::large_enum_variant)]
734enum Engine {
735 User(Connection),
737 Kernel(ktls::Kernel),
740}
741
742struct Sending<'a> {
746 stream: &'a TlsStream,
747 complete: bool,
748}
749
750impl Sending<'_> {
751 fn done(mut self) {
753 self.complete = true;
754 }
755}
756
757impl Drop for Sending<'_> {
758 fn drop(&mut self) {
759 if !self.complete {
760 self.stream.broken.set(true);
761 }
762 self.stream.sending.set(false);
763 let waiters = mem::take(&mut *self.stream.waiters.borrow_mut());
764 for waker in waiters {
765 waker.wake();
766 }
767 }
768}
769
770impl TlsStream {
771 fn new(tcp: TcpStream, conn: Connection) -> Self {
772 Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
773 }
774
775 fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
779 Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
780 }
781
782 fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
783 Self {
784 tcp,
785 engine: RefCell::new(engine),
786 plain: RefCell::new(plain),
787 wire: RefCell::new(Vec::new()),
788 eof: Cell::new(peer_closed),
789 close_notify: Cell::new(peer_closed),
790 sending: Cell::new(false),
791 broken: Cell::new(false),
792 failed: Cell::new(None),
793 waiters: RefCell::new(Vec::new()),
794 }
795 }
796
797 fn conn(&self) -> RefMut<'_, Connection> {
800 RefMut::map(self.engine.borrow_mut(), |e| match e {
801 Engine::User(c) => c,
802 Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
803 })
804 }
805
806 pub fn is_ktls(&self) -> bool {
810 matches!(*self.engine.borrow(), Engine::Kernel(_))
811 }
812
813 async fn wait_for_sender(&self) {
815 poll_fn(|cx| {
816 if !self.sending.get() {
817 return Poll::Ready(());
818 }
819 let mut waiters = self.waiters.borrow_mut();
821 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
822 waiters.push(cx.waker().clone());
823 }
824 Poll::Pending
825 })
826 .await;
827 }
828
829 async fn lock_send(&self) -> Sending<'_> {
832 while self.sending.get() {
833 self.wait_for_sender().await;
834 }
835 self.sending.set(true);
836 Sending {
837 stream: self,
838 complete: false,
839 }
840 }
841
842 async fn handshake(self, limit: Duration) -> io::Result<Self> {
844 let handshake = async {
845 while self.conn().is_handshaking() {
846 self.flush_tls().await?;
847 if !self.conn().is_handshaking() {
848 break;
849 }
850 if self.eof.get() {
851 return Err(handshake_eof());
852 }
853 self.pump().await?;
854 }
855 self.flush_tls().await
856 };
857 match timeout(limit, handshake).await {
858 Ok(Ok(())) => Ok(self),
859 Ok(Err(e)) => Err(e),
860 Err(_) => Err(handshake_timed_out(limit)),
861 }
862 }
863
864 async fn flush_tls(&self) -> io::Result<()> {
866 loop {
867 if !self.conn().wants_write() {
868 return Ok(());
869 }
870 if self.broken.get() {
871 return Err(broken());
872 }
873 if self.sending.get() {
874 self.wait_for_sender().await;
877 continue;
878 }
879 let mut wire = mem::take(&mut *self.wire.borrow_mut());
880 {
881 let mut conn = self.conn();
882 while conn.wants_write() {
883 conn.write_tls(&mut wire)?;
884 }
885 }
886 let sending = self.lock_send().await;
887 let (res, mut wire) = self.tcp.write_all(wire).await;
888 res?;
889 sending.done();
890 wire.clear();
891 *self.wire.borrow_mut() = wire;
892 }
893 }
894
895 async fn pump(&self) -> io::Result<()> {
898 let chunk = self.tcp.recv().await?;
900 if chunk.is_empty() {
901 self.eof.set(true);
902 return Ok(());
903 }
904 let result = {
905 let mut conn = self.conn();
906 let mut plain = self.plain.borrow_mut();
907 let mut input = &chunk[..];
908 let mut result = Ok(());
909 while !input.is_empty() {
910 match conn.read_tls(&mut input) {
913 Ok(0) => {
914 result = Err(coded(
915 Code::TlsProtocol,
916 "rustls accepted no more TLS data",
917 "this is a bug in giong-tls; please report it at \
918 https://github.com/giong-run/Giong/issues.",
919 ));
920 break;
921 }
922 Ok(_) => {}
923 Err(e) => {
924 result = Err(e);
925 break;
926 }
927 }
928 match conn.process_new_packets() {
929 Ok(state) => {
930 let n = state.plaintext_bytes_to_read();
931 if n > 0 {
932 let at = plain.len();
933 plain.resize(at + n, 0);
934 if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
935 plain.truncate(at);
936 result = Err(e);
937 break;
938 }
939 }
940 if state.peer_has_closed() {
941 self.close_notify.set(true);
942 self.eof.set(true);
943 break;
944 }
945 }
946 Err(e) => {
947 result = Err(tls_error(e));
948 break;
949 }
950 }
951 }
952 result
953 };
954 drop(chunk);
955 if self.broken.get() {
959 return result;
960 }
961 let flushed = self.flush_tls().await;
962 result.and(flushed)
963 }
964
965 pub async fn recv(&self) -> io::Result<Vec<u8>> {
981 if self.is_ktls() {
982 return self.kernel_recv().await;
983 }
984 loop {
985 {
986 let mut plain = self.plain.borrow_mut();
987 if !plain.is_empty() {
988 return Ok(mem::take(&mut *plain));
989 }
990 }
991 if let Some(e) = self.failed.take() {
992 return Err(e);
993 }
994 if self.eof.get() {
995 return Ok(Vec::new());
996 }
997 if let Err(e) = self.pump().await {
998 if self.plain.borrow().is_empty() {
1000 return Err(e);
1001 }
1002 self.failed.set(Some(e));
1003 }
1004 }
1005 }
1006
1007 pub async fn write_all(&self, buf: Vec<u8>) -> (io::Result<()>, Vec<u8>) {
1014 if self.is_ktls() {
1015 return self.kernel_write_all(buf).await;
1016 }
1017 let mut sent = 0;
1018 while sent < buf.len() {
1019 let accepted = self.conn().writer().write(&buf[sent..]);
1021 match accepted {
1022 Ok(n) => sent += n,
1023 Err(e) => return (Err(e), buf),
1024 }
1025 if let Err(e) = self.flush_tls().await {
1026 return (Err(e), buf);
1027 }
1028 }
1029 (Ok(()), buf)
1030 }
1031
1032 pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1043 where
1044 B: giong::IoBuf + AsRef<[u8]>,
1045 {
1046 if self.is_ktls() {
1047 return self.kernel_write_all_vectored(bufs).await;
1048 }
1049 for buf in &bufs {
1050 let buf = buf.as_ref();
1051 let mut sent = 0;
1052 while sent < buf.len() {
1053 let accepted = self.conn().writer().write(&buf[sent..]);
1054 match accepted {
1055 Ok(n) => sent += n,
1056 Err(e) => return (Err(e), bufs),
1057 }
1058 if sent < buf.len() {
1061 if let Err(e) = self.flush_tls().await {
1062 return (Err(e), bufs);
1063 }
1064 }
1065 }
1066 }
1067 match self.flush_tls().await {
1068 Ok(()) => (Ok(()), bufs),
1069 Err(e) => (Err(e), bufs),
1070 }
1071 }
1072
1073 pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1090 if offset
1091 .checked_add(len)
1092 .map_or(true, |end| end > i64::MAX as u64)
1093 {
1094 return Err(file_too_short(offset, len, offset));
1095 }
1096 if self.is_ktls() {
1097 return self.kernel_send_file(file, offset, len).await;
1098 }
1099 const PIECE: u64 = 256 * 1024;
1100 let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1101 let (mut at, mut left) = (offset, len);
1102 while left > 0 {
1103 let (res, b) = file.read_at(buf, at).await;
1104 buf = b;
1105 let n = match res {
1106 Ok(0) => {
1107 self.flush_tls().await?;
1108 return Err(file_too_short(offset, len, at));
1109 }
1110 Ok(n) => (n as u64).min(left) as usize,
1111 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1112 Err(e) => return Err(e),
1113 };
1114 let mut sent = 0;
1115 while sent < n {
1116 let accepted = self.conn().writer().write(&buf[sent..n]);
1117 sent += accepted?;
1118 self.flush_tls().await?;
1119 }
1120 at += n as u64;
1121 left -= n as u64;
1122 }
1123 Ok(())
1124 }
1125
1126 pub async fn shutdown(&self) -> io::Result<()> {
1128 if self.is_ktls() {
1129 return self.kernel_shutdown().await;
1130 }
1131 self.conn().send_close_notify();
1132 self.flush_tls().await?;
1133 self.tcp.shutdown(Shutdown::Write)
1134 }
1135
1136 pub fn received_close_notify(&self) -> bool {
1142 self.close_notify.get()
1143 }
1144
1145 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
1147 match &*self.engine.borrow() {
1148 Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
1149 Engine::Kernel(k) => k.negotiated.alpn.clone(),
1150 }
1151 }
1152
1153 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
1158 match &*self.engine.borrow() {
1159 Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
1160 Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
1161 }
1162 }
1163
1164 pub fn resumed(&self) -> bool {
1167 match &*self.engine.borrow() {
1168 Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
1169 Engine::Kernel(k) => k.negotiated.resumed,
1170 }
1171 }
1172
1173 pub fn tcp(&self) -> &TcpStream {
1175 &self.tcp
1176 }
1177}
1178
1179impl std::fmt::Debug for TlsStream {
1180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1181 f.debug_struct("TlsStream")
1182 .field("tcp", &self.tcp)
1183 .field("ktls", &self.is_ktls())
1184 .finish_non_exhaustive()
1185 }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190 use super::*;
1191
1192 fn ca_pem(name: &str) -> String {
1193 let key = rcgen::KeyPair::generate().unwrap();
1194 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1195 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1196 params
1197 .distinguished_name
1198 .push(rcgen::DnType::CommonName, name);
1199 params.self_signed(&key).unwrap().pem()
1200 }
1201
1202 fn scratch(name: &str) -> PathBuf {
1204 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
1205 let _ = std::fs::remove_dir_all(&dir);
1206 std::fs::create_dir_all(&dir).unwrap();
1207 dir
1208 }
1209
1210 fn os(path: &Path) -> &OsStr {
1211 path.as_os_str()
1212 }
1213
1214 #[test]
1215 fn server_names_are_dns_names_or_ip_addresses() {
1216 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
1217 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
1218 assert!(dns("example.com"));
1219 assert!(dns("db.prod.svc.cluster.local"));
1220 assert!(ip("10.0.0.1"));
1221 assert!(ip("::1"));
1222 assert!(ip("[::1]"));
1223 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
1224 let err = parse_server_name(bad).unwrap_err();
1225 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
1226 }
1227 }
1228
1229 #[test]
1230 fn the_first_bundle_that_exists_is_read() {
1231 let dir = scratch("bundle");
1232 let bundle = dir.join("bundle.pem");
1233 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
1234 std::fs::write(&bundle, two).unwrap();
1235 let missing = dir.join("missing.pem");
1236 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
1237 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
1238 assert_eq!(roots.len(), 2);
1239 std::fs::remove_dir_all(dir).unwrap();
1240 }
1241
1242 #[test]
1243 fn ssl_cert_file_and_dir_replace_the_system_locations() {
1244 let dir = scratch("env");
1245 let file = dir.join("file.pem");
1246 std::fs::write(&file, ca_pem("from file")).unwrap();
1247 let certs = dir.join("certs");
1248 std::fs::create_dir(&certs).unwrap();
1249 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
1250 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
1251 std::fs::write(certs.join("README"), "not a certificate").unwrap();
1252 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
1254 let system = dir.join("system.pem");
1255 std::fs::write(&system, ca_pem("system")).unwrap();
1256 let bundles = [system.to_str().unwrap()];
1257
1258 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
1259 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
1260 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
1261 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
1262 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
1263 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
1264 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
1265
1266 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
1267 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1268 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
1269 std::fs::remove_dir_all(dir).unwrap();
1270 }
1271
1272 #[test]
1273 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
1274 let dir = scratch("dir");
1275 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
1276 let roots = load_roots(
1277 None,
1278 None,
1279 &["/nonexistent/bundle.crt"],
1280 dir.to_str().unwrap(),
1281 );
1282 assert_eq!(roots.unwrap().len(), 1);
1283
1284 let empty = scratch("empty");
1285 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
1286 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1287 assert!(err.to_string().contains("webpki-roots"), "{err}");
1288 std::fs::remove_dir_all(dir).unwrap();
1289 std::fs::remove_dir_all(empty).unwrap();
1290 }
1291
1292 #[test]
1293 fn this_machines_roots_load() {
1294 TlsConnector::with_system_roots().unwrap();
1296 }
1297
1298 #[cfg(feature = "webpki-roots")]
1299 #[test]
1300 fn mozillas_roots_are_compiled_in() {
1301 TlsConnector::with_webpki_roots();
1302 }
1303}