Skip to main content

ntex_tls/rustls/
accept.rs

1//! Server handshake service with shared per-thread capacity and an I/O-configured timeout.
2use std::{io, sync::Arc};
3
4use ntex_io::{Filter, Io, Layer};
5use ntex_service::{BindCtx, Ctx, Service, cfg::Cfg, cfg::Configuration};
6use ntex_util::services::Counter;
7use tls_rustls::ServerConfig;
8
9use crate::{MAX_SSL_ACCEPT_COUNTER, TlsConfig, rustls::TlsServerFilter};
10
11#[derive(Debug)]
12/// Upgrades existing I/O connections to server-side TLS using rustls.
13///
14/// Reads [`TlsConfig`] from each connection's configuration. Readiness observes
15/// the shared per-thread soft limit set by [`crate::max_concurrent_ssl_accept`];
16/// it does not reserve a handshake slot. Calling the service holds a slot until
17/// the handshake completes, fails, times out, or is cancelled.
18///
19/// Existing I/O filters remain below the returned [`TlsServerFilter`].
20pub struct TlsAcceptor {
21    /// Shared certificate, protocol, and client-authentication policy.
22    cfg: Arc<ServerConfig>,
23    /// Thread-local handshake counter also used by other backend acceptors.
24    conns: Counter,
25}
26
27impl TlsAcceptor {
28    /// Creates an acceptor using the supplied rustls server configuration.
29    ///
30    /// Captures the current thread's handshake counter; the timeout is resolved
31    /// separately for each accepted connection.
32    pub fn new(cfg: Arc<ServerConfig>) -> Self {
33        MAX_SSL_ACCEPT_COUNTER.with(|conns| TlsAcceptor {
34            cfg,
35            conns: conns.clone(),
36        })
37    }
38}
39
40impl From<ServerConfig> for TlsAcceptor {
41    fn from(cfg: ServerConfig) -> Self {
42        Self::new(Arc::new(cfg))
43    }
44}
45
46impl<F: Filter, St> Service<St, Io<F>> for TlsAcceptor {
47    type Res = Io<Layer<TlsServerFilter, F>>;
48    type Error = io::Error;
49
50    /// Registers capacity-change notifications with the service readiness scope.
51    fn bind(&self, ctx: BindCtx<'_>) {
52        self.conns.bind(&ctx);
53    }
54
55    /// Waits for spare capacity without reserving it.
56    async fn ready(&self, _: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
57        if !self.conns.is_available() {
58            self.conns.available().await;
59        }
60        Ok(())
61    }
62
63    /// Counts this handshake and applies the timeout from the connection's registry.
64    async fn call(&self, io: Io<F>, _: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
65        let _guard = self.conns.get();
66        let cfg: Cfg<TlsConfig> = io.cfg().ctx().get();
67        super::TlsServerFilter::create(io, self.cfg.clone(), cfg.handshake_timeout()).await
68    }
69}