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