1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-10-11 20:51:58 +00:00
actix-web/src/server.rs

325 lines
10 KiB
Rust
Raw Normal View History

use std::{io, net};
2017-10-07 04:48:14 +00:00
use std::rc::Rc;
use std::net::SocketAddr;
use std::marker::PhantomData;
2017-10-07 04:48:14 +00:00
use actix::dev::*;
use futures::Stream;
2017-12-08 17:24:05 +00:00
use http::HttpTryFrom;
use http::header::HeaderValue;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_core::net::{TcpListener, TcpStream};
2017-10-07 04:48:14 +00:00
#[cfg(feature="tls")]
use futures::Future;
#[cfg(feature="tls")]
use native_tls::TlsAcceptor;
#[cfg(feature="tls")]
use tokio_tls::{TlsStream, TlsAcceptorExt};
2017-11-04 20:24:57 +00:00
#[cfg(feature="alpn")]
use futures::Future;
#[cfg(feature="alpn")]
use openssl::ssl::{SslMethod, SslAcceptorBuilder};
#[cfg(feature="alpn")]
use openssl::pkcs12::ParsedPkcs12;
#[cfg(feature="alpn")]
use tokio_openssl::{SslStream, SslAcceptorExt};
2017-12-06 19:00:39 +00:00
use channel::{HttpChannel, HttpHandler, IntoHttpHandler};
2017-10-22 01:54:24 +00:00
2017-12-08 06:54:44 +00:00
/// Various server settings
2017-12-08 17:24:05 +00:00
#[derive(Debug, Clone)]
pub struct ServerSettings {
2017-12-08 06:54:44 +00:00
addr: Option<SocketAddr>,
secure: bool,
2017-12-08 17:24:05 +00:00
host: Option<HeaderValue>,
2017-12-08 06:54:44 +00:00
}
2017-12-08 17:24:05 +00:00
impl ServerSettings {
2017-12-08 06:54:44 +00:00
/// Crate server settings instance
2017-12-08 17:24:05 +00:00
fn new(addr: Option<SocketAddr>, secure: bool) -> Self {
let host = if let Some(ref addr) = addr {
HeaderValue::try_from(format!("{}", addr).as_str()).ok()
} else {
None
};
ServerSettings {
addr: addr,
secure: secure,
host: host,
}
2017-12-08 06:54:44 +00:00
}
/// Returns the socket address of the local half of this TCP connection
pub fn local_addr(&self) -> Option<SocketAddr> {
2017-12-08 17:24:05 +00:00
self.addr
2017-12-08 06:54:44 +00:00
}
/// Returns true if connection is secure(https)
pub fn secure(&self) -> bool {
2017-12-08 17:24:05 +00:00
self.secure
2017-12-08 06:54:44 +00:00
}
2017-12-08 17:24:05 +00:00
/// Returns host header value
pub fn host(&self) -> Option<&HeaderValue> {
self.host.as_ref()
2017-12-08 06:54:44 +00:00
}
}
2017-10-08 21:56:51 +00:00
/// An HTTP Server
///
/// `T` - async stream, anything that implements `AsyncRead` + `AsyncWrite`.
///
/// `A` - peer address
2017-10-22 01:54:24 +00:00
///
/// `H` - request handler
pub struct HttpServer<T, A, H> {
2017-12-08 17:24:05 +00:00
h: Rc<Vec<H>>,
io: PhantomData<T>,
addr: PhantomData<A>,
2017-10-07 04:48:14 +00:00
}
2017-10-22 01:54:24 +00:00
impl<T: 'static, A: 'static, H: 'static> Actor for HttpServer<T, A, H> {
2017-10-07 04:48:14 +00:00
type Context = Context<Self>;
}
2017-10-22 01:54:24 +00:00
impl<T, A, H> HttpServer<T, A, H> where H: HttpHandler
{
/// Create new http server with vec of http handlers
2017-12-06 19:00:39 +00:00
pub fn new<V, U: IntoIterator<Item=V>>(handler: U) -> Self
where V: IntoHttpHandler<Handler=H>
{
let apps: Vec<_> = handler.into_iter().map(|h| h.into_handler()).collect();
2017-10-22 01:54:24 +00:00
2017-12-08 17:24:05 +00:00
HttpServer{ h: Rc::new(apps),
2017-10-22 01:54:24 +00:00
io: PhantomData,
2017-12-08 17:24:05 +00:00
addr: PhantomData }
2017-10-07 04:48:14 +00:00
}
}
2017-10-22 01:54:24 +00:00
impl<T, A, H> HttpServer<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
2017-10-22 01:54:24 +00:00
A: 'static,
H: HttpHandler,
{
/// Start listening for incomming connections from stream.
2017-12-08 06:54:44 +00:00
pub fn serve_incoming<S, Addr>(mut self, stream: S, secure: bool) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: Stream<Item=(T, A), Error=io::Error> + 'static
{
2017-12-08 17:24:05 +00:00
// set server settings
2017-12-08 06:54:44 +00:00
let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
2017-12-08 17:24:05 +00:00
let settings = ServerSettings::new(Some(addr), secure);
for h in Rc::get_mut(&mut self.h).unwrap().iter_mut() {
h.server_settings(settings.clone());
}
2017-12-08 06:54:44 +00:00
2017-12-08 17:24:05 +00:00
// start server
Ok(HttpServer::create(move |ctx| {
ctx.add_stream(stream.map(
2017-12-08 17:24:05 +00:00
move |(t, _)| IoStream{io: t, peer: None, http2: false}));
self
}))
}
2017-10-07 04:48:14 +00:00
fn bind<S: net::ToSocketAddrs>(&self, addr: S)
-> io::Result<Vec<(net::SocketAddr, TcpListener)>>
2017-10-07 04:48:14 +00:00
{
2017-10-15 21:53:03 +00:00
let mut err = None;
let mut addrs = Vec::new();
2017-10-16 08:19:23 +00:00
if let Ok(iter) = addr.to_socket_addrs() {
2017-10-15 21:53:03 +00:00
for addr in iter {
match TcpListener::bind(&addr, Arbiter::handle()) {
2017-10-27 06:14:33 +00:00
Ok(tcp) => addrs.push((addr, tcp)),
2017-10-15 21:53:03 +00:00
Err(e) => err = Some(e),
}
}
}
if addrs.is_empty() {
if let Some(e) = err.take() {
Err(e)
} else {
Err(io::Error::new(io::ErrorKind::Other, "Can not bind to address."))
}
} else {
Ok(addrs)
2017-10-15 21:53:03 +00:00
}
2017-10-07 04:48:14 +00:00
}
}
impl<H: HttpHandler> HttpServer<TcpStream, net::SocketAddr, H> {
/// Start listening for incomming connections.
///
/// This methods converts address to list of `SocketAddr`
/// then binds to all available addresses.
2017-12-08 06:54:44 +00:00
pub fn serve<S, Addr>(mut self, addr: S) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{
let addrs = self.bind(addr)?;
2017-12-08 17:24:05 +00:00
// set server settings
let settings = ServerSettings::new(Some(addrs[0].0), false);
for h in Rc::get_mut(&mut self.h).unwrap().iter_mut() {
h.server_settings(settings.clone());
}
// start server
Ok(HttpServer::create(move |ctx| {
for (addr, tcp) in addrs {
info!("Starting http server on {}", addr);
2017-12-08 17:24:05 +00:00
ctx.add_stream(tcp.incoming().map(
2017-12-08 17:24:05 +00:00
move |(t, a)| IoStream{io: t, peer: Some(a), http2: false}));
}
self
}))
}
}
#[cfg(feature="tls")]
impl<H: HttpHandler> HttpServer<TlsStream<TcpStream>, net::SocketAddr, H> {
/// Start listening for incomming tls connections.
///
/// This methods converts address to list of `SocketAddr`
/// then binds to all available addresses.
2017-12-08 06:54:44 +00:00
pub fn serve_tls<S, Addr>(mut self, addr: S, pkcs12: ::Pkcs12) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{
let addrs = self.bind(addr)?;
2017-12-08 17:24:05 +00:00
// set server settings
let settings = ServerSettings::new(Some(addrs[0].0), true);
for h in Rc::get_mut(&mut self.h).unwrap().iter_mut() {
h.server_settings(settings.clone());
}
2017-12-08 06:54:44 +00:00
let acceptor = match TlsAcceptor::builder(pkcs12) {
Ok(builder) => {
match builder.build() {
Ok(acceptor) => Rc::new(acceptor),
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
}
}
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
};
2017-12-08 17:24:05 +00:00
// start server
Ok(HttpServer::create(move |ctx| {
for (srv, tcp) in addrs {
info!("Starting tls http server on {}", srv);
let acc = acceptor.clone();
ctx.add_stream(tcp.incoming().and_then(move |(stream, addr)| {
TlsAcceptorExt::accept_async(acc.as_ref(), stream)
2017-12-08 17:24:05 +00:00
.map(move |t| IoStream{io: t, peer: Some(addr), http2: false})
2017-11-02 19:54:09 +00:00
.map_err(|err| {
trace!("Error during handling tls connection: {}", err);
2017-11-02 19:54:09 +00:00
io::Error::new(io::ErrorKind::Other, err)
})
}));
}
self
}))
}
}
#[cfg(feature="alpn")]
impl<H: HttpHandler> HttpServer<SslStream<TcpStream>, net::SocketAddr, H> {
/// Start listening for incomming tls connections.
///
/// This methods converts address to list of `SocketAddr`
/// then binds to all available addresses.
2017-12-08 06:54:44 +00:00
pub fn serve_tls<S, Addr>(mut self, addr: S, identity: ParsedPkcs12) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{
let addrs = self.bind(addr)?;
2017-12-08 17:24:05 +00:00
// set server settings
let settings = ServerSettings::new(Some(addrs[0].0), true);
for h in Rc::get_mut(&mut self.h).unwrap().iter_mut() {
h.server_settings(settings.clone());
}
2017-12-08 06:54:44 +00:00
let acceptor = match SslAcceptorBuilder::mozilla_intermediate(
SslMethod::tls(), &identity.pkey, &identity.cert, &identity.chain)
{
Ok(mut builder) => {
match builder.builder_mut().set_alpn_protocols(&[b"h2", b"http/1.1"]) {
Ok(_) => builder.build(),
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err)),
}
},
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
};
Ok(HttpServer::create(move |ctx| {
for (srv, tcp) in addrs {
info!("Starting tls http server on {}", srv);
let acc = acceptor.clone();
ctx.add_stream(tcp.incoming().and_then(move |(stream, addr)| {
SslAcceptorExt::accept_async(&acc, stream)
.map(move |stream| {
let http2 = if let Some(p) =
stream.get_ref().ssl().selected_alpn_protocol()
{
p.len() == 2 && &p == b"h2"
} else {
false
};
2017-12-08 17:24:05 +00:00
IoStream{io: stream, peer: Some(addr), http2: http2}
})
.map_err(|err| {
trace!("Error during handling tls connection: {}", err);
io::Error::new(io::ErrorKind::Other, err)
})
}));
}
self
}))
}
}
2017-12-08 17:24:05 +00:00
struct IoStream<T> {
io: T,
peer: Option<SocketAddr>,
http2: bool,
}
2017-10-21 22:21:16 +00:00
2017-12-08 17:24:05 +00:00
impl<T> ResponseType for IoStream<T>
where T: AsyncRead + AsyncWrite + 'static
{
2017-10-07 04:48:14 +00:00
type Item = ();
type Error = ();
}
2017-12-08 17:24:05 +00:00
impl<T, A, H> StreamHandler<IoStream<T>, io::Error> for HttpServer<T, A, H>
2017-10-22 01:54:24 +00:00
where T: AsyncRead + AsyncWrite + 'static,
H: HttpHandler + 'static,
A: 'static {}
2017-10-07 04:48:14 +00:00
2017-12-08 17:24:05 +00:00
impl<T, A, H> Handler<IoStream<T>, io::Error> for HttpServer<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
2017-10-22 01:54:24 +00:00
H: HttpHandler + 'static,
A: 'static,
{
fn error(&mut self, err: io::Error, _: &mut Context<Self>) {
2017-11-04 16:07:44 +00:00
debug!("Error handling request: {}", err)
}
2017-12-08 17:24:05 +00:00
fn handle(&mut self, msg: IoStream<T>, _: &mut Context<Self>)
-> Response<Self, IoStream<T>>
2017-10-07 04:48:14 +00:00
{
Arbiter::handle().spawn(
2017-12-08 17:24:05 +00:00
HttpChannel::new(Rc::clone(&self.h), msg.io, msg.peer, msg.http2));
2017-10-07 07:22:09 +00:00
Self::empty()
2017-10-07 04:48:14 +00:00
}
}