2017-11-03 19:29:44 +01:00
|
|
|
use std::{io, cmp, mem};
|
|
|
|
use std::rc::Rc;
|
2017-11-02 20:54:09 +01:00
|
|
|
use std::io::{Read, Write};
|
2017-11-03 19:29:44 +01:00
|
|
|
use std::cell::UnsafeCell;
|
2017-11-04 21:24:57 +01:00
|
|
|
use std::time::Duration;
|
2017-11-03 19:29:44 +01:00
|
|
|
use std::collections::VecDeque;
|
|
|
|
|
2017-11-04 21:24:57 +01:00
|
|
|
use actix::Arbiter;
|
2017-11-03 19:29:44 +01:00
|
|
|
use http::request::Parts;
|
2017-11-06 18:35:52 +01:00
|
|
|
use http::header::CONTENT_ENCODING;
|
2017-11-04 17:07:44 +01:00
|
|
|
use http2::{Reason, RecvStream};
|
2017-11-03 19:29:44 +01:00
|
|
|
use http2::server::{Server, Handshake, Respond};
|
2017-11-02 20:54:09 +01:00
|
|
|
use bytes::{Buf, Bytes};
|
2017-11-03 19:29:44 +01:00
|
|
|
use futures::{Async, Poll, Future, Stream};
|
2017-11-02 20:54:09 +01:00
|
|
|
use tokio_io::{AsyncRead, AsyncWrite};
|
2017-11-04 21:24:57 +01:00
|
|
|
use tokio_core::reactor::Timeout;
|
2017-11-02 20:54:09 +01:00
|
|
|
|
2017-11-03 19:29:44 +01:00
|
|
|
use task::Task;
|
2017-11-06 10:24:49 +01:00
|
|
|
use h2writer::H2Writer;
|
2017-11-04 20:33:14 +01:00
|
|
|
use channel::HttpHandler;
|
2017-11-03 19:29:44 +01:00
|
|
|
use httpcodes::HTTPNotFound;
|
|
|
|
use httprequest::HttpRequest;
|
2017-11-06 18:35:52 +01:00
|
|
|
use httpresponse::ContentEncoding;
|
|
|
|
use payload::{Payload, PayloadError, PayloadSender, PayloadWriter, EncodedPayload};
|
2017-11-03 19:29:44 +01:00
|
|
|
|
2017-11-04 21:24:57 +01:00
|
|
|
const KEEPALIVE_PERIOD: u64 = 15; // seconds
|
|
|
|
|
2017-11-03 19:29:44 +01:00
|
|
|
pub(crate) struct Http2<T, A, H>
|
|
|
|
where T: AsyncRead + AsyncWrite + 'static, A: 'static, H: 'static
|
|
|
|
{
|
|
|
|
router: Rc<Vec<H>>,
|
|
|
|
#[allow(dead_code)]
|
|
|
|
addr: A,
|
|
|
|
state: State<IoWrapper<T>>,
|
2017-11-04 17:07:44 +01:00
|
|
|
disconnected: bool,
|
2017-11-03 19:29:44 +01:00
|
|
|
tasks: VecDeque<Entry>,
|
2017-11-04 21:24:57 +01:00
|
|
|
keepalive_timer: Option<Timeout>,
|
2017-11-03 19:29:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
enum State<T: AsyncRead + AsyncWrite> {
|
|
|
|
Handshake(Handshake<T, Bytes>),
|
|
|
|
Server(Server<T, Bytes>),
|
|
|
|
Empty,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T, A, H> Http2<T, A, H>
|
|
|
|
where T: AsyncRead + AsyncWrite + 'static,
|
|
|
|
A: 'static,
|
|
|
|
H: HttpHandler + 'static
|
|
|
|
{
|
|
|
|
pub fn new(stream: T, addr: A, router: Rc<Vec<H>>, buf: Bytes) -> Self {
|
|
|
|
Http2{ router: router,
|
|
|
|
addr: addr,
|
2017-11-04 17:07:44 +01:00
|
|
|
disconnected: false,
|
2017-11-03 19:29:44 +01:00
|
|
|
tasks: VecDeque::new(),
|
|
|
|
state: State::Handshake(
|
2017-11-04 21:24:57 +01:00
|
|
|
Server::handshake(IoWrapper{unread: Some(buf), inner: stream})),
|
|
|
|
keepalive_timer: None,
|
|
|
|
}
|
2017-11-03 19:29:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn poll(&mut self) -> Poll<(), ()> {
|
2017-11-04 17:07:44 +01:00
|
|
|
// server
|
|
|
|
if let State::Server(ref mut server) = self.state {
|
2017-11-04 21:24:57 +01: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-11-04 17:07:44 +01:00
|
|
|
loop {
|
|
|
|
let mut not_ready = true;
|
|
|
|
|
|
|
|
// check in-flight connections
|
|
|
|
for item in &mut self.tasks {
|
|
|
|
// read payload
|
|
|
|
item.poll_payload();
|
|
|
|
|
|
|
|
if !item.eof {
|
|
|
|
let req = unsafe {item.req.get().as_mut().unwrap()};
|
|
|
|
match item.task.poll_io(&mut item.stream, req) {
|
|
|
|
Ok(Async::Ready(ready)) => {
|
|
|
|
item.eof = true;
|
|
|
|
if ready {
|
|
|
|
item.finished = true;
|
|
|
|
}
|
|
|
|
not_ready = false;
|
|
|
|
},
|
|
|
|
Ok(Async::NotReady) => (),
|
|
|
|
Err(_) => {
|
|
|
|
item.eof = true;
|
|
|
|
item.error = true;
|
|
|
|
item.stream.reset(Reason::INTERNAL_ERROR);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if !item.finished {
|
|
|
|
match item.task.poll() {
|
|
|
|
Ok(Async::NotReady) => (),
|
|
|
|
Ok(Async::Ready(_)) => {
|
|
|
|
not_ready = false;
|
|
|
|
item.finished = true;
|
|
|
|
},
|
|
|
|
Err(_) => {
|
|
|
|
item.error = true;
|
|
|
|
item.finished = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// cleanup finished tasks
|
|
|
|
while !self.tasks.is_empty() {
|
|
|
|
if self.tasks[0].eof && self.tasks[0].finished || self.tasks[0].error {
|
|
|
|
self.tasks.pop_front();
|
|
|
|
} else {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// get request
|
|
|
|
if !self.disconnected {
|
|
|
|
match server.poll() {
|
|
|
|
Ok(Async::Ready(None)) => {
|
|
|
|
not_ready = false;
|
|
|
|
self.disconnected = true;
|
|
|
|
for entry in &mut self.tasks {
|
|
|
|
entry.task.disconnected()
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Ok(Async::Ready(Some((req, resp)))) => {
|
|
|
|
not_ready = false;
|
|
|
|
let (parts, body) = req.into_parts();
|
|
|
|
self.tasks.push_back(
|
|
|
|
Entry::new(parts, body, resp, &self.router));
|
2017-11-04 21:24:57 +01:00
|
|
|
self.keepalive_timer.take();
|
2017-11-04 17:07:44 +01:00
|
|
|
}
|
2017-11-04 21:24:57 +01:00
|
|
|
Ok(Async::NotReady) => {
|
|
|
|
// start keep-alive timer
|
|
|
|
if self.tasks.is_empty() {
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
trace!("Connection error: {}", err);
|
|
|
|
self.disconnected = true;
|
|
|
|
for entry in &mut self.tasks {
|
|
|
|
entry.task.disconnected()
|
|
|
|
}
|
|
|
|
self.keepalive_timer.take();
|
|
|
|
},
|
2017-11-04 17:07:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if not_ready {
|
|
|
|
if self.tasks.is_empty() && self.disconnected {
|
|
|
|
return Ok(Async::Ready(()))
|
|
|
|
} else {
|
|
|
|
return Ok(Async::NotReady)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-03 19:29:44 +01:00
|
|
|
// handshake
|
|
|
|
self.state = if let State::Handshake(ref mut handshake) = self.state {
|
|
|
|
match handshake.poll() {
|
|
|
|
Ok(Async::Ready(srv)) => {
|
|
|
|
State::Server(srv)
|
|
|
|
},
|
|
|
|
Ok(Async::NotReady) =>
|
|
|
|
return Ok(Async::NotReady),
|
|
|
|
Err(err) => {
|
|
|
|
trace!("Error handling connection: {}", err);
|
|
|
|
return Err(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
mem::replace(&mut self.state, State::Empty)
|
|
|
|
};
|
|
|
|
|
2017-11-04 17:07:44 +01:00
|
|
|
self.poll()
|
2017-11-03 19:29:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-06 18:35:52 +01:00
|
|
|
struct PayloadInfo(PayloadInfoItem);
|
|
|
|
enum PayloadInfoItem {
|
|
|
|
Sender(PayloadSender),
|
|
|
|
Encoding(EncodedPayload),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PayloadInfo {
|
|
|
|
|
|
|
|
fn as_mut(&mut self) -> &mut PayloadWriter {
|
|
|
|
match self.0 {
|
|
|
|
PayloadInfoItem::Sender(ref mut sender) => sender,
|
|
|
|
PayloadInfoItem::Encoding(ref mut enc) => enc,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-03 19:29:44 +01:00
|
|
|
struct Entry {
|
|
|
|
task: Task,
|
|
|
|
req: UnsafeCell<HttpRequest>,
|
2017-11-06 18:35:52 +01:00
|
|
|
payload: PayloadInfo,
|
2017-11-03 19:29:44 +01:00
|
|
|
recv: RecvStream,
|
2017-11-04 17:07:44 +01:00
|
|
|
stream: H2Writer,
|
2017-11-03 19:29:44 +01:00
|
|
|
eof: bool,
|
|
|
|
error: bool,
|
|
|
|
finished: bool,
|
2017-11-04 17:07:44 +01:00
|
|
|
reof: bool,
|
|
|
|
capacity: usize,
|
2017-11-03 19:29:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Entry {
|
|
|
|
fn new<H>(parts: Parts,
|
|
|
|
recv: RecvStream,
|
|
|
|
resp: Respond<Bytes>,
|
|
|
|
router: &Rc<Vec<H>>) -> Entry
|
|
|
|
where H: HttpHandler + 'static
|
|
|
|
{
|
|
|
|
let path = parts.uri.path().to_owned();
|
|
|
|
let query = parts.uri.query().unwrap_or("").to_owned();
|
|
|
|
|
|
|
|
let mut req = HttpRequest::new(
|
|
|
|
parts.method, path, parts.version, parts.headers, query);
|
2017-11-06 18:35:52 +01:00
|
|
|
|
|
|
|
// Payload and Content-Encoding
|
2017-11-03 19:29:44 +01:00
|
|
|
let (psender, payload) = Payload::new(false);
|
2017-11-06 18:35:52 +01:00
|
|
|
let enc = if let Some(enc) = req.headers().get(CONTENT_ENCODING) {
|
|
|
|
if let Ok(enc) = enc.to_str() {
|
|
|
|
ContentEncoding::from(enc)
|
|
|
|
} else {
|
|
|
|
ContentEncoding::Auto
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
ContentEncoding::Auto
|
|
|
|
};
|
|
|
|
let psender = match enc {
|
|
|
|
ContentEncoding::Auto | ContentEncoding::Identity =>
|
|
|
|
PayloadInfoItem::Sender(psender),
|
|
|
|
_ => PayloadInfoItem::Encoding(EncodedPayload::new(psender, enc)),
|
|
|
|
};
|
2017-11-03 19:29:44 +01:00
|
|
|
|
|
|
|
// start request processing
|
|
|
|
let mut task = None;
|
|
|
|
for h in router.iter() {
|
|
|
|
if req.path().starts_with(h.prefix()) {
|
|
|
|
task = Some(h.handle(&mut req, payload));
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Entry {task: task.unwrap_or_else(|| Task::reply(HTTPNotFound)),
|
|
|
|
req: UnsafeCell::new(req),
|
2017-11-06 18:35:52 +01:00
|
|
|
payload: PayloadInfo(psender),
|
2017-11-03 19:29:44 +01:00
|
|
|
recv: recv,
|
2017-11-04 17:07:44 +01:00
|
|
|
stream: H2Writer::new(resp),
|
2017-11-03 19:29:44 +01:00
|
|
|
eof: false,
|
|
|
|
error: false,
|
2017-11-04 17:07:44 +01:00
|
|
|
finished: false,
|
|
|
|
reof: false,
|
|
|
|
capacity: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_payload(&mut self) {
|
|
|
|
if !self.reof {
|
|
|
|
match self.recv.poll() {
|
|
|
|
Ok(Async::Ready(Some(chunk))) => {
|
2017-11-06 18:35:52 +01:00
|
|
|
self.payload.as_mut().feed_data(chunk);
|
2017-11-04 17:07:44 +01:00
|
|
|
},
|
|
|
|
Ok(Async::Ready(None)) => {
|
|
|
|
self.reof = true;
|
|
|
|
},
|
|
|
|
Ok(Async::NotReady) => (),
|
|
|
|
Err(err) => {
|
2017-11-06 18:35:52 +01:00
|
|
|
self.payload.as_mut().set_error(PayloadError::Http2(err))
|
2017-11-04 17:07:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-06 18:35:52 +01:00
|
|
|
let capacity = self.payload.as_mut().capacity();
|
2017-11-04 17:07:44 +01:00
|
|
|
if self.capacity != capacity {
|
|
|
|
self.capacity = capacity;
|
|
|
|
if let Err(err) = self.recv.release_capacity().release_capacity(capacity) {
|
2017-11-06 18:35:52 +01:00
|
|
|
self.payload.as_mut().set_error(PayloadError::Http2(err))
|
2017-11-04 17:07:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-11-03 19:29:44 +01:00
|
|
|
}
|
|
|
|
}
|
2017-11-02 20:54:09 +01:00
|
|
|
|
|
|
|
struct IoWrapper<T> {
|
|
|
|
unread: Option<Bytes>,
|
|
|
|
inner: T,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Read> Read for IoWrapper<T> {
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
|
|
|
if let Some(mut bytes) = self.unread.take() {
|
|
|
|
let size = cmp::min(buf.len(), bytes.len());
|
2017-11-03 19:29:44 +01:00
|
|
|
buf[..size].copy_from_slice(&bytes[..size]);
|
|
|
|
if bytes.len() > size {
|
|
|
|
bytes.split_to(size);
|
2017-11-02 20:54:09 +01:00
|
|
|
self.unread = Some(bytes);
|
|
|
|
}
|
|
|
|
Ok(size)
|
|
|
|
} else {
|
|
|
|
self.inner.read(buf)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Write> Write for IoWrapper<T> {
|
|
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
|
|
self.inner.write(buf)
|
|
|
|
}
|
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
|
|
self.inner.flush()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: AsyncRead + 'static> AsyncRead for IoWrapper<T> {
|
|
|
|
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
|
|
|
|
self.inner.prepare_uninitialized_buffer(buf)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: AsyncWrite + 'static> AsyncWrite for IoWrapper<T> {
|
|
|
|
fn shutdown(&mut self) -> Poll<(), io::Error> {
|
|
|
|
self.inner.shutdown()
|
|
|
|
}
|
|
|
|
fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> {
|
|
|
|
self.inner.write_buf(buf)
|
|
|
|
}
|
|
|
|
}
|