ntex_tls/
lib.rs

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