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

433 lines
14 KiB
Rust
Raw Normal View History

use std::{io, net};
2017-10-07 04:48:14 +00:00
use std::rc::Rc;
use std::cell::UnsafeCell;
2017-10-13 23:33:23 +00:00
use std::time::Duration;
use std::marker::PhantomData;
2017-10-07 04:48:14 +00:00
use std::collections::VecDeque;
use actix::dev::*;
use futures::{Future, Poll, Async, Stream};
2017-10-13 23:33:23 +00:00
use tokio_core::reactor::Timeout;
2017-10-07 04:48:14 +00:00
use tokio_core::net::{TcpListener, TcpStream};
use tokio_io::{AsyncRead, AsyncWrite};
2017-10-07 04:48:14 +00:00
#[cfg(feature="tls")]
use native_tls::TlsAcceptor;
#[cfg(feature="tls")]
use tokio_tls::{TlsStream, TlsAcceptorExt};
2017-11-02 19:54:09 +00:00
use h1;
use task::Task;
2017-10-22 01:54:24 +00:00
use payload::Payload;
use httpcodes::HTTPNotFound;
use httprequest::HttpRequest;
/// Low level http request handler
pub trait HttpHandler: 'static {
/// Http handler prefix
fn prefix(&self) -> &str;
/// Handle request
fn handle(&self, req: &mut HttpRequest, payload: Payload) -> Task;
2017-10-22 01:54:24 +00:00
}
2017-10-07 04:48:14 +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> {
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
pub fn new<U: IntoIterator<Item=H>>(handler: U) -> Self {
2017-10-23 00:33:24 +00:00
let apps: Vec<_> = handler.into_iter().collect();
2017-10-22 01:54:24 +00:00
HttpServer {h: Rc::new(apps),
io: PhantomData,
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.
pub fn serve_incoming<S, Addr>(self, stream: S) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: Stream<Item=(T, A), Error=io::Error> + 'static
{
Ok(HttpServer::create(move |ctx| {
2017-10-21 22:21:16 +00:00
ctx.add_stream(stream.map(|(t, a)| IoStream(t, a)));
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.
pub fn serve<S, Addr>(self, addr: S) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{
let addrs = self.bind(addr)?;
Ok(HttpServer::create(move |ctx| {
for (addr, tcp) in addrs {
info!("Starting http server on {}", addr);
ctx.add_stream(tcp.incoming().map(|(t, a)| IoStream(t, a)));
}
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.
pub fn serve_tls<S, Addr>(self, addr: S, pkcs12: ::Pkcs12) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{
let addrs = self.bind(addr)?;
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))
};
Ok(HttpServer::create(move |ctx| {
for (addr, tcp) in addrs {
info!("Starting tls http server on {}", addr);
let acc = acceptor.clone();
ctx.add_stream(tcp.incoming().and_then(move |(stream, addr)| {
2017-11-02 19:54:09 +00:00
println!("SSL");
TlsAcceptorExt::accept_async(acc.as_ref(), stream)
2017-11-02 19:54:09 +00:00
.map(move |t| {
println!("connected {:?} {:?}", t, addr);
IoStream(t, addr)
})
.map_err(|err| {
println!("ERR: {:?}", err);
io::Error::new(io::ErrorKind::Other, err)
})
}));
}
self
}))
}
}
2017-10-21 22:21:16 +00:00
struct IoStream<T, A>(T, A);
impl<T, A> ResponseType for IoStream<T, A>
where T: AsyncRead + AsyncWrite + 'static,
A: 'static
{
2017-10-07 04:48:14 +00:00
type Item = ();
type Error = ();
}
2017-10-22 01:54:24 +00:00
impl<T, A, H> StreamHandler<IoStream<T, A>, io::Error> for HttpServer<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static {}
2017-10-07 04:48:14 +00:00
2017-10-22 01:54:24 +00:00
impl<T, A, H> Handler<IoStream<T, A>, io::Error> for HttpServer<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
2017-10-22 01:54:24 +00:00
A: 'static,
H: HttpHandler + 'static,
{
fn error(&mut self, err: io::Error, _: &mut Context<Self>) {
2017-11-02 19:54:09 +00:00
println!("Error handling request: {}", err)
}
2017-10-21 22:21:16 +00:00
fn handle(&mut self, msg: IoStream<T, A>, _: &mut Context<Self>)
-> Response<Self, IoStream<T, A>>
2017-10-07 04:48:14 +00:00
{
Arbiter::handle().spawn(
2017-10-22 01:54:24 +00:00
HttpChannel{router: Rc::clone(&self.h),
2017-10-07 04:48:14 +00:00
addr: msg.1,
stream: msg.0,
2017-11-02 19:54:09 +00:00
reader: h1::Reader::new(),
error: false,
2017-10-07 04:48:14 +00:00
items: VecDeque::new(),
2017-10-21 06:12:36 +00:00
inactive: VecDeque::new(),
2017-10-13 23:33:23 +00:00
keepalive: true,
keepalive_timer: None,
2017-10-07 04:48:14 +00:00
});
2017-10-07 07:22:09 +00:00
Self::empty()
2017-10-07 04:48:14 +00:00
}
}
struct Entry {
task: Task,
req: UnsafeCell<HttpRequest>,
2017-10-07 04:48:14 +00:00
eof: bool,
error: bool,
finished: bool,
}
2017-10-13 23:33:23 +00:00
const KEEPALIVE_PERIOD: u64 = 15; // seconds
const MAX_PIPELINED_MESSAGES: usize = 16;
2017-10-22 01:54:24 +00:00
pub struct HttpChannel<T: 'static, A: 'static, H: 'static> {
router: Rc<Vec<H>>,
2017-10-07 04:48:14 +00:00
#[allow(dead_code)]
addr: A,
stream: T,
2017-11-02 19:54:09 +00:00
reader: h1::Reader,
error: bool,
2017-10-07 04:48:14 +00:00
items: VecDeque<Entry>,
2017-10-21 06:12:36 +00:00
inactive: VecDeque<Entry>,
2017-10-13 23:33:23 +00:00
keepalive: bool,
keepalive_timer: Option<Timeout>,
}
2017-10-30 03:54:52 +00:00
/*impl<T: 'static, A: 'static, H: 'static> Drop for HttpChannel<T, A, H> {
2017-10-13 23:33:23 +00:00
fn drop(&mut self) {
println!("Drop http channel");
}
2017-10-30 03:54:52 +00:00
}*/
2017-10-07 04:48:14 +00:00
2017-10-22 01:54:24 +00:00
impl<T, A, H> Actor for HttpChannel<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static
{
2017-10-07 04:48:14 +00:00
type Context = Context<Self>;
}
2017-10-22 01:54:24 +00:00
impl<T, A, H> Future for HttpChannel<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static
{
2017-10-07 04:48:14 +00:00
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
2017-10-13 23:33:23 +00:00
// keep-alive timer
if let Some(ref mut timeout) = self.keepalive_timer {
match timeout.poll() {
Ok(Async::Ready(_)) =>
return Ok(Async::Ready(())),
Ok(Async::NotReady) => (),
Err(_) => unreachable!(),
}
}
2017-10-07 04:48:14 +00:00
loop {
2017-10-25 23:25:26 +00:00
let mut not_ready = true;
2017-10-07 04:48:14 +00:00
// check in-flight messages
let mut idx = 0;
while idx < self.items.len() {
if idx == 0 {
if self.items[idx].error {
return Err(())
}
// this is anoying
let req = unsafe {self.items[idx].req.get().as_mut().unwrap()};
match self.items[idx].task.poll_io(&mut self.stream, req)
{
2017-10-21 06:12:36 +00:00
Ok(Async::Ready(ready)) => {
2017-10-25 23:25:26 +00:00
not_ready = false;
2017-10-07 04:48:14 +00:00
let mut item = self.items.pop_front().unwrap();
2017-10-13 23:33:23 +00:00
// overide keep-alive state
if self.keepalive {
self.keepalive = item.task.keepalive();
}
2017-10-21 06:12:36 +00:00
if !ready {
2017-10-07 04:48:14 +00:00
item.eof = true;
2017-10-21 06:12:36 +00:00
self.inactive.push_back(item);
2017-10-07 04:48:14 +00:00
}
2017-10-13 23:33:23 +00:00
// no keep-alive
2017-10-21 06:12:36 +00:00
if ready && !self.keepalive &&
self.items.is_empty() && self.inactive.is_empty()
{
2017-10-13 23:33:23 +00:00
return Ok(Async::Ready(()))
}
2017-10-07 04:48:14 +00:00
continue
},
Ok(Async::NotReady) => (),
Err(_) => {
// it is not possible to recover from error
// during task handling, so just drop connection
return Err(())
}
2017-10-07 04:48:14 +00:00
}
2017-10-21 06:12:36 +00:00
} else if !self.items[idx].finished && !self.items[idx].error {
2017-10-07 04:48:14 +00:00
match self.items[idx].task.poll() {
2017-10-21 06:12:36 +00:00
Ok(Async::NotReady) => (),
2017-10-25 23:25:26 +00:00
Ok(Async::Ready(_)) => {
not_ready = false;
self.items[idx].finished = true;
},
2017-10-07 04:48:14 +00:00
Err(_) =>
self.items[idx].error = true,
}
}
idx += 1;
}
2017-10-21 06:12:36 +00:00
// check inactive tasks
let mut idx = 0;
while idx < self.inactive.len() {
if idx == 0 && self.inactive[idx].error && self.inactive[idx].finished {
let _ = self.inactive.pop_front();
continue
}
if !self.inactive[idx].finished && !self.inactive[idx].error {
match self.inactive[idx].task.poll() {
Ok(Async::NotReady) => (),
2017-10-25 23:25:26 +00:00
Ok(Async::Ready(_)) => {
not_ready = false;
self.inactive[idx].finished = true
}
2017-10-21 06:12:36 +00:00
Err(_) =>
self.inactive[idx].error = true,
}
}
idx += 1;
}
2017-10-07 04:48:14 +00:00
// read incoming data
2017-10-13 23:33:23 +00:00
if !self.error && self.items.len() < MAX_PIPELINED_MESSAGES {
match self.reader.parse(&mut self.stream) {
Ok(Async::Ready((mut req, payload))) => {
2017-10-25 23:25:26 +00:00
not_ready = false;
2017-10-13 23:33:23 +00:00
// stop keepalive timer
self.keepalive_timer.take();
// start request processing
2017-10-22 01:54:24 +00:00
let mut task = None;
for h in self.router.iter() {
if req.path().starts_with(h.prefix()) {
task = Some(h.handle(&mut req, payload));
2017-10-22 01:54:24 +00:00
break
}
}
self.items.push_back(
2017-10-22 01:54:24 +00:00
Entry {task: task.unwrap_or_else(|| Task::reply(HTTPNotFound)),
req: UnsafeCell::new(req),
eof: false,
error: false,
finished: false});
}
2017-10-13 23:33:23 +00:00
Err(err) => {
2017-10-25 23:25:26 +00:00
// notify all tasks
not_ready = false;
for entry in &mut self.items {
entry.task.disconnected()
}
2017-10-13 23:33:23 +00:00
// kill keepalive
self.keepalive = false;
self.keepalive_timer.take();
// on parse error, stop reading stream but
2017-10-21 06:12:36 +00:00
// tasks need to be completed
2017-10-13 23:33:23 +00:00
self.error = true;
if self.items.is_empty() {
2017-11-02 19:54:09 +00:00
if let h1::ReaderError::Error(err) = err {
self.items.push_back(
Entry {task: Task::reply(err),
req: UnsafeCell::new(HttpRequest::for_error()),
eof: false,
error: false,
finished: false});
}
2017-10-13 23:33:23 +00:00
}
}
Ok(Async::NotReady) => {
// start keep-alive timer, this is also slow request timeout
2017-10-21 06:12:36 +00:00
if self.items.is_empty() && self.inactive.is_empty() {
2017-10-13 23:33:23 +00:00
if self.keepalive {
if self.keepalive_timer.is_none() {
trace!("Start keep-alive timer");
let mut timeout = Timeout::new(
Duration::new(KEEPALIVE_PERIOD, 0),
Arbiter::handle()).unwrap();
// register timeout
let _ = timeout.poll();
self.keepalive_timer = Some(timeout);
}
} else {
// keep-alive disable, drop connection
return Ok(Async::Ready(()))
}
}
return Ok(Async::NotReady)
}
}
2017-10-07 04:48:14 +00:00
}
2017-10-13 23:33:23 +00:00
// check for parse error
2017-10-21 06:12:36 +00:00
if self.items.is_empty() && self.inactive.is_empty() && self.error {
2017-10-13 23:33:23 +00:00
return Ok(Async::Ready(()))
}
2017-10-25 23:25:26 +00:00
if not_ready {
return Ok(Async::NotReady)
}
2017-10-07 04:48:14 +00:00
}
}
}