1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 17:52:40 +01:00
actix-extras/src/server/h1.rs

1290 lines
42 KiB
Rust
Raw Normal View History

2018-04-14 01:02:01 +02:00
use std::collections::VecDeque;
2018-10-02 05:53:22 +02:00
use std::net::{Shutdown, SocketAddr};
use std::time::{Duration, Instant};
2017-10-07 06:48:14 +02:00
2018-06-22 07:30:40 +02:00
use bytes::BytesMut;
2018-04-14 01:02:01 +02:00
use futures::{Async, Future, Poll};
2018-10-02 04:18:24 +02:00
use tokio_current_thread::spawn;
2018-05-25 06:03:16 +02:00
use tokio_timer::Delay;
2017-10-07 06:48:14 +02:00
2018-06-18 01:45:54 +02:00
use error::{Error, PayloadError};
2018-06-25 06:58:04 +02:00
use http::{StatusCode, Version};
2018-04-14 01:02:01 +02:00
use payload::{Payload, PayloadStatus, PayloadWriter};
2017-10-07 06:48:14 +02:00
use super::error::{HttpDispatchError, ServerError};
2018-04-29 07:20:32 +02:00
use super::h1decoder::{DecoderError, H1Decoder, Message};
2018-04-14 01:02:01 +02:00
use super::h1writer::H1Writer;
2018-10-02 04:18:24 +02:00
use super::handler::{HttpHandler, HttpHandlerTask, HttpHandlerTaskFut};
2018-06-24 06:42:20 +02:00
use super::input::PayloadType;
use super::settings::ServiceConfig;
2018-10-02 04:18:24 +02:00
use super::{IoStream, Writer};
2018-01-12 03:35:05 +01:00
const MAX_PIPELINED_MESSAGES: usize = 16;
2017-10-07 06:48:14 +02:00
bitflags! {
2018-09-01 02:24:13 +02:00
pub struct Flags: u8 {
const STARTED = 0b0000_0001;
2018-10-02 07:23:02 +02:00
const KEEPALIVE_ENABLED = 0b0000_0010;
2018-09-01 02:24:13 +02:00
const KEEPALIVE = 0b0000_0100;
const SHUTDOWN = 0b0000_1000;
const READ_DISCONNECTED = 0b0001_0000;
const WRITE_DISCONNECTED = 0b0010_0000;
const POLLED = 0b0100_0000;
2018-10-02 19:43:23 +02:00
const FLUSHED = 0b1000_0000;
}
}
2018-10-02 07:23:02 +02:00
/// Dispatcher for HTTP/1.1 protocol
pub struct Http1Dispatcher<T: IoStream, H: HttpHandler + 'static> {
flags: Flags,
settings: ServiceConfig<H>,
addr: Option<SocketAddr>,
2018-03-18 19:05:44 +01:00
stream: H1Writer<T, H>,
2018-04-29 07:20:32 +02:00
decoder: H1Decoder,
payload: Option<PayloadType>,
buf: BytesMut,
2018-06-18 01:45:54 +02:00
tasks: VecDeque<Entry<H>>,
2018-10-02 04:18:24 +02:00
error: Option<HttpDispatchError>,
2018-09-29 00:04:59 +02:00
ka_expire: Instant,
ka_timer: Option<Delay>,
}
2018-10-02 04:18:24 +02:00
enum Entry<H: HttpHandler> {
2018-06-18 01:45:54 +02:00
Task(H::Task),
Error(Box<HttpHandlerTask>),
}
2018-10-02 04:18:24 +02:00
impl<H: HttpHandler> Entry<H> {
fn into_task(self) -> H::Task {
match self {
Entry::Task(task) => task,
Entry::Error(_) => panic!(),
}
}
2018-06-18 01:45:54 +02:00
fn disconnected(&mut self) {
match *self {
2018-10-02 04:18:24 +02:00
Entry::Task(ref mut task) => task.disconnected(),
Entry::Error(ref mut task) => task.disconnected(),
2018-06-18 01:45:54 +02:00
}
}
fn poll_io(&mut self, io: &mut Writer) -> Poll<bool, Error> {
match *self {
2018-10-02 04:18:24 +02:00
Entry::Task(ref mut task) => task.poll_io(io),
Entry::Error(ref mut task) => task.poll_io(io),
2018-06-18 01:45:54 +02:00
}
}
fn poll_completed(&mut self) -> Poll<(), Error> {
match *self {
2018-10-02 04:18:24 +02:00
Entry::Task(ref mut task) => task.poll_completed(),
Entry::Error(ref mut task) => task.poll_completed(),
2018-06-18 01:45:54 +02:00
}
}
}
2018-10-02 07:23:02 +02:00
impl<T, H> Http1Dispatcher<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(
2018-10-03 02:30:29 +02:00
settings: ServiceConfig<H>, stream: T, buf: BytesMut, is_eof: bool,
keepalive_timer: Option<Delay>,
2018-04-14 01:02:01 +02:00
) -> Self {
2018-10-03 02:30:29 +02:00
let addr = stream.peer_addr();
2018-09-29 00:04:59 +02:00
let (ka_expire, ka_timer) = if let Some(delay) = keepalive_timer {
(delay.deadline(), Some(delay))
} else if let Some(delay) = settings.keep_alive_timer() {
(delay.deadline(), Some(delay))
} else {
(settings.now(), None)
};
2018-10-02 07:48:11 +02:00
let flags = if is_eof {
2018-10-02 19:43:23 +02:00
Flags::READ_DISCONNECTED | Flags::FLUSHED
2018-10-02 07:23:02 +02:00
} else if settings.keep_alive_enabled() {
2018-10-02 19:43:23 +02:00
Flags::KEEPALIVE | Flags::KEEPALIVE_ENABLED | Flags::FLUSHED
2018-10-02 07:23:02 +02:00
} else {
Flags::empty()
};
Http1Dispatcher {
2018-09-08 18:20:18 +02:00
stream: H1Writer::new(stream, settings.clone()),
2018-04-29 07:20:32 +02:00
decoder: H1Decoder::new(),
payload: None,
2018-04-14 01:02:01 +02:00
tasks: VecDeque::new(),
2018-10-02 00:19:49 +02:00
error: None,
2018-10-03 02:30:29 +02:00
flags,
2018-04-14 01:02:01 +02:00
addr,
2018-04-29 07:20:32 +02:00
buf,
2018-04-14 01:02:01 +02:00
settings,
2018-09-29 00:04:59 +02:00
ka_timer,
ka_expire,
2018-02-26 23:33:56 +01:00
}
}
pub(crate) fn for_error(
settings: ServiceConfig<H>, stream: T, status: StatusCode,
mut keepalive_timer: Option<Delay>, buf: BytesMut,
) -> Self {
if let Some(deadline) = settings.client_timer_expire() {
let _ = keepalive_timer.as_mut().map(|delay| delay.reset(deadline));
}
let mut disp = Http1Dispatcher {
2018-10-02 19:43:23 +02:00
flags: Flags::STARTED | Flags::READ_DISCONNECTED | Flags::FLUSHED,
stream: H1Writer::new(stream, settings.clone()),
decoder: H1Decoder::new(),
payload: None,
tasks: VecDeque::new(),
error: None,
addr: None,
ka_timer: keepalive_timer,
ka_expire: settings.now(),
buf,
settings,
};
disp.push_response_entry(status);
disp
}
2018-04-29 07:20:32 +02:00
#[inline]
fn can_read(&self) -> bool {
if self.flags.contains(Flags::READ_DISCONNECTED) {
2018-09-01 03:56:21 +02:00
return false;
2018-09-01 02:24:13 +02:00
}
2018-04-29 07:20:32 +02:00
if let Some(ref info) = self.payload {
info.need_read() == PayloadStatus::Read
} else {
true
}
}
2018-10-02 04:18:24 +02:00
// if checked is set to true, delay disconnect until all tasks have finished.
fn client_disconnected(&mut self, checked: bool) {
self.flags.insert(Flags::READ_DISCONNECTED);
if let Some(mut payload) = self.payload.take() {
payload.set_error(PayloadError::Incomplete);
2018-07-05 08:50:54 +02:00
}
2018-08-26 16:21:05 +02:00
2018-10-02 04:18:24 +02:00
if !checked || self.tasks.is_empty() {
2018-10-02 19:43:23 +02:00
self.flags
.insert(Flags::WRITE_DISCONNECTED | Flags::FLUSHED);
2018-10-02 04:18:24 +02:00
self.stream.disconnected();
2018-08-26 16:21:05 +02:00
2018-10-02 04:18:24 +02:00
// notify all tasks
for mut task in self.tasks.drain(..) {
task.disconnected();
match task.poll_completed() {
Ok(Async::NotReady) => {
// spawn not completed task, it does not require access to io
// at this point
spawn(HttpHandlerTaskFut::new(task.into_task()));
}
Ok(Async::Ready(_)) => (),
Err(err) => {
error!("Unhandled application error: {}", err);
}
}
}
2018-08-26 16:21:05 +02:00
}
}
2018-04-29 07:20:32 +02:00
#[inline]
pub fn poll(&mut self) -> Poll<(), HttpDispatchError> {
2018-09-29 00:04:59 +02:00
// check connection keep-alive
self.poll_keepalive()?;
2018-03-13 00:16:17 +01:00
// shutdown
if self.flags.contains(Flags::SHUTDOWN) {
2018-10-02 20:32:43 +02:00
if self.flags.contains(Flags::WRITE_DISCONNECTED) {
2018-09-01 03:56:21 +02:00
return Ok(Async::Ready(()));
2018-09-01 02:24:13 +02:00
}
2018-10-02 19:43:23 +02:00
return self.poll_flush(true);
2018-03-13 00:16:17 +01:00
}
2018-10-02 19:43:23 +02:00
// process incoming requests
2018-10-02 04:18:24 +02:00
if !self.flags.contains(Flags::WRITE_DISCONNECTED) {
2018-10-02 19:43:23 +02:00
self.poll_handler()?;
// flush stream
self.poll_flush(false)?;
// deal with keep-alive and stream eof (client-side write shutdown)
2018-10-02 20:32:43 +02:00
if self.tasks.is_empty() && self.flags.contains(Flags::FLUSHED) {
2018-10-02 19:43:23 +02:00
// handle stream eof
if self
.flags
.intersects(Flags::READ_DISCONNECTED | Flags::WRITE_DISCONNECTED)
{
return Ok(Async::Ready(()));
}
// no keep-alive
if self.flags.contains(Flags::STARTED)
&& (!self.flags.contains(Flags::KEEPALIVE_ENABLED)
|| !self.flags.contains(Flags::KEEPALIVE))
{
2018-03-13 00:16:17 +01:00
self.flags.insert(Flags::SHUTDOWN);
2018-10-02 19:43:23 +02:00
return self.poll();
2018-04-14 01:02:01 +02:00
}
2018-10-02 19:43:23 +02:00
}
Ok(Async::NotReady)
} else if let Some(err) = self.error.take() {
Err(err)
} else {
Ok(Async::Ready(()))
}
}
/// Flush stream
fn poll_flush(&mut self, shutdown: bool) -> Poll<(), HttpDispatchError> {
if shutdown || self.flags.contains(Flags::STARTED) {
match self.stream.poll_completed(shutdown) {
Ok(Async::NotReady) => {
// mark stream
if !self.stream.flushed() {
self.flags.remove(Flags::FLUSHED);
2018-09-29 00:04:59 +02:00
}
2018-10-02 04:18:24 +02:00
Ok(Async::NotReady)
2018-09-29 00:04:59 +02:00
}
2018-10-02 19:43:23 +02:00
Err(err) => {
debug!("Error sending data: {}", err);
self.client_disconnected(false);
Err(err.into())
2018-10-02 19:43:23 +02:00
}
Ok(Async::Ready(_)) => {
// if payload is not consumed we can not use connection
if self.payload.is_some() && self.tasks.is_empty() {
return Err(HttpDispatchError::PayloadIsNotConsumed);
}
self.flags.insert(Flags::FLUSHED);
Ok(Async::Ready(()))
}
2018-02-27 05:07:22 +01:00
}
2018-10-02 04:18:24 +02:00
} else {
Ok(Async::Ready(()))
2018-02-27 05:07:22 +01:00
}
}
2018-09-29 00:04:59 +02:00
/// keep-alive timer. returns `true` is keep-alive, otherwise drop
fn poll_keepalive(&mut self) -> Result<(), HttpDispatchError> {
2018-10-02 04:18:24 +02:00
if let Some(ref mut timer) = self.ka_timer {
2018-09-29 00:04:59 +02:00
match timer.poll() {
Ok(Async::Ready(_)) => {
// if we get timer during shutdown, just drop connection
if self.flags.contains(Flags::SHUTDOWN) {
let io = self.stream.get_mut();
let _ = IoStream::set_linger(io, Some(Duration::from_secs(0)));
let _ = IoStream::shutdown(io, Shutdown::Both);
return Err(HttpDispatchError::ShutdownTimeout);
}
2018-09-29 00:04:59 +02:00
if timer.deadline() >= self.ka_expire {
// check for any outstanding request handling
if self.tasks.is_empty() {
if !self.flags.contains(Flags::STARTED) {
// timeout on first request (slow request) return 408
trace!("Slow request timeout");
self.flags
.insert(Flags::STARTED | Flags::READ_DISCONNECTED);
self.tasks.push_back(Entry::Error(ServerError::err(
Version::HTTP_11,
StatusCode::REQUEST_TIMEOUT,
)));
2018-09-29 00:04:59 +02:00
} else {
trace!("Keep-alive timeout, close connection");
self.flags.insert(Flags::SHUTDOWN);
2018-10-02 05:04:16 +02:00
// start shutdown timer
if let Some(deadline) =
self.settings.client_shutdown_timer()
{
timer.reset(deadline)
} else {
return Ok(());
}
2018-09-29 00:04:59 +02:00
}
} else if let Some(dl) = self.settings.keep_alive_expire() {
timer.reset(dl)
2018-09-29 00:04:59 +02:00
}
} else {
2018-10-02 04:18:24 +02:00
timer.reset(self.ka_expire)
2018-09-29 00:04:59 +02:00
}
}
2018-10-02 04:18:24 +02:00
Ok(Async::NotReady) => (),
2018-09-29 00:04:59 +02:00
Err(e) => {
error!("Timer error {:?}", e);
2018-10-02 04:18:24 +02:00
return Err(HttpDispatchError::Unknown);
2018-09-29 00:04:59 +02:00
}
}
}
2018-10-02 04:18:24 +02:00
Ok(())
2018-09-29 00:04:59 +02:00
}
2018-04-29 07:20:32 +02:00
#[inline]
2018-10-02 19:43:23 +02:00
/// read data from the stream
pub(self) fn poll_io(&mut self) -> Result<bool, HttpDispatchError> {
2018-06-22 07:30:40 +02:00
if !self.flags.contains(Flags::POLLED) {
self.flags.insert(Flags::POLLED);
2018-10-03 02:30:29 +02:00
if !self.buf.is_empty() {
let updated = self.parse()?;
return Ok(updated);
}
2018-06-22 07:30:40 +02:00
}
2018-09-01 02:24:13 +02:00
2018-04-29 07:20:32 +02:00
// read io from socket
2018-10-02 19:43:23 +02:00
let mut updated = false;
2018-09-01 02:24:13 +02:00
if self.can_read() && self.tasks.len() < MAX_PIPELINED_MESSAGES {
2018-06-25 06:58:04 +02:00
match self.stream.get_mut().read_available(&mut self.buf) {
2018-08-26 16:21:05 +02:00
Ok(Async::Ready((read_some, disconnected))) => {
if read_some && self.parse()? {
updated = true;
2018-08-26 16:21:05 +02:00
}
2018-06-22 07:30:40 +02:00
if disconnected {
2018-10-02 04:18:24 +02:00
self.client_disconnected(true);
2018-06-22 07:30:40 +02:00
}
2018-04-29 18:09:08 +02:00
}
2018-06-22 07:30:40 +02:00
Ok(Async::NotReady) => (),
2018-10-02 04:18:24 +02:00
Err(err) => {
self.client_disconnected(false);
return Err(err.into());
2018-04-29 07:20:32 +02:00
}
2018-02-10 07:26:48 +01:00
}
2018-04-29 07:20:32 +02:00
}
2018-10-02 19:43:23 +02:00
Ok(updated)
2018-04-29 07:20:32 +02:00
}
2018-02-10 07:26:48 +01:00
2018-10-02 19:43:23 +02:00
pub(self) fn poll_handler(&mut self) -> Result<(), HttpDispatchError> {
self.poll_io()?;
let mut retry = self.can_read();
2018-02-27 05:07:22 +01:00
2018-10-02 19:43:23 +02:00
// process first pipelined response, only first task can do io operation in http/1
2018-10-02 04:18:24 +02:00
while !self.tasks.is_empty() {
match self.tasks[0].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);
2018-04-14 01:02:01 +02:00
}
2018-10-02 04:18:24 +02:00
// prepare stream for next response
self.stream.reset();
2018-09-29 00:04:59 +02:00
2018-10-02 04:18:24 +02:00
let task = self.tasks.pop_front().unwrap();
if !ready {
// task is done with io operations but still needs to do more work
spawn(HttpHandlerTaskFut::new(task.into_task()));
}
}
2018-10-02 04:18:24 +02:00
Ok(Async::NotReady) => {
// check if we need timer
if self.ka_timer.is_some() && self.stream.upgrade() {
self.ka_timer.take();
2018-09-01 03:56:21 +02:00
}
2018-10-02 04:18:24 +02:00
// if read-backpressure is enabled and we consumed some data.
2018-10-02 19:43:23 +02:00
// we may read more dataand retry
if !retry && self.can_read() && self.poll_io()? {
retry = self.can_read();
continue;
}
2018-10-02 04:18:24 +02:00
break;
}
Err(err) => {
error!("Unhandled error1: {}", err);
// it is not possible to recover from error
// during pipe handling, so just drop connection
self.client_disconnected(false);
return Err(err.into());
}
}
}
2018-10-02 04:18:24 +02:00
// check in-flight messages. all tasks must be alive,
// they need to produce response. if app returned error
// and we can not continue processing incoming requests.
let mut idx = 1;
while idx < self.tasks.len() {
let stop = match self.tasks[idx].poll_completed() {
Ok(Async::NotReady) => false,
Ok(Async::Ready(_)) => true,
Err(err) => {
self.error = Some(err.into());
true
}
};
if stop {
// error in task handling or task is completed,
// so no response for this task which means we can not read more requests
// because pipeline sequence is broken.
// but we can safely complete existing tasks
self.flags.insert(Flags::READ_DISCONNECTED);
for mut task in self.tasks.drain(idx..) {
task.disconnected();
match task.poll_completed() {
Ok(Async::NotReady) => {
// spawn not completed task, it does not require access to io
// at this point
spawn(HttpHandlerTaskFut::new(task.into_task()));
}
Ok(Async::Ready(_)) => (),
Err(err) => {
error!("Unhandled application error: {}", err);
}
}
}
2018-04-14 01:02:01 +02:00
break;
2018-10-02 04:18:24 +02:00
} else {
idx += 1;
2018-02-10 07:26:48 +01:00
}
}
2018-10-02 19:43:23 +02:00
Ok(())
}
fn push_response_entry(&mut self, status: StatusCode) {
2018-10-02 04:18:24 +02:00
self.tasks
.push_back(Entry::Error(ServerError::err(Version::HTTP_11, status)));
}
2018-10-02 19:43:23 +02:00
pub(self) fn parse(&mut self) -> Result<bool, HttpDispatchError> {
2018-09-29 00:04:59 +02:00
let mut updated = false;
2018-04-29 07:20:32 +02:00
'outer: loop {
match self.decoder.decode(&mut self.buf, &self.settings) {
2018-06-18 00:41:41 +02:00
Ok(Some(Message::Message { mut msg, payload })) => {
2018-09-29 00:04:59 +02:00
updated = true;
2018-04-29 07:20:32 +02:00
self.flags.insert(Flags::STARTED);
2018-03-18 19:05:44 +01:00
2018-04-29 07:20:32 +02:00
if payload {
let (ps, pl) = Payload::new(false);
2018-06-25 06:58:04 +02:00
*msg.inner.payload.borrow_mut() = Some(pl);
self.payload = Some(PayloadType::new(&msg.inner.headers, ps));
2018-02-27 05:07:22 +01:00
}
2018-02-10 01:20:10 +01:00
// stream extensions
msg.inner_mut().stream_extensions =
self.stream.get_mut().extensions();
2018-04-29 07:20:32 +02:00
// set remote addr
2018-07-04 18:52:49 +02:00
msg.inner_mut().addr = self.addr;
2018-02-10 01:20:10 +01:00
2018-04-29 07:20:32 +02:00
// search handler for request
2018-09-09 23:33:45 +02:00
match self.settings.handler().handle(msg) {
2018-10-02 04:18:24 +02:00
Ok(mut task) => {
2018-09-09 23:33:45 +02:00
if self.tasks.is_empty() {
2018-10-02 04:18:24 +02:00
match task.poll_io(&mut self.stream) {
2018-09-09 23:33:45 +02:00
Ok(Async::Ready(ready)) => {
// override keep-alive state
if self.stream.keepalive() {
self.flags.insert(Flags::KEEPALIVE);
} else {
self.flags.remove(Flags::KEEPALIVE);
2018-05-16 01:41:46 +02:00
}
2018-09-09 23:33:45 +02:00
// prepare stream for next response
self.stream.reset();
if !ready {
2018-10-02 04:18:24 +02:00
// task is done with io operations
// but still needs to do more work
spawn(HttpHandlerTaskFut::new(task));
2018-05-16 01:41:46 +02:00
}
2018-09-09 23:33:45 +02:00
continue 'outer;
}
2018-09-29 00:04:59 +02:00
Ok(Async::NotReady) => (),
2018-09-09 23:33:45 +02:00
Err(err) => {
error!("Unhandled error: {}", err);
2018-10-02 04:18:24 +02:00
self.client_disconnected(false);
return Err(err.into());
2018-05-16 01:41:46 +02:00
}
}
}
2018-10-02 04:18:24 +02:00
self.tasks.push_back(Entry::Task(task));
2018-09-09 23:33:45 +02:00
continue 'outer;
}
Err(_) => {
2018-09-09 23:33:45 +02:00
// handler is not found
2018-10-02 04:18:24 +02:00
self.push_response_entry(StatusCode::NOT_FOUND);
}
2018-02-10 01:20:10 +01:00
}
2018-04-14 01:02:01 +02:00
}
2018-04-29 07:20:32 +02:00
Ok(Some(Message::Chunk(chunk))) => {
2018-09-29 00:04:59 +02:00
updated = true;
2018-04-29 07:20:32 +02:00
if let Some(ref mut payload) = self.payload {
payload.feed_data(chunk);
} else {
error!("Internal server error: unexpected payload chunk");
2018-10-02 19:43:23 +02:00
self.flags.insert(Flags::READ_DISCONNECTED | Flags::STARTED);
self.push_response_entry(StatusCode::INTERNAL_SERVER_ERROR);
2018-10-02 04:18:24 +02:00
self.error = Some(HttpDispatchError::InternalError);
2018-05-15 16:55:36 +02:00
break;
2017-12-15 22:10:12 +01:00
}
2018-04-14 01:02:01 +02:00
}
2018-04-29 07:20:32 +02:00
Ok(Some(Message::Eof)) => {
2018-09-29 00:04:59 +02:00
updated = true;
2018-05-07 05:05:31 +02:00
if let Some(mut payload) = self.payload.take() {
2018-04-29 07:20:32 +02:00
payload.feed_eof();
} else {
error!("Internal server error: unexpected eof");
2018-10-02 19:43:23 +02:00
self.flags.insert(Flags::READ_DISCONNECTED | Flags::STARTED);
self.push_response_entry(StatusCode::INTERNAL_SERVER_ERROR);
2018-10-02 04:18:24 +02:00
self.error = Some(HttpDispatchError::InternalError);
2018-05-15 16:55:36 +02:00
break;
2017-12-16 07:49:48 +01:00
}
2017-10-14 09:11:12 +02:00
}
2018-09-01 02:24:13 +02:00
Ok(None) => {
if self.flags.contains(Flags::READ_DISCONNECTED) {
2018-10-02 04:18:24 +02:00
self.client_disconnected(true);
2018-09-01 02:24:13 +02:00
}
2018-09-01 03:56:21 +02:00
break;
}
2018-04-29 07:20:32 +02:00
Err(e) => {
2018-05-07 05:05:31 +02:00
if let Some(mut payload) = self.payload.take() {
2018-04-29 07:20:32 +02:00
let e = match e {
DecoderError::Io(e) => PayloadError::Io(e),
DecoderError::Error(_) => PayloadError::EncodingCorrupted,
2018-04-14 01:02:01 +02:00
};
2018-04-29 07:20:32 +02:00
payload.set_error(e);
2018-03-17 04:56:23 +01:00
}
2018-10-02 04:18:24 +02:00
// Malformed requests should be responded with 400
self.push_response_entry(StatusCode::BAD_REQUEST);
2018-10-02 19:43:23 +02:00
self.flags.insert(Flags::READ_DISCONNECTED | Flags::STARTED);
2018-10-02 04:18:24 +02:00
self.error = Some(HttpDispatchError::MalformedRequest);
2018-05-15 16:55:36 +02:00
break;
2017-10-14 09:11:12 +02:00
}
2018-03-17 04:56:23 +01:00
}
2018-04-14 01:02:01 +02:00
}
2018-09-29 00:04:59 +02:00
if self.ka_timer.is_some() && updated {
if let Some(expire) = self.settings.keep_alive_expire() {
self.ka_expire = expire;
}
}
2018-10-02 19:43:23 +02:00
Ok(updated)
2017-11-02 20:54:09 +01:00
}
}
2017-10-14 09:11:12 +02:00
#[cfg(test)]
mod tests {
2018-05-15 18:29:59 +02:00
use std::net::Shutdown;
2018-06-22 07:30:40 +02:00
use std::{cmp, io, time};
2018-05-15 18:29:59 +02:00
2018-09-29 00:04:59 +02:00
use actix::System;
2018-05-15 18:29:59 +02:00
use bytes::{Buf, Bytes, BytesMut};
2018-09-29 00:04:59 +02:00
use futures::future;
2018-04-14 01:02:01 +02:00
use http::{Method, Version};
2018-05-15 18:29:59 +02:00
use tokio_io::{AsyncRead, AsyncWrite};
use super::*;
use application::{App, HttpApplication};
2018-04-14 01:02:01 +02:00
use httpmessage::HttpMessage;
2018-04-29 07:20:32 +02:00
use server::h1decoder::Message;
use server::handler::IntoHttpHandler;
use server::settings::{ServerSettings, ServiceConfig};
2018-09-08 23:55:39 +02:00
use server::{KeepAlive, Request};
2017-10-14 09:11:12 +02:00
fn wrk_settings() -> ServiceConfig<HttpApplication> {
ServiceConfig::<HttpApplication>::new(
App::new().into_handler(),
2018-08-03 08:17:10 +02:00
KeepAlive::Os,
5000,
2018-10-02 05:04:16 +02:00
2000,
2018-08-03 08:17:10 +02:00
ServerSettings::default(),
2018-09-08 23:55:39 +02:00
)
2018-08-03 08:17:10 +02:00
}
2018-04-29 07:20:32 +02:00
impl Message {
2018-06-25 06:58:04 +02:00
fn message(self) -> Request {
2018-04-29 07:20:32 +02:00
match self {
2018-04-29 18:09:08 +02:00
Message::Message { msg, payload: _ } => msg,
2018-04-29 07:20:32 +02:00
_ => panic!("error"),
2017-10-14 09:11:12 +02:00
}
}
2018-04-29 07:20:32 +02:00
fn is_payload(&self) -> bool {
match *self {
2018-04-29 18:09:08 +02:00
Message::Message { msg: _, payload } => payload,
2018-04-29 07:20:32 +02:00
_ => panic!("error"),
2017-10-14 09:11:12 +02:00
}
}
2018-04-29 07:20:32 +02:00
fn chunk(self) -> Bytes {
match self {
Message::Chunk(chunk) => chunk,
_ => panic!("error"),
}
}
2018-04-29 07:20:32 +02:00
fn eof(&self) -> bool {
match *self {
Message::Eof => true,
_ => false,
2018-04-14 01:02:01 +02:00
}
2018-04-29 07:20:32 +02:00
}
2017-10-14 09:11:12 +02:00
}
macro_rules! parse_ready {
2018-04-14 01:02:01 +02:00
($e:expr) => {{
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2018-04-29 07:20:32 +02:00
match H1Decoder::new().decode($e, &settings) {
2018-06-25 06:58:04 +02:00
Ok(Some(msg)) => msg.message(),
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! expect_parse_err {
2018-04-14 01:02:01 +02:00
($e:expr) => {{
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-12-15 05:29:49 +01:00
2018-04-29 07:20:32 +02:00
match H1Decoder::new().decode($e, &settings) {
Err(err) => match err {
2018-04-29 07:20:32 +02:00
DecoderError::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
}
2018-05-15 18:29:59 +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,
}
}
}
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 {
fn shutdown(&mut self, _: Shutdown) -> io::Result<()> {
Ok(())
}
fn set_nodelay(&mut self, _: bool) -> io::Result<()> {
Ok(())
}
fn set_linger(&mut self, _: Option<time::Duration>) -> io::Result<()> {
Ok(())
}
2018-10-02 07:48:11 +02:00
fn set_keepalive(&mut self, _: Option<time::Duration>) -> io::Result<()> {
Ok(())
}
2018-05-15 18:29:59 +02:00
}
impl io::Write for Buffer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl AsyncWrite for Buffer {
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)
}
}
#[test]
fn test_req_parse_err() {
2018-09-29 00:04:59 +02:00
let mut sys = System::new("test");
2018-10-02 04:18:24 +02:00
let _ = sys.block_on(future::lazy(|| {
2018-09-29 00:04:59 +02:00
let buf = Buffer::new("GET /test HTTP/1\r\n\r\n");
let readbuf = BytesMut::new();
let settings = wrk_settings();
2018-05-15 18:29:59 +02:00
2018-10-02 07:23:02 +02:00
let mut h1 =
2018-10-03 04:05:58 +02:00
Http1Dispatcher::new(settings.clone(), buf, readbuf, false, None);
2018-10-02 04:18:24 +02:00
assert!(h1.poll_io().is_ok());
assert!(h1.poll_io().is_ok());
assert!(h1.flags.contains(Flags::READ_DISCONNECTED));
2018-09-29 00:04:59 +02:00
assert_eq!(h1.tasks.len(), 1);
future::ok::<_, ()>(())
}));
2018-05-15 18:29:59 +02:00
}
2017-10-14 09:11:12 +02:00
#[test]
fn test_parse() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n\r\n");
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
match reader.decode(&mut buf, &settings) {
Ok(Some(msg)) => {
2018-06-25 06:58:04 +02:00
let req = msg.message();
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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("PUT /test HTTP/1");
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
match reader.decode(&mut buf, &settings) {
Ok(None) => (),
2018-03-30 00:55:27 +02:00
_ => unreachable!("Error"),
2017-10-14 09:11:12 +02:00
}
2018-04-29 07:20:32 +02:00
buf.extend(b".1\r\n\r\n");
match reader.decode(&mut buf, &settings) {
Ok(Some(msg)) => {
2018-06-25 06:58:04 +02:00
let mut req = msg.message();
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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("POST /test2 HTTP/1.0\r\n\r\n");
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
match reader.decode(&mut buf, &settings) {
Ok(Some(msg)) => {
2018-06-25 06:58:04 +02:00
let mut req = msg.message();
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() {
2018-04-29 07:20:32 +02:00
let mut buf =
BytesMut::from("GET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody");
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
match reader.decode(&mut buf, &settings) {
Ok(Some(msg)) => {
2018-06-25 06:58:04 +02:00
let mut req = msg.message();
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-29 07:20:32 +02:00
assert_eq!(
reader
.decode(&mut buf, &settings)
.unwrap()
.unwrap()
.chunk()
.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 =
2018-04-29 07:20:32 +02:00
BytesMut::from("\r\nGET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody");
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
match reader.decode(&mut buf, &settings) {
Ok(Some(msg)) => {
2018-06-25 06:58:04 +02:00
let mut req = msg.message();
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-29 07:20:32 +02:00
assert_eq!(
reader
.decode(&mut buf, &settings)
.unwrap()
.unwrap()
.chunk()
.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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n");
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
assert!(reader.decode(&mut buf, &settings).unwrap().is_none());
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"\r\n");
match reader.decode(&mut buf, &settings) {
Ok(Some(msg)) => {
2018-06-25 06:58:04 +02:00
let req = msg.message();
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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n");
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
assert!{ reader.decode(&mut buf, &settings).unwrap().is_none() }
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"t");
assert!{ reader.decode(&mut buf, &settings).unwrap().is_none() }
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"es");
assert!{ reader.decode(&mut buf, &settings).unwrap().is_none() }
2017-10-14 09:11:12 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"t: value\r\n\r\n");
match reader.decode(&mut buf, &settings) {
Ok(Some(msg)) => {
2018-06-25 06:58:04 +02:00
let req = msg.message();
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-05-15 16:55:36 +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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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",
);
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
2018-06-25 06:58:04 +02:00
let req = msg.message();
2017-10-14 09:11:12 +02:00
2018-05-17 21:20:20 +02:00
let val: Vec<_> = req
.headers()
2018-04-29 07:20:32 +02:00
.get_all("Set-Cookie")
.iter()
.map(|v| v.to_str().unwrap().to_owned())
.collect();
assert_eq!(val[0], "c1=cookie1");
assert_eq!(val[1], "c2=cookie2");
2017-10-14 09:11:12 +02:00
}
#[test]
fn test_conn_default_1_0() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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
assert!(req.upgrade());
}
#[test]
fn test_conn_upgrade_connect_method() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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());
}
#[test]
fn test_request_chunked() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2018-01-21 01:51:18 +01:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("getpath \r\n\r\n");
2017-10-14 09:11:12 +02:00
expect_parse_err!(&mut buf);
}
#[test]
fn test_http_request_upgrade() {
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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",
);
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.is_payload());
2018-06-25 06:58:04 +02:00
let req = msg.message();
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!(
2018-04-29 18:09:08 +02:00
reader
.decode(&mut buf, &settings)
.unwrap()
.unwrap()
.chunk()
.as_ref(),
2018-04-14 01:02:01 +02:00
b"some raw data"
);
2017-10-14 09:11:12 +02:00
}
#[test]
fn test_http_request_parser_utf8() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"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-29 07:20:32 +02:00
let mut buf = BytesMut::from("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-29 07:20:32 +02:00
let mut buf = BytesMut::from("!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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from("GET //get HT/11\r\n\r\n");
2017-10-14 09:11:12 +02:00
expect_parse_err!(&mut buf);
}
#[test]
fn test_http_request_chunked_payload() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:11:12 +02:00
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.is_payload());
2018-06-25 06:58:04 +02:00
let req = msg.message();
2017-10-14 09:11:12 +02:00
assert!(req.chunked().unwrap());
2018-04-29 07:20:32 +02:00
buf.extend(b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n");
assert_eq!(
2018-04-29 18:09:08 +02:00
reader
.decode(&mut buf, &settings)
.unwrap()
.unwrap()
.chunk()
.as_ref(),
2018-04-29 07:20:32 +02:00
b"data"
);
2018-04-14 01:02:01 +02:00
assert_eq!(
2018-04-29 18:09:08 +02:00
reader
.decode(&mut buf, &settings)
.unwrap()
.unwrap()
.chunk()
.as_ref(),
2018-04-29 07:20:32 +02:00
b"line"
);
2018-05-15 16:55:36 +02:00
assert!(reader.decode(&mut buf, &settings).unwrap().unwrap().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() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:28:49 +02:00
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.is_payload());
2018-06-25 06:58:04 +02:00
let req = msg.message();
2017-10-14 09:28:49 +02:00
assert!(req.chunked().unwrap());
2018-04-29 07:20:32 +02:00
buf.extend(
b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n\
POST /test2 HTTP/1.1\r\n\
transfer-encoding: chunked\r\n\r\n"
.iter(),
2018-04-14 01:02:01 +02:00
);
2018-04-29 07:20:32 +02:00
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert_eq!(msg.chunk().as_ref(), b"data");
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert_eq!(msg.chunk().as_ref(), b"line");
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.eof());
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.is_payload());
2018-06-25 06:58:04 +02:00
let req2 = msg.message();
2018-04-29 07:20:32 +02:00
assert!(req2.chunked().unwrap());
2017-10-14 09:28:49 +02:00
assert_eq!(*req2.method(), Method::POST);
assert!(req2.chunked().unwrap());
}
#[test]
fn test_http_request_chunked_payload_chunks() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
2017-10-14 09:28:49 +02:00
"GET /test HTTP/1.1\r\n\
2018-04-14 01:02:01 +02:00
transfer-encoding: chunked\r\n\r\n",
);
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:28:49 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.is_payload());
2018-06-25 06:58:04 +02:00
let req = msg.message();
2017-10-14 09:28:49 +02:00
assert!(req.chunked().unwrap());
2018-03-03 07:08:56 +01:00
2018-04-29 07:20:32 +02:00
buf.extend(b"4\r\n1111\r\n");
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert_eq!(msg.chunk().as_ref(), b"1111");
2017-10-14 09:28:49 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"4\r\ndata\r");
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert_eq!(msg.chunk().as_ref(), b"data");
2017-10-14 09:28:49 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"\n4");
assert!(reader.decode(&mut buf, &settings).unwrap().is_none());
2017-10-14 09:28:49 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"\r");
assert!(reader.decode(&mut buf, &settings).unwrap().is_none());
buf.extend(b"\n");
assert!(reader.decode(&mut buf, &settings).unwrap().is_none());
2017-10-14 09:28:49 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"li");
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert_eq!(msg.chunk().as_ref(), b"li");
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-04-29 07:20:32 +02:00
buf.extend(b"ne\r\n0\r\n");
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert_eq!(msg.chunk().as_ref(), b"ne");
assert!(reader.decode(&mut buf, &settings).unwrap().is_none());
buf.extend(b"\r\n");
2018-05-15 16:55:36 +02:00
assert!(reader.decode(&mut buf, &settings).unwrap().unwrap().eof());
2017-10-14 09:28:49 +02:00
}
#[test]
fn test_parse_chunked_payload_chunk_extension() {
2018-04-29 07:20:32 +02:00
let mut buf = BytesMut::from(
&"GET /test HTTP/1.1\r\n\
transfer-encoding: chunked\r\n\r\n"[..],
2018-04-14 01:02:01 +02:00
);
2018-08-03 08:17:10 +02:00
let settings = wrk_settings();
2017-10-14 09:28:49 +02:00
2018-04-29 07:20:32 +02:00
let mut reader = H1Decoder::new();
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.is_payload());
2018-06-25 06:58:04 +02:00
assert!(msg.message().chunked().unwrap());
2017-10-14 09:28:49 +02:00
2018-04-29 07:20:32 +02:00
buf.extend(b"4;test\r\ndata\r\n4\r\nline\r\n0\r\n\r\n"); // test: test\r\n\r\n")
2018-05-15 16:55:36 +02:00
let chunk = reader.decode(&mut buf, &settings).unwrap().unwrap().chunk();
2018-04-29 07:20:32 +02:00
assert_eq!(chunk, Bytes::from_static(b"data"));
2018-05-15 16:55:36 +02:00
let chunk = reader.decode(&mut buf, &settings).unwrap().unwrap().chunk();
2018-04-29 07:20:32 +02:00
assert_eq!(chunk, Bytes::from_static(b"line"));
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
assert!(msg.eof());
2017-10-14 09:28:49 +02:00
}
2017-10-14 09:11:12 +02:00
}