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    clippy::unused_async_trait_impl
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_util::services::Counter;
22
23mod config;
24mod types;
25mod utils;
26
27pub use self::config::TlsConfig;
28pub use self::types::{PeerCertChainDer, PeerCertDer, PskIdentity, Servername};
29
30/// Sets the maximum per-worker concurrent ssl connection establish process.
31///
32/// All listeners will stop accepting connections when this limit is
33/// reached. It can be used to limit the global SSL CPU usage.
34///
35/// By default max connections is set to a 256.
36pub fn max_concurrent_ssl_accept(num: usize) {
37    MAX_SSL_ACCEPT.store(num, Ordering::Relaxed);
38    MAX_SSL_ACCEPT_COUNTER.with(|counts| counts.set_capacity(num));
39}
40
41static MAX_SSL_ACCEPT: AtomicUsize = AtomicUsize::new(256);
42
43thread_local! {
44    static MAX_SSL_ACCEPT_COUNTER: Counter = Counter::new(MAX_SSL_ACCEPT.load(Ordering::Relaxed));
45}
46
47/// Ssl error combinded with service error.
48#[derive(Debug)]
49pub enum TlsError<E> {
50    Tls(std::io::Error),
51    Service(E),
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn max_concurrent_accept() {
60        // the default value, other tests use the limit
61        max_concurrent_ssl_accept(256);
62        assert_eq!(MAX_SSL_ACCEPT.load(Ordering::Relaxed), 256);
63        MAX_SSL_ACCEPT_COUNTER.with(|c| {
64            let _guards: Vec<_> = (0..255).map(|_| c.get()).collect();
65            assert!(c.is_available());
66            let _last = c.get();
67            assert!(!c.is_available());
68        });
69    }
70}