1
0
mirror of https://github.com/fafhrd91/actix-net synced 2024-11-24 00:01:11 +01:00

move rustls and nativetls acceptor services to actix-tls

This commit is contained in:
Nikolay Kim 2019-12-05 20:52:37 +06:00
parent 3a858feaec
commit b18fbc98d5
7 changed files with 155 additions and 203 deletions

View File

@ -1,42 +0,0 @@
//! SSL Services
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::counter::Counter;
#[cfg(feature = "openssl")]
mod openssl;
#[cfg(feature = "openssl")]
pub use self::openssl::OpensslAcceptor;
#[cfg(feature = "nativetls")]
mod nativetls;
#[cfg(feature = "nativetls")]
pub use self::nativetls::NativeTlsAcceptor;
#[cfg(feature = "rustls")]
mod rustls;
#[cfg(feature = "rustls")]
pub use self::rustls::RustlsAcceptor;
/// Sets the maximum per-worker concurrent ssl connection establish process.
///
/// All listeners will stop accepting connections when this limit is
/// reached. It can be used to limit the global SSL CPU usage.
///
/// By default max connections is set to a 256.
pub fn max_concurrent_ssl_connect(num: usize) {
MAX_CONN.store(num, Ordering::Relaxed);
}
pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
thread_local! {
static MAX_CONN_COUNTER: Counter = Counter::new(MAX_CONN.load(Ordering::Relaxed));
}
/// Ssl error combinded with service error.
#[derive(Debug)]
pub enum SslError<E1, E2> {
Ssl(E1),
Service(E2),
}

View File

@ -1,124 +0,0 @@
use std::future::Future;
use std::io;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_service::{Service, ServiceFactory};
use futures::future::{ok, Ready};
use rust_tls::ServerConfig;
use tokio_rustls::{server::TlsStream, Accept, TlsAcceptor};
use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::{Io, Protocol, ServerConfig as SrvConfig};
/// Support `SSL` connections via rustls package
///
/// `rust-tls` feature enables `RustlsAcceptor` type
pub struct RustlsAcceptor<T, P = ()> {
config: Arc<ServerConfig>,
io: PhantomData<(T, P)>,
}
impl<T: AsyncRead + AsyncWrite, P> RustlsAcceptor<T, P> {
/// Create `RustlsAcceptor` new service
pub fn new(config: ServerConfig) -> Self {
RustlsAcceptor {
config: Arc::new(config),
io: PhantomData,
}
}
}
impl<T, P> Clone for RustlsAcceptor<T, P> {
fn clone(&self) -> Self {
Self {
config: self.config.clone(),
io: PhantomData,
}
}
}
impl<T: AsyncRead + AsyncWrite + Unpin, P> ServiceFactory for RustlsAcceptor<T, P> {
type Request = Io<T, P>;
type Response = Io<TlsStream<T>, P>;
type Error = io::Error;
type Config = SrvConfig;
type Service = RustlsAcceptorService<T, P>;
type InitError = ();
type Future = Ready<Result<Self::Service, Self::InitError>>;
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
cfg.set_secure();
MAX_CONN_COUNTER.with(|conns| {
ok(RustlsAcceptorService {
acceptor: self.config.clone().into(),
conns: conns.clone(),
io: PhantomData,
})
})
}
}
pub struct RustlsAcceptorService<T, P> {
acceptor: TlsAcceptor,
io: PhantomData<(T, P)>,
conns: Counter,
}
impl<T: AsyncRead + AsyncWrite + Unpin, P> Service for RustlsAcceptorService<T, P> {
type Request = Io<T, P>;
type Response = Io<TlsStream<T>, P>;
type Error = io::Error;
type Future = RustlsAcceptorServiceFut<T, P>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
if self.conns.available(cx) {
Poll::Ready(Ok(()))
} else {
Poll::Pending
}
}
fn call(&mut self, req: Self::Request) -> Self::Future {
let (io, params, _) = req.into_parts();
RustlsAcceptorServiceFut {
_guard: self.conns.get(),
fut: self.acceptor.accept(io),
params: Some(params),
}
}
}
pub struct RustlsAcceptorServiceFut<T, P>
where
T: AsyncRead + AsyncWrite + Unpin,
{
fut: Accept<T>,
params: Option<P>,
_guard: CounterGuard,
}
impl<T: AsyncRead + AsyncWrite + Unpin, P> Unpin for RustlsAcceptorServiceFut<T, P> {}
impl<T: AsyncRead + AsyncWrite + Unpin, P> Future for RustlsAcceptorServiceFut<T, P> {
type Output = Result<Io<TlsStream<T>, P>, io::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let this = self.get_mut();
let res = futures::ready!(Pin::new(&mut this.fut).poll(cx));
match res {
Ok(io) => {
let params = this.params.take().unwrap();
Poll::Ready(Ok(Io::from_parts(io, params, Protocol::Unknown)))
}
Err(e) => Poll::Ready(Err(e)),
}
}
}

View File

@ -8,6 +8,8 @@
* Enable rustls acceptor service
* Enable native-tls acceptor service
## [1.0.0-alpha.1] - 2019-12-02
* Split openssl accetor from actix-server package

View File

@ -13,7 +13,7 @@ edition = "2018"
workspace = ".."
[package.metadata.docs.rs]
features = ["openssl", "rustls"]
features = ["openssl", "rustls", "nativetls"]
[lib]
name = "actix_tls"
@ -28,6 +28,9 @@ openssl = ["open-ssl", "tokio-openssl"]
# rustls
rustls = ["rust-tls", "webpki"]
# nativetls
nativetls = ["native-tls", "tokio-tls"]
[dependencies]
actix-service = "1.0.0-alpha.3"
actix-codec = "0.2.0-alpha.3"
@ -48,6 +51,10 @@ webpki = { version = "0.21", optional = true }
webpki-roots = { version = "0.17", optional = true }
tokio-rustls = { version = "0.12.0", optional = true }
# native-tls
native-tls = { version="0.2", optional = true }
tokio-tls = { version="0.3", optional = true }
[dev-dependencies]
bytes = "0.5"
actix-testing = { version="1.0.0-alpha.3" }

View File

@ -9,10 +9,11 @@ use actix_utils::counter::Counter;
#[cfg(feature = "openssl")]
pub mod openssl;
//#[cfg(feature = "rustls")]
//mod rustls;
//#[cfg(feature = "rustls")]
//pub use self::rustls::RustlsAcceptor;
#[cfg(feature = "rustls")]
pub mod rustls;
#[cfg(feature = "nativetls")]
pub mod nativetls;
/// Sets the maximum per-worker concurrent ssl connection establish process.
///

View File

@ -1,26 +1,24 @@
use std::convert::Infallible;
use std::marker::PhantomData;
use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_service::{Service, ServiceFactory};
use futures::future::{self, FutureExt as _, LocalBoxFuture, TryFutureExt as _};
use native_tls::Error;
use tokio_tls::{TlsAcceptor, TlsStream};
use actix_utils::counter::Counter;
use futures::future::{self, FutureExt, LocalBoxFuture, TryFutureExt};
pub use native_tls::Error;
pub use tokio_tls::{TlsAcceptor, TlsStream};
use crate::counter::Counter;
use crate::ssl::MAX_CONN_COUNTER;
use crate::{Io, ServerConfig};
use crate::MAX_CONN_COUNTER;
/// Support `SSL` connections via native-tls package
///
/// `tls` feature enables `NativeTlsAcceptor` type
pub struct NativeTlsAcceptor<T, P = ()> {
pub struct NativeTlsAcceptor<T> {
acceptor: TlsAcceptor,
io: PhantomData<(T, P)>,
io: PhantomData<T>,
}
impl<T, P> NativeTlsAcceptor<T, P>
impl<T> NativeTlsAcceptor<T>
where
T: AsyncRead + AsyncWrite + Unpin,
{
@ -34,7 +32,7 @@ where
}
}
impl<T, P> Clone for NativeTlsAcceptor<T, P> {
impl<T> Clone for NativeTlsAcceptor<T> {
#[inline]
fn clone(&self) -> Self {
Self {
@ -44,23 +42,20 @@ impl<T, P> Clone for NativeTlsAcceptor<T, P> {
}
}
impl<T, P> ServiceFactory for NativeTlsAcceptor<T, P>
impl<T> ServiceFactory for NativeTlsAcceptor<T>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,
P: 'static,
{
type Request = Io<T, P>;
type Response = Io<TlsStream<T>, P>;
type Request = T;
type Response = TlsStream<T>;
type Error = Error;
type Service = NativeTlsAcceptorService<T>;
type Config = ServerConfig;
type Service = NativeTlsAcceptorService<T, P>;
type InitError = Infallible;
type Config = ();
type InitError = ();
type Future = future::Ready<Result<Self::Service, Self::InitError>>;
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
cfg.set_secure();
fn new_service(&self, _: ()) -> Self::Future {
MAX_CONN_COUNTER.with(|conns| {
future::ok(NativeTlsAcceptorService {
acceptor: self.acceptor.clone(),
@ -71,13 +66,13 @@ where
}
}
pub struct NativeTlsAcceptorService<T, P> {
pub struct NativeTlsAcceptorService<T> {
acceptor: TlsAcceptor,
io: PhantomData<(T, P)>,
io: PhantomData<T>,
conns: Counter,
}
impl<T, P> Clone for NativeTlsAcceptorService<T, P> {
impl<T> Clone for NativeTlsAcceptorService<T> {
fn clone(&self) -> Self {
Self {
acceptor: self.acceptor.clone(),
@ -87,15 +82,14 @@ impl<T, P> Clone for NativeTlsAcceptorService<T, P> {
}
}
impl<T, P> Service for NativeTlsAcceptorService<T, P>
impl<T> Service for NativeTlsAcceptorService<T>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,
P: 'static,
{
type Request = Io<T, P>;
type Response = Io<TlsStream<T>, P>;
type Request = T;
type Response = TlsStream<T>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Io<TlsStream<T>, P>, Error>>;
type Future = LocalBoxFuture<'static, Result<TlsStream<T>, Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.conns.available(cx) {
@ -108,9 +102,7 @@ where
fn call(&mut self, req: Self::Request) -> Self::Future {
let guard = self.conns.get();
let this = self.clone();
let (io, params, proto) = req.into_parts();
async move { this.acceptor.accept(io).await }
.map_ok(move |stream| Io::from_parts(stream, params, proto))
async move { this.acceptor.accept(req).await }
.map_ok(move |io| {
// Required to preserve `CounterGuard` until `Self::Future`
// is completely resolved.

116
actix-tls/src/rustls.rs Normal file
View File

@ -0,0 +1,116 @@
use std::future::Future;
use std::io;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_service::{Service, ServiceFactory};
use actix_utils::counter::{Counter, CounterGuard};
use futures::future::{ok, Ready};
use tokio_rustls::{Accept, TlsAcceptor};
pub use rust_tls::ServerConfig;
pub use tokio_rustls::server::TlsStream;
use crate::MAX_CONN_COUNTER;
/// Support `SSL` connections via rustls package
///
/// `rust-tls` feature enables `RustlsAcceptor` type
pub struct Acceptor<T> {
config: Arc<ServerConfig>,
io: PhantomData<T>,
}
impl<T: AsyncRead + AsyncWrite> Acceptor<T> {
/// Create rustls based `Acceptor` service factory
pub fn new(config: ServerConfig) -> Self {
Acceptor {
config: Arc::new(config),
io: PhantomData,
}
}
}
impl<T> Clone for Acceptor<T> {
fn clone(&self) -> Self {
Self {
config: self.config.clone(),
io: PhantomData,
}
}
}
impl<T: AsyncRead + AsyncWrite + Unpin> ServiceFactory for Acceptor<T> {
type Request = T;
type Response = TlsStream<T>;
type Error = io::Error;
type Service = AcceptorService<T>;
type Config = ();
type InitError = ();
type Future = Ready<Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
MAX_CONN_COUNTER.with(|conns| {
ok(AcceptorService {
acceptor: self.config.clone().into(),
conns: conns.clone(),
io: PhantomData,
})
})
}
}
/// RusTLS based `Acceptor` service
pub struct AcceptorService<T> {
acceptor: TlsAcceptor,
io: PhantomData<T>,
conns: Counter,
}
impl<T: AsyncRead + AsyncWrite + Unpin> Service for AcceptorService<T> {
type Request = T;
type Response = TlsStream<T>;
type Error = io::Error;
type Future = AcceptorServiceFut<T>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.conns.available(cx) {
Poll::Ready(Ok(()))
} else {
Poll::Pending
}
}
fn call(&mut self, req: Self::Request) -> Self::Future {
AcceptorServiceFut {
_guard: self.conns.get(),
fut: self.acceptor.accept(req),
}
}
}
pub struct AcceptorServiceFut<T>
where
T: AsyncRead + AsyncWrite + Unpin,
{
fut: Accept<T>,
_guard: CounterGuard,
}
impl<T: AsyncRead + AsyncWrite + Unpin> Future for AcceptorServiceFut<T> {
type Output = Result<TlsStream<T>, io::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let res = futures::ready!(Pin::new(&mut this.fut).poll(cx));
match res {
Ok(io) => Poll::Ready(Ok(io)),
Err(e) => Poll::Ready(Err(e)),
}
}
}