Skip to main content

ntex_tls/rustls/
server.rs

1//! Server-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 ntex_util::time::Millis;
6use tls_rustls::{ServerConfig, ServerConnection};
7
8use crate::{Servername, rustls::Stream};
9
10#[derive(Debug)]
11/// Encrypts and decrypts a server connection using rustls.
12///
13/// Construct through [`Self::create`] or [`super::TlsAcceptor`]. In addition to
14/// the shared TLS metadata, the filter exposes the client's SNI as
15/// [`Servername`]. Shutdown exchanges `close_notify`, accepting transport EOF
16/// when the peer has already disconnected.
17pub struct TlsServerFilter {
18    /// Single-threaded session; mutable access is scoped to `stream` calls.
19    session: RefCell<ServerConnection>,
20}
21
22impl FilterLayer for TlsServerFilter {
23    /// Returns `None` while the session is busy, for example when a
24    /// certificate resolver queries its own connection during the handshake.
25    fn query(&self, id: any::TypeId) -> Option<Box<dyn any::Any>> {
26        let mut session = self.session.try_borrow_mut().ok()?;
27        if id == any::TypeId::of::<Servername>() {
28            let name = session.server_name()?;
29            Some(Box::new(Servername(name.to_string())))
30        } else {
31            Stream::new(&mut *session).query(id)
32        }
33    }
34
35    /// Decrypts input, releasing the session borrow before a peer-close notification can reenter.
36    fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
37        let mut peer_closed = false;
38        let result = self.stream(|s| s.process_read_buf(buf, &mut peer_closed));
39        // Release the session before closing: the read-task waker may reenter.
40        if peer_closed {
41            buf.io().close();
42        }
43        result
44    }
45
46    fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
47        self.stream(|s| s.process_write_buf(buf))
48    }
49
50    fn shutdown(&self, buf: &FilterBuf<'_>) -> io::Result<Poll<()>> {
51        self.stream(|s| s.shutdown(buf))
52    }
53}
54
55impl TlsServerFilter {
56    /// Installs a server filter and completes the handshake within `timeout`.
57    ///
58    /// Zero disables the deadline. The timeout is supplied directly, not read
59    /// from [`crate::TlsConfig`], and this constructor does not acquire an
60    /// acceptor-capacity slot. Existing filters remain below TLS.
61    ///
62    /// The session's buffering limit is initialized from the I/O write-page
63    /// capacity; certificates and client authentication follow `cfg`.
64    ///
65    /// # Errors
66    ///
67    /// Returns [`io::ErrorKind::TimedOut`] on expiration, or an error from
68    /// session creation, negotiation, or transport I/O. Premature transport EOF
69    /// returns [`io::ErrorKind::UnexpectedEof`].
70    pub fn create<F: Filter>(
71        io: Io<F>,
72        cfg: Arc<ServerConfig>,
73        timeout: Millis,
74    ) -> impl Future<Output = Result<Io<Layer<TlsServerFilter, F>>, io::Error>> {
75        crate::utils::with_timeout(timeout, async move {
76            log::trace!("{}: Initiate server connection", io.tag());
77
78            let mut session = ServerConnection::new(cfg).map_err(io::Error::other)?;
79            session.set_buffer_limit(Some(io.cfg().write_size().capacity()));
80            let io = io.add_filter(TlsServerFilter {
81                session: RefCell::new(session),
82            });
83
84            crate::utils::handshake(&io, || Ok(io.filter().is_handshaking())).await?;
85            log::trace!("{}: TLS Handshake succeeded", io.tag());
86            Ok(io)
87        })
88    }
89
90    /// Observes handshake completion outside any mutable session borrow.
91    fn is_handshaking(&self) -> bool {
92        self.session.borrow().is_handshaking()
93    }
94
95    /// Gives `f` exclusive access to the session through the shared stream adapter.
96    ///
97    /// The callback must not reenter this filter or trigger a notification that
98    /// does so while the session is borrowed; reentrant I/O operations panic.
99    pub(super) fn stream<F, R>(&self, f: F) -> R
100    where
101        F: FnOnce(&mut Stream<'_, ServerConnection>) -> R,
102    {
103        #[cfg(test)]
104        let _borrow = crate::utils::testing::TlsBorrow::new();
105
106        let mut session = self.session.borrow_mut();
107        f(&mut Stream::new(&mut *session))
108    }
109}