1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-25 00:43:00 +01:00
actix-web/src/server/h1.rs

1607 lines
52 KiB
Rust
Raw Normal View History

2018-02-26 23:33:56 +01:00
#![cfg_attr(feature = "cargo-clippy", allow(redundant_field_names))]
2018-04-14 01:02:01 +02:00
use std::collections::VecDeque;
use std::net::SocketAddr;
2018-04-14 01:02:01 +02:00
use std::rc::Rc;
use std::time::Duration;
2018-04-14 01:02:01 +02:00
use std::{self, io};
2017-10-07 06:48:14 +02:00
use actix::Arbiter;
2018-03-03 21:17:26 +01:00
use bytes::{Bytes, BytesMut};
2018-04-14 01:02:01 +02:00
use futures::{Async, Future, Poll};
use http::header::{self, HeaderName, HeaderValue};
use http::{HeaderMap, HttpTryFrom, Method, Uri, Version};
use httparse;
use tokio_core::reactor::Timeout;
2017-10-07 06:48:14 +02:00
2018-04-14 01:02:01 +02:00
use error::{ParseError, PayloadError, ResponseError};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
2018-04-14 01:02:01 +02:00
use payload::{Payload, PayloadStatus, PayloadWriter};
use pipeline::Pipeline;
2018-04-17 21:55:13 +02:00
use uri::Url;
2017-10-07 06:48:14 +02:00
2018-01-12 03:41:33 +01:00
use super::encoding::PayloadType;
2018-04-14 01:02:01 +02:00
use super::h1writer::H1Writer;
2018-01-12 03:35:05 +01:00
use super::settings::WorkerSettings;
use super::{HttpHandler, HttpHandlerTask, IoStream};
2018-04-14 01:02:01 +02:00
use super::{utils, Writer};
2018-01-12 03:35:05 +01:00
2017-10-09 05:16:48 +02:00
const MAX_BUFFER_SIZE: usize = 131_072;
const MAX_HEADERS: usize = 96;
const MAX_PIPELINED_MESSAGES: usize = 16;
2017-10-07 06:48:14 +02:00
bitflags! {
struct Flags: u8 {
2018-03-13 00:16:17 +01:00
const STARTED = 0b0000_0001;
const ERROR = 0b0000_0010;
const KEEPALIVE = 0b0000_0100;
2018-03-13 00:16:17 +01:00
const SHUTDOWN = 0b0000_1000;
}
}
bitflags! {
struct EntryFlags: u8 {
const EOF = 0b0000_0001;
const ERROR = 0b0000_0010;
const FINISHED = 0b0000_0100;
}
}
pub(crate) struct Http1<T: IoStream, H: 'static> {
flags: Flags,
2017-12-14 06:38:47 +01:00
settings: Rc<WorkerSettings<H>>,
addr: Option<SocketAddr>,
2018-03-18 19:05:44 +01:00
stream: H1Writer<T, H>,
reader: Reader,
read_buf: BytesMut,
tasks: VecDeque<Entry>,
keepalive_timer: Option<Timeout>,
2017-10-07 06:48:14 +02:00
}
struct Entry {
2017-12-09 13:33:40 +01:00
pipe: Box<HttpHandlerTask>,
flags: EntryFlags,
}
impl<T, H> Http1<T, H>
2018-04-14 01:02:01 +02:00
where
T: IoStream,
H: HttpHandler + 'static,
{
2018-04-14 01:02:01 +02:00
pub fn new(
settings: Rc<WorkerSettings<H>>, stream: T, addr: Option<SocketAddr>,
read_buf: BytesMut,
) -> Self {
2018-02-26 23:33:56 +01:00
let bytes = settings.get_shared_bytes();
2018-04-14 01:02:01 +02:00
Http1 {
flags: Flags::KEEPALIVE,
stream: H1Writer::new(stream, bytes, Rc::clone(&settings)),
reader: Reader::new(),
tasks: VecDeque::new(),
keepalive_timer: None,
addr,
read_buf,
settings,
2018-02-26 23:33:56 +01:00
}
}
2017-12-29 01:25:47 +01:00
pub fn settings(&self) -> &WorkerSettings<H> {
self.settings.as_ref()
}
2018-01-04 07:43:44 +01:00
pub(crate) fn io(&mut self) -> &mut T {
self.stream.get_mut()
}
pub fn poll(&mut self) -> Poll<(), ()> {
// keep-alive timer
2018-01-21 01:12:38 +01:00
if let Some(ref mut timer) = self.keepalive_timer {
match timer.poll() {
2017-11-09 04:31:25 +01:00
Ok(Async::Ready(_)) => {
trace!("Keep-alive timeout, close connection");
2018-03-13 00:16:17 +01:00
self.flags.insert(Flags::SHUTDOWN);
2017-11-09 04:31:25 +01:00
}
Ok(Async::NotReady) => (),
Err(_) => unreachable!(),
}
}
2018-03-13 00:16:17 +01:00
// shutdown
if self.flags.contains(Flags::SHUTDOWN) {
match self.stream.poll_completed(true) {
Ok(Async::NotReady) => return Ok(Async::NotReady),
Ok(Async::Ready(_)) => return Ok(Async::Ready(())),
Err(err) => {
debug!("Error sending data: {}", err);
2018-04-14 01:02:01 +02:00
return Err(());
2018-03-13 00:16:17 +01:00
}
}
}
2018-02-27 05:07:22 +01:00
loop {
match self.poll_io()? {
Async::Ready(true) => (),
2018-03-13 00:16:17 +01:00
Async::Ready(false) => {
self.flags.insert(Flags::SHUTDOWN);
2018-04-14 01:02:01 +02:00
return self.poll();
}
2018-02-27 05:07:22 +01:00
Async::NotReady => return Ok(Async::NotReady),
}
}
}
2018-02-10 07:26:48 +01:00
// TODO: refactor
2018-02-27 05:07:22 +01:00
pub fn poll_io(&mut self) -> Poll<bool, ()> {
2018-02-10 07:26:48 +01:00
// read incoming data
2018-04-14 01:02:01 +02:00
let need_read = if !self.flags.intersects(Flags::ERROR)
&& self.tasks.len() < MAX_PIPELINED_MESSAGES
2018-02-10 07:26:48 +01:00
{
'outer: loop {
2018-04-14 01:02:01 +02:00
match self.reader.parse(
self.stream.get_mut(),
&mut self.read_buf,
&self.settings,
) {
2018-02-10 07:26:48 +01:00
Ok(Async::Ready(mut req)) => {
2018-03-13 00:16:17 +01:00
self.flags.insert(Flags::STARTED);
2018-02-10 07:26:48 +01:00
// set remote addr
req.set_peer_addr(self.addr);
// stop keepalive timer
self.keepalive_timer.take();
// start request processing
for h in self.settings.handlers().iter_mut() {
req = match h.handle(req) {
2018-02-27 05:07:22 +01:00
Ok(pipe) => {
2018-04-14 01:02:01 +02:00
self.tasks.push_back(Entry {
pipe,
flags: EntryFlags::empty(),
});
continue 'outer;
}
2018-02-10 07:26:48 +01:00
Err(req) => req,
}
}
2018-04-14 01:02:01 +02:00
self.tasks.push_back(Entry {
pipe: Pipeline::error(HttpResponse::NotFound()),
flags: EntryFlags::empty(),
});
continue;
}
2018-02-10 07:26:48 +01:00
Ok(Async::NotReady) => (),
Err(err) => {
trace!("Parse error: {:?}", err);
2018-02-10 07:26:48 +01:00
// notify all tasks
self.stream.disconnected();
for entry in &mut self.tasks {
entry.pipe.disconnected()
}
// kill keepalive
self.flags.remove(Flags::KEEPALIVE);
self.keepalive_timer.take();
2018-04-14 01:02:01 +02:00
// on parse error, stop reading stream but tasks need to be
// completed
2018-02-10 07:26:48 +01:00
self.flags.insert(Flags::ERROR);
2018-02-27 05:07:22 +01:00
match err {
ReaderError::Disconnect => (),
2018-04-14 01:02:01 +02:00
_ => if self.tasks.is_empty() {
if let ReaderError::Error(err) = err {
self.tasks.push_back(Entry {
pipe: Pipeline::error(err.error_response()),
flags: EntryFlags::empty(),
});
2018-02-27 05:07:22 +01:00
}
2018-04-14 01:02:01 +02:00
},
2018-02-10 07:26:48 +01:00
}
2018-04-14 01:02:01 +02:00
}
2018-02-10 07:26:48 +01:00
}
2018-04-14 01:02:01 +02:00
break;
2018-02-10 07:26:48 +01:00
}
false
} else {
true
};
let retry = self.reader.need_read() == PayloadStatus::Read;
2018-02-27 05:07:22 +01:00
// check in-flight messages
let mut io = false;
let mut idx = 0;
while idx < self.tasks.len() {
let item = &mut self.tasks[idx];
if !io && !item.flags.contains(EntryFlags::EOF) {
// io is corrupted, send buffer
if item.flags.contains(EntryFlags::ERROR) {
if let Ok(Async::NotReady) = self.stream.poll_completed(true) {
2018-04-14 01:02:01 +02:00
return Ok(Async::NotReady);
}
2018-04-14 01:02:01 +02:00
return Err(());
}
match item.pipe.poll_io(&mut self.stream) {
Ok(Async::Ready(ready)) => {
// override keep-alive state
if self.stream.keepalive() {
self.flags.insert(Flags::KEEPALIVE);
} else {
self.flags.remove(Flags::KEEPALIVE);
}
// prepare stream for next response
self.stream.reset();
if ready {
2018-04-14 01:02:01 +02:00
item.flags
.insert(EntryFlags::EOF | EntryFlags::FINISHED);
} else {
item.flags.insert(EntryFlags::FINISHED);
2018-02-27 05:07:22 +01:00
}
2018-04-14 01:02:01 +02:00
}
// no more IO for this iteration
Ok(Async::NotReady) => {
if self.reader.need_read() == PayloadStatus::Read && !retry {
return Ok(Async::Ready(true));
}
io = true;
}
Err(err) => {
// it is not possible to recover from error
// during pipe handling, so just drop connection
error!("Unhandled error: {}", err);
item.flags.insert(EntryFlags::ERROR);
// check stream state, we still can have valid data in buffer
if let Ok(Async::NotReady) = self.stream.poll_completed(true) {
2018-04-14 01:02:01 +02:00
return Ok(Async::NotReady);
2017-11-25 18:28:25 +01:00
}
2018-04-14 01:02:01 +02:00
return Err(());
}
}
} else if !item.flags.contains(EntryFlags::FINISHED) {
match item.pipe.poll() {
Ok(Async::NotReady) => (),
Ok(Async::Ready(_)) => item.flags.insert(EntryFlags::FINISHED),
Err(err) => {
item.flags.insert(EntryFlags::ERROR);
error!("Unhandled error: {}", err);
}
}
}
idx += 1;
}
// cleanup finished tasks
let mut popped = false;
while !self.tasks.is_empty() {
2018-04-14 01:02:01 +02:00
if self.tasks[0]
.flags
.contains(EntryFlags::EOF | EntryFlags::FINISHED)
{
popped = true;
self.tasks.pop_front();
} else {
2018-04-14 01:02:01 +02:00
break;
2018-02-10 07:26:48 +01:00
}
}
if need_read && popped {
2018-04-14 01:02:01 +02:00
return self.poll_io();
}
// check stream state
2018-03-13 00:16:17 +01:00
if self.flags.contains(Flags::STARTED) {
match self.stream.poll_completed(false) {
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(err) => {
debug!("Error sending data: {}", err);
2018-04-14 01:02:01 +02:00
return Err(());
2018-03-13 00:16:17 +01:00
}
_ => (),
2018-03-11 23:37:33 +01:00
}
}
// deal with keep-alive
if self.tasks.is_empty() {
// no keep-alive situations
2018-04-14 01:02:01 +02:00
if self.flags.contains(Flags::ERROR)
|| (!self.flags.contains(Flags::KEEPALIVE)
|| !self.settings.keep_alive_enabled())
&& self.flags.contains(Flags::STARTED)
{
2018-04-14 01:02:01 +02:00
return Ok(Async::Ready(false));
}
// start keep-alive timer
let keep_alive = self.settings.keep_alive();
if self.keepalive_timer.is_none() && keep_alive > 0 {
trace!("Start keep-alive timer");
2018-04-14 01:02:01 +02:00
let mut timer =
Timeout::new(Duration::new(keep_alive, 0), Arbiter::handle())
.unwrap();
// register timer
let _ = timer.poll();
self.keepalive_timer = Some(timer);
}
}
Ok(Async::NotReady)
}
2017-10-07 06:48:14 +02:00
}
struct Reader {
payload: Option<PayloadInfo>,
}
enum Decoding {
Ready,
NotReady,
}
struct PayloadInfo {
2017-11-07 01:23:58 +01:00
tx: PayloadType,
decoder: Decoder,
}
2017-10-14 09:11:12 +02:00
#[derive(Debug)]
enum ReaderError {
Disconnect,
2017-10-14 01:33:23 +02:00
Payload,
PayloadDropped,
2017-10-14 01:33:23 +02:00
Error(ParseError),
}
2017-10-07 06:48:14 +02:00
impl Reader {
pub fn new() -> Reader {
2018-04-14 01:02:01 +02:00
Reader { payload: None }
2017-10-07 06:48:14 +02:00
}
2018-02-27 05:07:22 +01:00
#[inline]
fn need_read(&self) -> PayloadStatus {
2018-02-27 05:07:22 +01:00
if let Some(ref info) = self.payload {
info.tx.need_read()
} else {
PayloadStatus::Read
2018-02-27 05:07:22 +01:00
}
}
2018-03-18 19:05:44 +01:00
2018-02-10 01:20:10 +01:00
#[inline]
2018-04-14 01:02:01 +02:00
fn decode(
&mut self, buf: &mut BytesMut, payload: &mut PayloadInfo
) -> Result<Decoding, ReaderError> {
2018-02-27 05:07:22 +01:00
while !buf.is_empty() {
2018-02-10 01:20:10 +01:00
match payload.decoder.decode(buf) {
Ok(Async::Ready(Some(bytes))) => {
2018-02-27 05:07:22 +01:00
payload.tx.feed_data(bytes);
if payload.decoder.is_eof() {
payload.tx.feed_eof();
2018-04-14 01:02:01 +02:00
return Ok(Decoding::Ready);
2018-02-27 05:07:22 +01:00
}
2018-04-14 01:02:01 +02:00
}
2018-02-10 01:20:10 +01:00
Ok(Async::Ready(None)) => {
payload.tx.feed_eof();
2018-04-14 01:02:01 +02:00
return Ok(Decoding::Ready);
}
2018-02-10 01:20:10 +01:00
Ok(Async::NotReady) => return Ok(Decoding::NotReady),
Err(err) => {
payload.tx.set_error(err.into());
2018-04-14 01:02:01 +02:00
return Err(ReaderError::Payload);
2017-10-07 06:48:14 +02:00
}
}
}
2018-02-27 05:07:22 +01:00
Ok(Decoding::NotReady)
2017-10-07 06:48:14 +02:00
}
2018-02-10 01:20:10 +01:00
2018-04-14 01:02:01 +02:00
pub fn parse<T, H>(
&mut self, io: &mut T, buf: &mut BytesMut, settings: &WorkerSettings<H>
) -> Poll<HttpRequest, ReaderError>
where
T: IoStream,
2017-10-07 06:48:14 +02:00
{
match self.need_read() {
PayloadStatus::Read => (),
PayloadStatus::Pause => return Ok(Async::NotReady),
PayloadStatus::Dropped => return Err(ReaderError::PayloadDropped),
2018-02-27 05:07:22 +01:00
}
2017-12-15 22:10:12 +01:00
// read payload
2018-02-10 01:20:10 +01:00
let done = {
if let Some(ref mut payload) = self.payload {
'buf: loop {
2018-03-03 21:17:26 +01:00
let not_ready = match utils::read_from_io(io, buf) {
Ok(Async::Ready(0)) => {
payload.tx.set_error(PayloadError::Incomplete);
2018-02-10 01:20:10 +01:00
// http channel should not deal with payload errors
2018-04-14 01:02:01 +02:00
return Err(ReaderError::Payload);
}
2018-03-03 21:17:26 +01:00
Ok(Async::NotReady) => true,
2018-02-10 01:20:10 +01:00
Err(err) => {
payload.tx.set_error(err.into());
// http channel should not deal with payload errors
2018-04-14 01:02:01 +02:00
return Err(ReaderError::Payload);
2018-02-10 01:20:10 +01:00
}
2018-03-03 21:17:26 +01:00
_ => false,
};
loop {
match payload.decoder.decode(buf) {
Ok(Async::Ready(Some(bytes))) => {
payload.tx.feed_data(bytes);
if payload.decoder.is_eof() {
payload.tx.feed_eof();
2018-04-14 01:02:01 +02:00
break 'buf true;
}
2018-04-14 01:02:01 +02:00
}
Ok(Async::Ready(None)) => {
payload.tx.feed_eof();
2018-04-14 01:02:01 +02:00
break 'buf true;
}
Ok(Async::NotReady) => {
// if buffer is full then
// socket still can contain more data
2018-03-03 21:17:26 +01:00
if not_ready {
2018-04-14 01:02:01 +02:00
return Ok(Async::NotReady);
}
2018-04-14 01:02:01 +02:00
continue 'buf;
}
Err(err) => {
payload.tx.set_error(err.into());
2018-04-14 01:02:01 +02:00
return Err(ReaderError::Payload);
}
}
2018-02-10 01:20:10 +01:00
}
}
} else {
false
2017-10-07 06:48:14 +02:00
}
2018-02-10 01:20:10 +01:00
};
2018-04-14 01:02:01 +02:00
if done {
self.payload = None
}
2017-10-07 06:48:14 +02:00
2017-12-15 22:10:12 +01:00
// if buf is empty parse_message will always return NotReady, let's avoid that
2018-03-03 21:17:26 +01:00
if buf.is_empty() {
match utils::read_from_io(io, buf) {
2018-02-10 07:26:48 +01:00
Ok(Async::Ready(0)) => return Err(ReaderError::Disconnect),
2017-12-15 22:10:12 +01:00
Ok(Async::Ready(_)) => (),
2018-02-10 07:26:48 +01:00
Ok(Async::NotReady) => return Ok(Async::NotReady),
2018-04-14 01:02:01 +02:00
Err(err) => return Err(ReaderError::Error(err.into())),
2017-12-15 22:10:12 +01:00
}
};
2017-10-07 06:48:14 +02:00
loop {
2017-12-15 04:34:31 +01:00
match Reader::parse_message(buf, settings).map_err(ReaderError::Error)? {
Async::Ready((msg, decoder)) => {
2017-12-15 22:10:12 +01:00
// process payload
2018-02-10 01:20:10 +01:00
if let Some(mut payload) = decoder {
match self.decode(buf, &mut payload)? {
Decoding::Ready => (),
Decoding::NotReady => self.payload = Some(payload),
2017-10-07 06:48:14 +02:00
}
2017-11-27 04:00:57 +01:00
}
return Ok(Async::Ready(msg));
2018-04-14 01:02:01 +02:00
}
Async::NotReady => {
if buf.len() >= MAX_BUFFER_SIZE {
2017-12-15 22:10:12 +01:00
error!("MAX_BUFFER_SIZE unprocessed data reached, closing");
2017-10-14 01:33:23 +02:00
return Err(ReaderError::Error(ParseError::TooLarge));
2017-10-07 06:48:14 +02:00
}
2018-03-03 21:17:26 +01:00
match utils::read_from_io(io, buf) {
Ok(Async::Ready(0)) => {
debug!("Ignored premature client disconnection");
return Err(ReaderError::Disconnect);
2018-04-14 01:02:01 +02:00
}
2018-03-03 21:17:26 +01:00
Ok(Async::Ready(_)) => (),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(err) => return Err(ReaderError::Error(err.into())),
2017-12-15 22:10:12 +01:00
}
2018-04-14 01:02:01 +02:00
}
2017-10-07 06:48:14 +02:00
}
}
}
2018-04-14 01:02:01 +02:00
fn parse_message<H>(
buf: &mut BytesMut, settings: &WorkerSettings<H>
) -> Poll<(HttpRequest, Option<PayloadInfo>), ParseError> {
2017-10-14 09:11:12 +02:00
// Parse http message
2018-03-20 23:51:19 +01:00
let mut has_te = false;
let mut has_upgrade = false;
let mut has_length = false;
2017-12-16 07:49:48 +01:00
let msg = {
let bytes_ptr = buf.as_ref().as_ptr() as usize;
2017-12-15 07:22:27 +01:00
let mut headers: [httparse::Header; MAX_HEADERS] =
2018-04-14 01:02:01 +02:00
unsafe { std::mem::uninitialized() };
2017-10-07 06:48:14 +02:00
2017-12-16 07:49:48 +01:00
let (len, method, path, version, headers_len) = {
2018-04-14 01:02:01 +02:00
let b = unsafe {
let b: &[u8] = buf;
std::mem::transmute(b)
};
2017-12-16 07:49:48 +01:00
let mut req = httparse::Request::new(&mut headers);
match req.parse(b)? {
httparse::Status::Complete(len) => {
2018-04-14 01:02:01 +02:00
let method = Method::from_bytes(req.method.unwrap().as_bytes())
2017-12-16 07:49:48 +01:00
.map_err(|_| ParseError::Method)?;
2018-04-17 21:55:13 +02:00
let path = Url::new(Uri::try_from(req.path.unwrap())?);
let version = if req.version.unwrap() == 1 {
2017-12-16 07:49:48 +01:00
Version::HTTP_11
} else {
Version::HTTP_10
};
(len, method, path, version, req.headers.len())
}
httparse::Status::Partial => return Ok(Async::NotReady),
2017-10-14 09:11:12 +02:00
}
2017-12-16 07:49:48 +01:00
};
let slice = buf.split_to(len).freeze();
// convert headers
let msg = settings.get_http_message();
2018-03-17 04:56:23 +01:00
{
let msg_mut = msg.get_mut();
for header in headers[..headers_len].iter() {
2018-03-20 23:51:19 +01:00
if let Ok(name) = HeaderName::from_bytes(header.name.as_bytes()) {
has_te = has_te || name == header::TRANSFER_ENCODING;
has_length = has_length || name == header::CONTENT_LENGTH;
2018-03-20 23:51:19 +01:00
has_upgrade = has_upgrade || name == header::UPGRADE;
2018-03-17 04:56:23 +01:00
let v_start = header.value.as_ptr() as usize - bytes_ptr;
let v_end = v_start + header.value.len();
let value = unsafe {
HeaderValue::from_shared_unchecked(
2018-04-14 01:02:01 +02:00
slice.slice(v_start, v_end),
)
};
2018-03-17 04:56:23 +01:00
msg_mut.headers.append(name, value);
} else {
2018-04-14 01:02:01 +02:00
return Err(ParseError::Header);
2018-03-17 04:56:23 +01:00
}
2017-10-14 09:11:12 +02:00
}
2017-12-16 07:49:48 +01:00
2018-04-17 21:55:13 +02:00
msg_mut.url = path;
2018-03-17 04:56:23 +01:00
msg_mut.method = method;
msg_mut.version = version;
}
2017-12-16 07:49:48 +01:00
msg
};
2018-03-27 00:58:30 +02:00
// https://tools.ietf.org/html/rfc7230#section-3.3.3
let decoder = if has_te && chunked(&msg.get_mut().headers)? {
// Chunked encoding
Some(Decoder::chunked())
} else if has_length {
2017-12-24 23:29:19 +01:00
// Content-Length
2018-04-14 01:02:01 +02:00
let len = msg.get_ref()
.headers
.get(header::CONTENT_LENGTH)
.unwrap();
2017-12-24 23:29:19 +01:00
if let Ok(s) = len.to_str() {
if let Ok(len) = s.parse::<u64>() {
Some(Decoder::length(len))
2017-10-14 09:11:12 +02:00
} else {
debug!("illegal Content-Length: {:?}", len);
2018-04-14 01:02:01 +02:00
return Err(ParseError::Header);
2017-10-14 09:11:12 +02:00
}
2017-12-24 23:29:19 +01:00
} else {
debug!("illegal Content-Length: {:?}", len);
2018-04-14 01:02:01 +02:00
return Err(ParseError::Header);
2017-10-10 08:07:32 +02:00
}
2018-03-20 23:51:19 +01:00
} else if has_upgrade || msg.get_ref().method == Method::CONNECT {
// upgrade(websocket) or connect
2017-12-24 23:29:19 +01:00
Some(Decoder::eof())
} else {
None
2017-10-14 09:11:12 +02:00
};
2017-11-27 04:00:57 +01:00
2017-12-24 23:29:19 +01:00
if let Some(decoder) = decoder {
let (psender, payload) = Payload::new(false);
let info = PayloadInfo {
2018-03-17 04:56:23 +01:00
tx: PayloadType::new(&msg.get_ref().headers, psender),
2018-02-26 23:33:56 +01:00
decoder,
2017-12-24 23:29:19 +01:00
};
msg.get_mut().payload = Some(payload);
2018-04-14 01:02:01 +02:00
Ok(Async::Ready((
HttpRequest::from_message(msg),
Some(info),
)))
2017-12-13 06:32:58 +01:00
} else {
Ok(Async::Ready((HttpRequest::from_message(msg), None)))
2017-12-13 06:32:58 +01:00
}
}
}
/// Check if request has chunked transfer encoding
2018-01-28 07:03:03 +01:00
pub fn chunked(headers: &HeaderMap) -> Result<bool, ParseError> {
2017-12-13 06:32:58 +01:00
if let Some(encodings) = headers.get(header::TRANSFER_ENCODING) {
if let Ok(s) = encodings.to_str() {
Ok(s.to_lowercase().contains("chunked"))
} else {
Err(ParseError::Header)
}
} else {
Ok(false)
}
}
2017-11-02 20:54:09 +01:00
/// Decoders to handle different Transfer-Encodings.
///
/// If a message body does not include a Transfer-Encoding, it *should*
/// include a Content-Length header.
#[derive(Debug, Clone, PartialEq)]
2018-01-28 07:03:03 +01:00
pub struct Decoder {
2017-11-02 20:54:09 +01:00
kind: Kind,
}
impl Decoder {
pub fn length(x: u64) -> Decoder {
2018-04-14 01:02:01 +02:00
Decoder {
kind: Kind::Length(x),
}
2017-11-02 20:54:09 +01:00
}
pub fn chunked() -> Decoder {
2018-04-14 01:02:01 +02:00
Decoder {
kind: Kind::Chunked(ChunkedState::Size, 0),
}
2017-11-02 20:54:09 +01:00
}
pub fn eof() -> Decoder {
2018-04-14 01:02:01 +02:00
Decoder {
kind: Kind::Eof(false),
}
2017-11-02 20:54:09 +01:00
}
}
#[derive(Debug, Clone, PartialEq)]
enum Kind {
2018-04-14 01:02:01 +02:00
/// A Reader used when a Content-Length header is passed with a positive
/// integer.
2017-11-02 20:54:09 +01:00
Length(u64),
/// A Reader used when Transfer-Encoding is `chunked`.
Chunked(ChunkedState, u64),
/// A Reader used for responses that don't indicate a length or chunked.
///
/// Note: This should only used for `Response`s. It is illegal for a
/// `Request` to be made with both `Content-Length` and
/// `Transfer-Encoding: chunked` missing, as explained from the spec:
///
/// > If a Transfer-Encoding header field is present in a response and
/// > the chunked transfer coding is not the final encoding, the
/// > message body length is determined by reading the connection until
/// > it is closed by the server. If a Transfer-Encoding header field
/// > is present in a request and the chunked transfer coding is not
/// > the final encoding, the message body length cannot be determined
/// > reliably; the server MUST respond with the 400 (Bad Request)
/// > status code and then close the connection.
Eof(bool),
}
#[derive(Debug, PartialEq, Clone)]
enum ChunkedState {
Size,
SizeLws,
Extension,
SizeLf,
Body,
BodyCr,
BodyLf,
EndCr,
EndLf,
End,
}
impl Decoder {
2018-02-27 05:07:22 +01:00
pub fn is_eof(&self) -> bool {
match self.kind {
2018-04-14 01:02:01 +02:00
Kind::Length(0) | Kind::Chunked(ChunkedState::End, _) | Kind::Eof(true) => {
true
}
2018-02-27 05:07:22 +01:00
_ => false,
}
}
2017-11-02 20:54:09 +01:00
pub fn decode(&mut self, body: &mut BytesMut) -> Poll<Option<Bytes>, io::Error> {
match self.kind {
Kind::Length(ref mut remaining) => {
if *remaining == 0 {
Ok(Async::Ready(None))
} else {
if body.is_empty() {
2018-04-14 01:02:01 +02:00
return Ok(Async::NotReady);
2017-11-02 20:54:09 +01:00
}
let len = body.len() as u64;
let buf;
if *remaining > len {
buf = body.take().freeze();
*remaining -= len;
} else {
buf = body.split_to(*remaining as usize).freeze();
*remaining = 0;
}
trace!("Length read: {}", buf.len());
Ok(Async::Ready(Some(buf)))
}
}
Kind::Chunked(ref mut state, ref mut size) => {
loop {
let mut buf = None;
// advances the chunked state
*state = try_ready!(state.step(body, size, &mut buf));
if *state == ChunkedState::End {
trace!("End of chunked stream");
return Ok(Async::Ready(None));
}
if let Some(buf) = buf {
return Ok(Async::Ready(Some(buf)));
}
if body.is_empty() {
return Ok(Async::NotReady);
}
}
}
Kind::Eof(ref mut is_eof) => {
if *is_eof {
Ok(Async::Ready(None))
} else if !body.is_empty() {
Ok(Async::Ready(Some(body.take().freeze())))
} else {
Ok(Async::NotReady)
}
}
}
}
}
macro_rules! byte (
($rdr:ident) => ({
if $rdr.len() > 0 {
let b = $rdr[0];
$rdr.split_to(1);
b
} else {
return Ok(Async::NotReady)
}
})
);
impl ChunkedState {
2018-04-14 01:02:01 +02:00
fn step(
&self, body: &mut BytesMut, size: &mut u64, buf: &mut Option<Bytes>
) -> Poll<ChunkedState, io::Error> {
2017-11-02 20:54:09 +01:00
use self::ChunkedState::*;
match *self {
Size => ChunkedState::read_size(body, size),
SizeLws => ChunkedState::read_size_lws(body),
Extension => ChunkedState::read_extension(body),
SizeLf => ChunkedState::read_size_lf(body, size),
Body => ChunkedState::read_body(body, size, buf),
BodyCr => ChunkedState::read_body_cr(body),
BodyLf => ChunkedState::read_body_lf(body),
EndCr => ChunkedState::read_end_cr(body),
EndLf => ChunkedState::read_end_lf(body),
End => Ok(Async::Ready(ChunkedState::End)),
}
}
fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> {
let radix = 16;
match byte!(rdr) {
b @ b'0'...b'9' => {
*size *= radix;
*size += u64::from(b - b'0');
}
b @ b'a'...b'f' => {
*size *= radix;
*size += u64::from(b + 10 - b'a');
}
b @ b'A'...b'F' => {
*size *= radix;
*size += u64::from(b + 10 - b'A');
}
b'\t' | b' ' => return Ok(Async::Ready(ChunkedState::SizeLws)),
b';' => return Ok(Async::Ready(ChunkedState::Extension)),
b'\r' => return Ok(Async::Ready(ChunkedState::SizeLf)),
_ => {
2018-04-14 01:02:01 +02:00
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk size line: Invalid Size",
));
2017-11-02 20:54:09 +01:00
}
}
Ok(Async::Ready(ChunkedState::Size))
}
fn read_size_lws(rdr: &mut BytesMut) -> Poll<ChunkedState, io::Error> {
trace!("read_size_lws");
match byte!(rdr) {
// LWS can follow the chunk size, but no more digits can come
b'\t' | b' ' => Ok(Async::Ready(ChunkedState::SizeLws)),
b';' => Ok(Async::Ready(ChunkedState::Extension)),
b'\r' => Ok(Async::Ready(ChunkedState::SizeLf)),
2018-04-14 01:02:01 +02:00
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk size linear white space",
)),
2017-11-02 20:54:09 +01:00
}
}
fn read_extension(rdr: &mut BytesMut) -> Poll<ChunkedState, io::Error> {
match byte!(rdr) {
b'\r' => Ok(Async::Ready(ChunkedState::SizeLf)),
_ => Ok(Async::Ready(ChunkedState::Extension)), // no supported extensions
}
}
2018-04-14 01:02:01 +02:00
fn read_size_lf(
rdr: &mut BytesMut, size: &mut u64
) -> Poll<ChunkedState, io::Error> {
2017-11-02 20:54:09 +01:00
match byte!(rdr) {
b'\n' if *size > 0 => Ok(Async::Ready(ChunkedState::Body)),
b'\n' if *size == 0 => Ok(Async::Ready(ChunkedState::EndCr)),
2018-04-14 01:02:01 +02:00
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk size LF",
)),
2017-11-02 20:54:09 +01:00
}
}
2018-04-14 01:02:01 +02:00
fn read_body(
rdr: &mut BytesMut, rem: &mut u64, buf: &mut Option<Bytes>
) -> Poll<ChunkedState, io::Error> {
2017-11-02 20:54:09 +01:00
trace!("Chunked read, remaining={:?}", rem);
let len = rdr.len() as u64;
if len == 0 {
Ok(Async::Ready(ChunkedState::Body))
} else {
let slice;
if *rem > len {
slice = rdr.take().freeze();
*rem -= len;
} else {
slice = rdr.split_to(*rem as usize).freeze();
*rem = 0;
}
*buf = Some(slice);
if *rem > 0 {
Ok(Async::Ready(ChunkedState::Body))
} else {
Ok(Async::Ready(ChunkedState::BodyCr))
}
}
}
fn read_body_cr(rdr: &mut BytesMut) -> Poll<ChunkedState, io::Error> {
match byte!(rdr) {
b'\r' => Ok(Async::Ready(ChunkedState::BodyLf)),
2018-04-14 01:02:01 +02:00
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk body CR",
)),
2017-11-02 20:54:09 +01:00
}
}
fn read_body_lf(rdr: &mut BytesMut) -> Poll<ChunkedState, io::Error> {
match byte!(rdr) {
b'\n' => Ok(Async::Ready(ChunkedState::Size)),
2018-04-14 01:02:01 +02:00
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk body LF",
)),
2017-11-02 20:54:09 +01:00
}
}
fn read_end_cr(rdr: &mut BytesMut) -> Poll<ChunkedState, io::Error> {
match byte!(rdr) {
b'\r' => Ok(Async::Ready(ChunkedState::EndLf)),
2018-04-14 01:02:01 +02:00
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk end CR",
)),
2017-11-02 20:54:09 +01:00
}
}
fn read_end_lf(rdr: &mut BytesMut) -> Poll<ChunkedState, io::Error> {
match byte!(rdr) {
b'\n' => Ok(Async::Ready(ChunkedState::End)),
2018-04-14 01:02:01 +02:00
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk end LF",
)),
2017-11-02 20:54:09 +01:00
}
}
}
2017-10-14 09:11:12 +02:00
#[cfg(test)]
mod tests {
2018-04-14 01:02:01 +02:00
use bytes::{Buf, Bytes, BytesMut};
2018-02-27 05:07:22 +01:00
use futures::{Async, Stream};
2018-04-14 01:02:01 +02:00
use http::{Method, Version};
use std::net::Shutdown;
use std::{cmp, io, time};
use tokio_io::{AsyncRead, AsyncWrite};
use super::*;
2017-12-15 05:29:49 +01:00
use application::HttpApplication;
2018-04-14 01:02:01 +02:00
use httpmessage::HttpMessage;
2018-01-12 03:35:05 +01:00
use server::settings::WorkerSettings;
use server::{IoStream, KeepAlive};
2017-10-14 09:11:12 +02:00
struct Buffer {
buf: Bytes,
err: Option<io::Error>,
}
impl Buffer {
fn new(data: &'static str) -> Buffer {
Buffer {
buf: Bytes::from(data),
err: None,
}
}
fn feed_data(&mut self, data: &'static str) {
let mut b = BytesMut::from(self.buf.as_ref());
b.extend(data.as_bytes());
self.buf = b.take().freeze();
}
}
2017-12-02 00:45:15 +01:00
2017-10-14 09:11:12 +02:00
impl AsyncRead for Buffer {}
impl io::Read for Buffer {
fn read(&mut self, dst: &mut [u8]) -> Result<usize, io::Error> {
if self.buf.is_empty() {
if self.err.is_some() {
Err(self.err.take().unwrap())
} else {
Err(io::Error::new(io::ErrorKind::WouldBlock, ""))
}
} else {
let size = cmp::min(self.buf.len(), dst.len());
let b = self.buf.split_to(size);
dst[..size].copy_from_slice(&b);
Ok(size)
}
}
}
impl IoStream for Buffer {
2018-01-04 08:59:12 +01:00
fn shutdown(&mut self, _: Shutdown) -> io::Result<()> {
Ok(())
}
2018-01-04 08:59:12 +01:00
fn set_nodelay(&mut self, _: bool) -> io::Result<()> {
Ok(())
}
2018-01-04 08:59:12 +01:00
fn set_linger(&mut self, _: Option<time::Duration>) -> io::Result<()> {
Ok(())
}
}
impl io::Write for Buffer {
2018-04-14 01:02:01 +02:00
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl AsyncWrite for Buffer {
2018-04-14 01:02:01 +02:00
fn shutdown(&mut self) -> Poll<(), io::Error> {
Ok(Async::Ready(()))
}
fn write_buf<B: Buf>(&mut self, _: &mut B) -> Poll<usize, io::Error> {
Ok(Async::NotReady)
}
}
2017-10-14 09:11:12 +02:00
macro_rules! not_ready {
2018-04-14 01:02:01 +02:00
($e:expr) => {
match $e {
Ok(Async::NotReady) => (),
Err(err) => unreachable!("Unexpected error: {:?}", err),
_ => unreachable!("Should not be ready"),
}
};
2017-10-14 09:11:12 +02:00
}
macro_rules! parse_ready {
2018-04-14 01:02:01 +02:00
($e:expr) => {{
let settings: WorkerSettings<HttpApplication> =
WorkerSettings::new(Vec::new(), KeepAlive::Os);
2017-12-15 05:29:49 +01:00
match Reader::new().parse($e, &mut BytesMut::new(), &settings) {
Ok(Async::Ready(req)) => req,
2018-03-30 00:55:27 +02:00
Ok(_) => unreachable!("Eof during parsing http request"),
Err(err) => unreachable!("Error during parsing http request: {:?}", err),
2017-10-14 09:11:12 +02:00
}
2018-04-14 01:02:01 +02:00
}};
2017-10-14 09:11:12 +02:00
}
macro_rules! reader_parse_ready {
2018-04-14 01:02:01 +02:00
($e:expr) => {
2017-10-14 09:11:12 +02:00
match $e {
Ok(Async::Ready(req)) => req,
2018-03-30 00:55:27 +02:00
Ok(_) => unreachable!("Eof during parsing http request"),
2018-04-14 01:02:01 +02:00
Err(err) => {
unreachable!("Error during parsing http request: {:?}", err)
}
2017-10-14 09:11:12 +02:00
}
2018-04-14 01:02:01 +02:00
};
2017-10-14 09:11:12 +02:00
}
macro_rules! expect_parse_err {
2018-04-14 01:02:01 +02:00
($e:expr) => {{
let mut buf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings: WorkerSettings<HttpApplication> =
WorkerSettings::new(Vec::new(), KeepAlive::Os);
2017-12-15 05:29:49 +01:00
match Reader::new().parse($e, &mut buf, &settings) {
Err(err) => match err {
ReaderError::Error(_) => (),
2018-03-30 00:55:27 +02:00
_ => unreachable!("Parse error expected"),
},
2018-04-14 01:02:01 +02:00
_ => unreachable!("Error expected"),
}
}};
2017-10-14 09:11:12 +02:00
}
#[test]
fn test_parse() {
let mut buf = Buffer::new("GET /test HTTP/1.1\r\n\r\n");
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(req)) => {
2017-10-14 09:11:12 +02:00
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method::GET);
assert_eq!(req.path(), "/test");
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_parse_partial() {
let mut buf = Buffer::new("PUT /test HTTP/1");
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
2017-10-14 09:11:12 +02:00
Ok(Async::NotReady) => (),
2018-03-30 00:55:27 +02:00
_ => unreachable!("Error"),
2017-10-14 09:11:12 +02:00
}
buf.feed_data(".1\r\n\r\n");
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(req)) => {
2017-10-14 09:11:12 +02:00
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method::PUT);
assert_eq!(req.path(), "/test");
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_parse_post() {
let mut buf = Buffer::new("POST /test2 HTTP/1.0\r\n\r\n");
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(req)) => {
2017-10-14 09:11:12 +02:00
assert_eq!(req.version(), Version::HTTP_10);
assert_eq!(*req.method(), Method::POST);
assert_eq!(req.path(), "/test2");
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_parse_body() {
let mut buf = Buffer::new("GET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody");
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(mut req)) => {
2017-10-14 09:11:12 +02:00
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method::GET);
assert_eq!(req.path(), "/test");
2017-12-19 09:18:57 +01:00
assert_eq!(req.payload_mut().readall().unwrap().as_ref(), b"body");
2017-10-14 09:11:12 +02:00
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_parse_body_crlf() {
2018-04-14 01:02:01 +02:00
let mut buf =
Buffer::new("\r\nGET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody");
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(mut req)) => {
2017-10-14 09:11:12 +02:00
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method::GET);
assert_eq!(req.path(), "/test");
2017-12-19 09:18:57 +01:00
assert_eq!(req.payload_mut().readall().unwrap().as_ref(), b"body");
2017-10-14 09:11:12 +02:00
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_parse_partial_eof() {
let mut buf = Buffer::new("GET /test HTTP/1.1\r\n");
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
not_ready!{ reader.parse(&mut buf, &mut readbuf, &settings) }
2017-10-14 09:11:12 +02:00
buf.feed_data("\r\n");
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(req)) => {
2017-10-14 09:11:12 +02:00
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method::GET);
assert_eq!(req.path(), "/test");
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_headers_split_field() {
let mut buf = Buffer::new("GET /test HTTP/1.1\r\n");
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
not_ready!{ reader.parse(&mut buf, &mut readbuf, &settings) }
2017-10-14 09:11:12 +02:00
buf.feed_data("t");
2017-12-15 05:29:49 +01:00
not_ready!{ reader.parse(&mut buf, &mut readbuf, &settings) }
2017-10-14 09:11:12 +02:00
buf.feed_data("es");
2017-12-15 05:29:49 +01:00
not_ready!{ reader.parse(&mut buf, &mut readbuf, &settings) }
2017-10-14 09:11:12 +02:00
buf.feed_data("t: value\r\n\r\n");
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(req)) => {
2017-10-14 09:11:12 +02:00
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method::GET);
assert_eq!(req.path(), "/test");
2018-04-14 01:02:01 +02:00
assert_eq!(
req.headers().get("test").unwrap().as_bytes(),
b"value"
);
2017-10-14 09:11:12 +02:00
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_headers_multi_value() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
Set-Cookie: c1=cookie1\r\n\
2018-04-14 01:02:01 +02:00
Set-Cookie: c2=cookie2\r\n\r\n",
);
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2017-12-15 05:29:49 +01:00
match reader.parse(&mut buf, &mut readbuf, &settings) {
Ok(Async::Ready(req)) => {
2018-04-14 01:02:01 +02:00
let val: Vec<_> = req.headers()
.get_all("Set-Cookie")
.iter()
.map(|v| v.to_str().unwrap().to_owned())
.collect();
2017-10-14 09:11:12 +02:00
assert_eq!(val[0], "c1=cookie1");
assert_eq!(val[1], "c2=cookie2");
}
2018-03-30 00:55:27 +02:00
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
2017-10-14 09:11:12 +02:00
}
}
#[test]
fn test_conn_default_1_0() {
let mut buf = Buffer::new("GET /test HTTP/1.0\r\n\r\n");
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(!req.keep_alive());
}
#[test]
fn test_conn_default_1_1() {
let mut buf = Buffer::new("GET /test HTTP/1.1\r\n\r\n");
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(req.keep_alive());
}
#[test]
fn test_conn_close() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
connection: close\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(!req.keep_alive());
}
#[test]
fn test_conn_close_1_0() {
let mut buf = Buffer::new(
"GET /test HTTP/1.0\r\n\
2018-04-14 01:02:01 +02:00
connection: close\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(!req.keep_alive());
}
#[test]
fn test_conn_keep_alive_1_0() {
let mut buf = Buffer::new(
"GET /test HTTP/1.0\r\n\
2018-04-14 01:02:01 +02:00
connection: keep-alive\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(req.keep_alive());
}
#[test]
fn test_conn_keep_alive_1_1() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
connection: keep-alive\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(req.keep_alive());
}
#[test]
fn test_conn_other_1_0() {
let mut buf = Buffer::new(
"GET /test HTTP/1.0\r\n\
2018-04-14 01:02:01 +02:00
connection: other\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(!req.keep_alive());
}
#[test]
fn test_conn_other_1_1() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
connection: other\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(req.keep_alive());
}
#[test]
fn test_conn_upgrade() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2017-12-25 01:15:40 +01:00
upgrade: websockets\r\n\
2018-04-14 01:02:01 +02:00
connection: upgrade\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2017-10-14 09:11:12 +02:00
assert!(req.upgrade());
}
#[test]
fn test_conn_upgrade_connect_method() {
let mut buf = Buffer::new(
"CONNECT /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
content-type: text/plain\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(req.upgrade());
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2017-10-14 09:11:12 +02:00
}
#[test]
fn test_request_chunked() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
if let Ok(val) = req.chunked() {
assert!(val);
} else {
2018-03-30 00:55:27 +02:00
unreachable!("Error");
2017-10-14 09:11:12 +02:00
}
2018-01-21 01:51:18 +01:00
// type in chunked
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chnked\r\n\r\n",
);
2018-01-21 01:51:18 +01:00
let req = parse_ready!(&mut buf);
if let Ok(val) = req.chunked() {
assert!(!val);
} else {
2018-03-30 00:55:27 +02:00
unreachable!("Error");
2018-01-21 01:51:18 +01:00
}
2017-10-14 09:11:12 +02:00
}
#[test]
fn test_headers_content_length_err_1() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
content-length: line\r\n\r\n",
);
2017-10-14 09:11:12 +02:00
expect_parse_err!(&mut buf)
}
#[test]
fn test_headers_content_length_err_2() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
content-length: -1\r\n\r\n",
);
2017-10-14 09:11:12 +02:00
expect_parse_err!(&mut buf);
}
#[test]
fn test_invalid_header() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
test line\r\n\r\n",
);
2017-10-14 09:11:12 +02:00
expect_parse_err!(&mut buf);
}
#[test]
fn test_invalid_name() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
test[]: line\r\n\r\n",
);
2017-10-14 09:11:12 +02:00
expect_parse_err!(&mut buf);
}
#[test]
fn test_http_request_bad_status_line() {
let mut buf = Buffer::new("getpath \r\n\r\n");
expect_parse_err!(&mut buf);
}
#[test]
fn test_http_request_upgrade() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
connection: upgrade\r\n\
upgrade: websocket\r\n\r\n\
2018-04-14 01:02:01 +02:00
some raw data",
);
2017-11-27 04:00:57 +01:00
let mut req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert!(!req.keep_alive());
assert!(req.upgrade());
2018-04-14 01:02:01 +02:00
assert_eq!(
req.payload_mut().readall().unwrap().as_ref(),
b"some raw data"
);
2017-10-14 09:11:12 +02:00
}
#[test]
fn test_http_request_parser_utf8() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
x-test: тест\r\n\r\n",
);
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
2018-04-14 01:02:01 +02:00
assert_eq!(
req.headers().get("x-test").unwrap().as_bytes(),
"тест".as_bytes()
);
2017-10-14 09:11:12 +02:00
}
#[test]
fn test_http_request_parser_two_slashes() {
2018-04-14 01:02:01 +02:00
let mut buf = Buffer::new("GET //path HTTP/1.1\r\n\r\n");
2017-11-27 04:00:57 +01:00
let req = parse_ready!(&mut buf);
2017-10-14 09:11:12 +02:00
assert_eq!(req.path(), "//path");
}
#[test]
fn test_http_request_parser_bad_method() {
2018-04-14 01:02:01 +02:00
let mut buf = Buffer::new("!12%()+=~$ /get HTTP/1.1\r\n\r\n");
2017-10-14 09:11:12 +02:00
expect_parse_err!(&mut buf);
}
#[test]
fn test_http_request_parser_bad_version() {
let mut buf = Buffer::new("GET //get HT/11\r\n\r\n");
expect_parse_err!(&mut buf);
}
#[test]
fn test_http_request_chunked_payload() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:11:12 +02:00
let mut reader = Reader::new();
2018-04-14 01:02:01 +02:00
let mut req =
reader_parse_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:11:12 +02:00
assert!(req.chunked().unwrap());
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2017-10-14 09:11:12 +02:00
buf.feed_data("4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n");
2018-02-27 05:07:22 +01:00
let _ = req.payload_mut().poll();
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2018-04-14 01:02:01 +02:00
assert_eq!(
req.payload_mut().readall().unwrap().as_ref(),
b"dataline"
);
2017-12-19 09:18:57 +01:00
assert!(req.payload().eof());
2017-10-14 09:11:12 +02:00
}
2017-10-14 09:28:49 +02:00
#[test]
fn test_http_request_chunked_payload_and_next_message() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:28:49 +02:00
let mut reader = Reader::new();
2018-04-14 01:02:01 +02:00
let mut req =
reader_parse_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
assert!(req.chunked().unwrap());
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2017-10-14 09:28:49 +02:00
buf.feed_data(
"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n\
POST /test2 HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
2018-02-27 05:07:22 +01:00
let _ = req.payload_mut().poll();
2017-10-14 09:28:49 +02:00
2017-12-15 05:29:49 +01:00
let req2 = reader_parse_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
assert_eq!(*req2.method(), Method::POST);
assert!(req2.chunked().unwrap());
2017-12-19 09:18:57 +01:00
assert!(!req2.payload().eof());
2017-10-14 09:28:49 +02:00
2018-04-14 01:02:01 +02:00
assert_eq!(
req.payload_mut().readall().unwrap().as_ref(),
b"dataline"
);
2017-12-19 09:18:57 +01:00
assert!(req.payload().eof());
2017-10-14 09:28:49 +02:00
}
#[test]
fn test_http_request_chunked_payload_chunks() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:28:49 +02:00
let mut reader = Reader::new();
2018-04-14 01:02:01 +02:00
let mut req =
reader_parse_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2018-04-05 05:24:09 +02:00
req.payload_mut().set_read_buffer_capacity(0);
2017-10-14 09:28:49 +02:00
assert!(req.chunked().unwrap());
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2017-10-14 09:28:49 +02:00
2018-03-03 07:08:56 +01:00
buf.feed_data("4\r\n1111\r\n");
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
assert_eq!(req.payload_mut().readall().unwrap().as_ref(), b"1111");
2017-10-14 09:28:49 +02:00
buf.feed_data("4\r\ndata\r");
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
buf.feed_data("\n4");
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
buf.feed_data("\r");
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
buf.feed_data("\n");
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
buf.feed_data("li");
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
buf.feed_data("ne\r\n0\r\n");
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
2018-03-03 07:08:56 +01:00
//trailers
2017-10-14 09:28:49 +02:00
//buf.feed_data("test: test\r\n");
//not_ready!(reader.parse(&mut buf, &mut readbuf));
2017-10-14 09:28:49 +02:00
2018-02-27 05:07:22 +01:00
let _ = req.payload_mut().poll();
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2018-04-14 01:02:01 +02:00
assert_eq!(
req.payload_mut().readall().unwrap().as_ref(),
b"dataline"
);
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2017-10-14 09:28:49 +02:00
buf.feed_data("\r\n");
2018-02-27 05:07:22 +01:00
let _ = req.payload_mut().poll();
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-12-19 09:18:57 +01:00
assert!(req.payload().eof());
2017-10-14 09:28:49 +02:00
}
#[test]
fn test_parse_chunked_payload_chunk_extension() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
let mut readbuf = BytesMut::new();
2018-04-14 01:02:01 +02:00
let settings = WorkerSettings::<HttpApplication>::new(Vec::new(), KeepAlive::Os);
2017-10-14 09:28:49 +02:00
let mut reader = Reader::new();
2018-04-14 01:02:01 +02:00
let mut req =
reader_parse_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-10-14 09:28:49 +02:00
assert!(req.chunked().unwrap());
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2017-10-14 09:28:49 +02:00
buf.feed_data("4;test\r\ndata\r\n4\r\nline\r\n0\r\n\r\n"); // test: test\r\n\r\n")
2018-02-27 05:07:22 +01:00
let _ = req.payload_mut().poll();
2017-12-15 05:29:49 +01:00
not_ready!(reader.parse(&mut buf, &mut readbuf, &settings));
2017-12-19 09:18:57 +01:00
assert!(!req.payload().eof());
2018-04-14 01:02:01 +02:00
assert_eq!(
req.payload_mut().readall().unwrap().as_ref(),
b"dataline"
);
2017-12-19 09:18:57 +01:00
assert!(req.payload().eof());
2017-10-14 09:28:49 +02:00
}
2017-10-14 09:11:12 +02:00
/*#[test]
#[should_panic]
fn test_parse_multiline() {
let mut buf = Buffer::new(
"GET /test HTTP/1.1\r\n\
test: line\r\n \
continue\r\n\
test2: data\r\n\
\r\n", false);
let mut reader = Reader::new();
match reader.parse(&mut buf) {
Ok(res) => (),
2018-03-30 00:55:27 +02:00
Err(err) => unreachable!("{:?}", err),
2017-10-14 09:11:12 +02:00
}
}*/
}