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::missing_fields_in_debug,
5    clippy::must_use_candidate,
6    clippy::missing_errors_doc,
7    clippy::struct_field_names
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, Clone)]
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    #[allow(clippy::new_without_default)]
78    /// Create instance of `TlsConfig`
79    pub fn new() -> Self {
80        TlsConfig {
81            handshake_timeout: Millis(5_000),
82            config: CfgContext::default(),
83        }
84    }
85
86    #[inline]
87    /// Get tls handshake timeout.
88    pub fn handshake_timeout(&self) -> Millis {
89        self.handshake_timeout
90    }
91
92    #[must_use]
93    /// Set tls handshake timeout.
94    ///
95    /// Defines a timeout for connection tls handshake negotiation.
96    /// To disable timeout set value to 0.
97    ///
98    /// By default handshake timeout is set to 5 seconds.
99    pub fn set_handshake_timeout<T: Into<Seconds>>(mut self, timeout: T) -> Self {
100        self.handshake_timeout = timeout.into().into();
101        self
102    }
103}