Skip to main content

ntex_tls/
lib.rs

1//! An implementations of SSL streams for ntex ecosystem
2#![deny(clippy::pedantic)]
3#![allow(
4    clippy::clone_on_copy,
5    clippy::missing_fields_in_debug,
6    clippy::must_use_candidate,
7    clippy::missing_errors_doc
8)]
9
10use std::sync::atomic::{AtomicUsize, Ordering};
11
12#[cfg(feature = "openssl")]
13pub mod openssl;
14
15#[cfg(feature = "rustls")]
16pub mod rustls;
17
18#[cfg(all(windows, feature = "schannel"))]
19pub mod schannel;
20
21use ntex_service::cfg::{CfgContext, Configuration};
22use ntex_util::{services::Counter, time::Millis, time::Seconds};
23
24/// Sets the maximum per-worker concurrent ssl connection establish process.
25///
26/// All listeners will stop accepting connections when this limit is
27/// reached. It can be used to limit the global SSL CPU usage.
28///
29/// By default max connections is set to a 256.
30pub fn max_concurrent_ssl_accept(num: usize) {
31    MAX_SSL_ACCEPT.store(num, Ordering::Relaxed);
32    MAX_SSL_ACCEPT_COUNTER.with(|counts| counts.set_capacity(num));
33}
34
35static MAX_SSL_ACCEPT: AtomicUsize = AtomicUsize::new(256);
36
37thread_local! {
38    static MAX_SSL_ACCEPT_COUNTER: Counter = Counter::new(MAX_SSL_ACCEPT.load(Ordering::Relaxed));
39}
40
41/// A TLS PSK identity.
42///
43/// Used in conjunction with [`ntex_io::Filter::query`]:
44#[derive(Clone, Debug, PartialEq, Eq, Hash)]
45pub struct PskIdentity(pub Vec<u8>);
46
47/// The TLS SNI server name (DNS).
48///
49/// Used in conjunction with [`ntex_io::Filter::query`]:
50#[derive(Clone, Debug, PartialEq, Eq, Hash)]
51pub struct Servername(pub String);
52
53#[derive(Debug)]
54/// Tls service configuration
55pub struct TlsConfig {
56    handshake_timeout: Millis,
57    config: CfgContext,
58}
59
60impl Default for TlsConfig {
61    fn default() -> Self {
62        TlsConfig::new()
63    }
64}
65
66impl Configuration for TlsConfig {
67    const NAME: &str = "TLS Configuration";
68
69    fn ctx(&self) -> &CfgContext {
70        &self.config
71    }
72
73    fn set_ctx(&mut self, ctx: CfgContext) {
74        self.config = ctx;
75    }
76}
77
78impl TlsConfig {
79    #[must_use]
80    /// Create instance of `TlsConfig`
81    pub fn new() -> Self {
82        TlsConfig {
83            handshake_timeout: Millis(5_000),
84            config: CfgContext::default(),
85        }
86    }
87
88    #[inline]
89    /// Get tls handshake timeout.
90    pub fn handshake_timeout(&self) -> Millis {
91        self.handshake_timeout
92    }
93
94    #[must_use]
95    /// Set tls handshake timeout.
96    ///
97    /// Defines a timeout for connection tls handshake negotiation.
98    /// To disable timeout set value to 0.
99    ///
100    /// By default handshake timeout is set to 5 seconds.
101    pub fn set_handshake_timeout<T: Into<Seconds>>(mut self, timeout: T) -> Self {
102        self.handshake_timeout = timeout.into().into();
103        self
104    }
105}