ntex_tls/rustls/client.rs
1//! Client-side rustls session ownership and filter integration.
2use std::{any, cell::RefCell, io, sync::Arc, task::Poll};
3
4use ntex_io::{Filter, FilterBuf, FilterLayer, Io, Layer};
5use tls_rustls::{ClientConfig, ClientConnection, pki_types::ServerName};
6
7use super::stream::Stream;
8
9#[derive(Debug)]
10/// Encrypts and decrypts a client connection using rustls.
11///
12/// Construct through [`Self::create`] or [`super::TlsConnector`]. The filter
13/// exposes the metadata described in the [`super`] module and exchanges
14/// `close_notify` during shutdown, accepting transport EOF if the peer has
15/// already disconnected.
16pub struct TlsClientFilter {
17 /// Single-threaded session; mutable access is scoped to `stream` calls.
18 session: RefCell<ClientConnection>,
19}
20
21impl FilterLayer for TlsClientFilter {
22 /// Returns `None` while the session is busy, for example when a
23 /// certificate verifier queries its own connection during the handshake.
24 fn query(&self, id: any::TypeId) -> Option<Box<dyn any::Any>> {
25 let mut session = self.session.try_borrow_mut().ok()?;
26 Stream::new(&mut *session).query(id)
27 }
28
29 /// Decrypts input, releasing the session borrow before a peer-close notification can reenter.
30 fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
31 let mut peer_closed = false;
32 let result = self.stream(|s| s.process_read_buf(buf, &mut peer_closed));
33 // Release the session before closing: the read-task waker may reenter.
34 if peer_closed {
35 buf.io().close();
36 }
37 result
38 }
39
40 fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
41 self.stream(|s| s.process_write_buf(buf))
42 }
43
44 fn shutdown(&self, buf: &FilterBuf<'_>) -> io::Result<Poll<()>> {
45 self.stream(|s| s.shutdown(buf))
46 }
47}
48
49impl TlsClientFilter {
50 /// Installs a client filter and drives its handshake to completion.
51 ///
52 /// `domain` supplies the name used by rustls verification and, for DNS names,
53 /// SNI according to `cfg`. Existing filters are preserved. The session's
54 /// buffering limit is initialized from the I/O write-page capacity.
55 ///
56 /// No handshake timeout or concurrency limit is applied here. Use
57 /// [`super::TlsConnector`] for the service-configured timeout.
58 ///
59 /// # Errors
60 ///
61 /// Returns an error if session creation, certificate verification, protocol
62 /// negotiation, or transport I/O fails. An incomplete handshake followed by
63 /// transport EOF returns [`io::ErrorKind::UnexpectedEof`].
64 pub async fn create<F: Filter>(
65 io: Io<F>,
66 cfg: Arc<ClientConfig>,
67 domain: ServerName<'static>,
68 ) -> Result<Io<Layer<TlsClientFilter, F>>, io::Error> {
69 let mut session = ClientConnection::new(cfg, domain).map_err(io::Error::other)?;
70 session.set_buffer_limit(Some(io.cfg().write_size().capacity()));
71 let io = io.add_filter(TlsClientFilter {
72 session: RefCell::new(session),
73 });
74
75 crate::utils::handshake(&io, || Ok(io.filter().is_handshaking())).await?;
76 Ok(io)
77 }
78
79 /// Observes handshake completion outside any mutable session borrow.
80 fn is_handshaking(&self) -> bool {
81 self.session.borrow().is_handshaking()
82 }
83
84 /// Gives `f` exclusive access to the session through the shared stream adapter.
85 ///
86 /// The callback must not reenter this filter or trigger a notification that
87 /// does so while the session is borrowed; reentrant I/O operations panic.
88 pub(super) fn stream<F, R>(&self, f: F) -> R
89 where
90 F: FnOnce(&mut Stream<'_, ClientConnection>) -> R,
91 {
92 #[cfg(test)]
93 let _borrow = crate::utils::testing::TlsBorrow::new();
94
95 let mut session = self.session.borrow_mut();
96 f(&mut Stream::new(&mut *session))
97 }
98}