use std::future::Future; use std::marker::PhantomData; use std::pin::Pin; use std::rc::Rc; use std::task::{Context, Poll}; use std::{fmt, net}; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_rt::net::TcpStream; use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory}; use futures_core::ready; use futures_util::future::{ok, Ready}; use crate::body::MessageBody; use crate::cloneable::CloneableService; use crate::config::ServiceConfig; use crate::error::{DispatchError, Error, ParseError}; use crate::helpers::DataFactory; use crate::request::Request; use crate::response::Response; use super::codec::Codec; use super::dispatcher::Dispatcher; use super::{ExpectHandler, Message, UpgradeHandler}; /// `ServiceFactory` implementation for HTTP1 transport pub struct H1Service> { srv: S, cfg: ServiceConfig, expect: X, upgrade: Option, on_connect: Option Box>>, _t: PhantomData<(T, B)>, } impl H1Service where S: ServiceFactory, S::Error: Into, S::InitError: fmt::Debug, S::Response: Into>, B: MessageBody, { /// Create new `HttpService` instance with config. pub(crate) fn with_config>( cfg: ServiceConfig, service: F, ) -> Self { H1Service { cfg, srv: service.into_factory(), expect: ExpectHandler, upgrade: None, on_connect: None, _t: PhantomData, } } } impl H1Service where S: ServiceFactory, S::Error: Into, S::InitError: fmt::Debug, S::Response: Into>, B: MessageBody, X: ServiceFactory, X::Error: Into, X::InitError: fmt::Debug, U: ServiceFactory< Config = (), Request = (Request, Framed), Response = (), >, U::Error: fmt::Display, U::InitError: fmt::Debug, { /// Create simple tcp stream service pub fn tcp( self, ) -> impl ServiceFactory< Config = (), Request = TcpStream, Response = (), Error = DispatchError, InitError = (), > { pipeline_factory(|io: TcpStream| { let peer_addr = io.peer_addr().ok(); ok((io, peer_addr)) }) .and_then(self) } } #[cfg(feature = "openssl")] mod openssl { use super::*; use actix_tls::openssl::{Acceptor, SslAcceptor, SslStream}; use actix_tls::{openssl::HandshakeError, SslError}; impl H1Service, S, B, X, U> where S: ServiceFactory, S::Error: Into, S::InitError: fmt::Debug, S::Response: Into>, B: MessageBody, X: ServiceFactory, X::Error: Into, X::InitError: fmt::Debug, U: ServiceFactory< Config = (), Request = (Request, Framed, Codec>), Response = (), >, U::Error: fmt::Display, U::InitError: fmt::Debug, { /// Create openssl based service pub fn openssl( self, acceptor: SslAcceptor, ) -> impl ServiceFactory< Config = (), Request = TcpStream, Response = (), Error = SslError, DispatchError>, InitError = (), > { pipeline_factory( Acceptor::new(acceptor) .map_err(SslError::Ssl) .map_init_err(|_| panic!()), ) .and_then(|io: SslStream| { let peer_addr = io.get_ref().peer_addr().ok(); ok((io, peer_addr)) }) .and_then(self.map_err(SslError::Service)) } } } #[cfg(feature = "rustls")] mod rustls { use super::*; use actix_tls::rustls::{Acceptor, ServerConfig, TlsStream}; use actix_tls::SslError; use std::{fmt, io}; impl H1Service, S, B, X, U> where S: ServiceFactory, S::Error: Into, S::InitError: fmt::Debug, S::Response: Into>, B: MessageBody, X: ServiceFactory, X::Error: Into, X::InitError: fmt::Debug, U: ServiceFactory< Config = (), Request = (Request, Framed, Codec>), Response = (), >, U::Error: fmt::Display, U::InitError: fmt::Debug, { /// Create rustls based service pub fn rustls( self, config: ServerConfig, ) -> impl ServiceFactory< Config = (), Request = TcpStream, Response = (), Error = SslError, InitError = (), > { pipeline_factory( Acceptor::new(config) .map_err(SslError::Ssl) .map_init_err(|_| panic!()), ) .and_then(|io: TlsStream| { let peer_addr = io.get_ref().0.peer_addr().ok(); ok((io, peer_addr)) }) .and_then(self.map_err(SslError::Service)) } } } impl H1Service where S: ServiceFactory, S::Error: Into, S::Response: Into>, S::InitError: fmt::Debug, B: MessageBody, { pub fn expect(self, expect: X1) -> H1Service where X1: ServiceFactory, X1::Error: Into, X1::InitError: fmt::Debug, { H1Service { expect, cfg: self.cfg, srv: self.srv, upgrade: self.upgrade, on_connect: self.on_connect, _t: PhantomData, } } pub fn upgrade(self, upgrade: Option) -> H1Service where U1: ServiceFactory), Response = ()>, U1::Error: fmt::Display, U1::InitError: fmt::Debug, { H1Service { upgrade, cfg: self.cfg, srv: self.srv, expect: self.expect, on_connect: self.on_connect, _t: PhantomData, } } /// Set on connect callback. pub(crate) fn on_connect( mut self, f: Option Box>>, ) -> Self { self.on_connect = f; self } } impl ServiceFactory for H1Service where T: AsyncRead + AsyncWrite + Unpin, S: ServiceFactory, S::Error: Into, S::Response: Into>, S::InitError: fmt::Debug, B: MessageBody, X: ServiceFactory, X::Error: Into, X::InitError: fmt::Debug, U: ServiceFactory), Response = ()>, U::Error: fmt::Display, U::InitError: fmt::Debug, { type Config = (); type Request = (T, Option); type Response = (); type Error = DispatchError; type InitError = (); type Service = H1ServiceHandler; type Future = H1ServiceResponse; fn new_service(&self, _: ()) -> Self::Future { H1ServiceResponse { fut: self.srv.new_service(()), fut_ex: Some(self.expect.new_service(())), fut_upg: self.upgrade.as_ref().map(|f| f.new_service(())), expect: None, upgrade: None, on_connect: self.on_connect.clone(), cfg: Some(self.cfg.clone()), _t: PhantomData, } } } #[doc(hidden)] #[pin_project::pin_project] pub struct H1ServiceResponse where S: ServiceFactory, S::Error: Into, S::InitError: fmt::Debug, X: ServiceFactory, X::Error: Into, X::InitError: fmt::Debug, U: ServiceFactory), Response = ()>, U::Error: fmt::Display, U::InitError: fmt::Debug, { #[pin] fut: S::Future, #[pin] fut_ex: Option, #[pin] fut_upg: Option, expect: Option, upgrade: Option, on_connect: Option Box>>, cfg: Option, _t: PhantomData<(T, B)>, } impl Future for H1ServiceResponse where T: AsyncRead + AsyncWrite + Unpin, S: ServiceFactory, S::Error: Into, S::Response: Into>, S::InitError: fmt::Debug, B: MessageBody, X: ServiceFactory, X::Error: Into, X::InitError: fmt::Debug, U: ServiceFactory), Response = ()>, U::Error: fmt::Display, U::InitError: fmt::Debug, { type Output = Result, ()>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut this = self.as_mut().project(); if let Some(fut) = this.fut_ex.as_pin_mut() { let expect = ready!(fut .poll(cx) .map_err(|e| log::error!("Init http service error: {:?}", e)))?; this = self.as_mut().project(); *this.expect = Some(expect); this.fut_ex.set(None); } if let Some(fut) = this.fut_upg.as_pin_mut() { let upgrade = ready!(fut .poll(cx) .map_err(|e| log::error!("Init http service error: {:?}", e)))?; this = self.as_mut().project(); *this.upgrade = Some(upgrade); this.fut_ex.set(None); } let result = ready!(this .fut .poll(cx) .map_err(|e| log::error!("Init http service error: {:?}", e))); Poll::Ready(result.map(|service| { let this = self.as_mut().project(); H1ServiceHandler::new( this.cfg.take().unwrap(), service, this.expect.take().unwrap(), this.upgrade.take(), this.on_connect.clone(), ) })) } } /// `Service` implementation for HTTP1 transport pub struct H1ServiceHandler { srv: CloneableService, expect: CloneableService, upgrade: Option>, on_connect: Option Box>>, cfg: ServiceConfig, _t: PhantomData<(T, B)>, } impl H1ServiceHandler where S: Service, S::Error: Into, S::Response: Into>, B: MessageBody, X: Service, X::Error: Into, U: Service), Response = ()>, U::Error: fmt::Display, { fn new( cfg: ServiceConfig, srv: S, expect: X, upgrade: Option, on_connect: Option Box>>, ) -> H1ServiceHandler { H1ServiceHandler { srv: CloneableService::new(srv), expect: CloneableService::new(expect), upgrade: upgrade.map(CloneableService::new), cfg, on_connect, _t: PhantomData, } } } impl Service for H1ServiceHandler where T: AsyncRead + AsyncWrite + Unpin, S: Service, S::Error: Into, S::Response: Into>, B: MessageBody, X: Service, X::Error: Into, U: Service), Response = ()>, U::Error: fmt::Display, { type Request = (T, Option); type Response = (); type Error = DispatchError; type Future = Dispatcher; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { let ready = self .expect .poll_ready(cx) .map_err(|e| { let e = e.into(); log::error!("Http service readiness error: {:?}", e); DispatchError::Service(e) })? .is_ready(); let ready = self .srv .poll_ready(cx) .map_err(|e| { let e = e.into(); log::error!("Http service readiness error: {:?}", e); DispatchError::Service(e) })? .is_ready() && ready; if ready { Poll::Ready(Ok(())) } else { Poll::Pending } } fn call(&mut self, (io, addr): Self::Request) -> Self::Future { let on_connect = if let Some(ref on_connect) = self.on_connect { Some(on_connect(&io)) } else { None }; Dispatcher::new( io, self.cfg.clone(), self.srv.clone(), self.expect.clone(), self.upgrade.clone(), on_connect, addr, ) } } /// `ServiceFactory` implementation for `OneRequestService` service #[derive(Default)] pub struct OneRequest { config: ServiceConfig, _t: PhantomData, } impl OneRequest where T: AsyncRead + AsyncWrite + Unpin, { /// Create new `H1SimpleService` instance. pub fn new() -> Self { OneRequest { config: ServiceConfig::default(), _t: PhantomData, } } } impl ServiceFactory for OneRequest where T: AsyncRead + AsyncWrite + Unpin, { type Config = (); type Request = T; type Response = (Request, Framed); type Error = ParseError; type InitError = (); type Service = OneRequestService; type Future = Ready>; fn new_service(&self, _: ()) -> Self::Future { ok(OneRequestService { _t: PhantomData, config: self.config.clone(), }) } } /// `Service` implementation for HTTP1 transport. Reads one request and returns /// request and framed object. pub struct OneRequestService { _t: PhantomData, config: ServiceConfig, } impl Service for OneRequestService where T: AsyncRead + AsyncWrite + Unpin, { type Request = T; type Response = (Request, Framed); type Error = ParseError; type Future = OneRequestServiceResponse; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: Self::Request) -> Self::Future { OneRequestServiceResponse { framed: Some(Framed::new(req, Codec::new(self.config.clone()))), } } } #[doc(hidden)] pub struct OneRequestServiceResponse where T: AsyncRead + AsyncWrite + Unpin, { framed: Option>, } impl Future for OneRequestServiceResponse where T: AsyncRead + AsyncWrite + Unpin, { type Output = Result<(Request, Framed), ParseError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.framed.as_mut().unwrap().next_item(cx) { Poll::Ready(Some(Ok(req))) => match req { Message::Item(req) => { Poll::Ready(Ok((req, self.framed.take().unwrap()))) } Message::Chunk(_) => unreachable!("Something is wrong"), }, Poll::Ready(Some(Err(err))) => Poll::Ready(Err(err)), Poll::Ready(None) => Poll::Ready(Err(ParseError::Incomplete)), Poll::Pending => Poll::Pending, } } }