1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 13:29:24 +00:00
actix-web/actix-http/src/h1/dispatcher.rs

944 lines
34 KiB
Rust
Raw Normal View History

2018-10-04 23:22:00 +00:00
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
2019-11-26 05:25:50 +00:00
use std::{fmt, io, net};
2018-10-04 23:22:00 +00:00
2019-12-02 11:33:11 +00:00
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed, FramedParts};
2019-12-05 17:35:43 +00:00
use actix_rt::time::{delay_until, Delay, Instant};
2018-12-11 02:08:33 +00:00
use actix_service::Service;
2018-12-06 22:32:52 +00:00
use bitflags::bitflags;
2019-12-19 03:56:14 +00:00
use bytes::{Buf, BytesMut};
2019-04-06 07:16:04 +00:00
use log::{error, trace};
2020-02-03 20:55:49 +00:00
use pin_project::pin_project;
2018-10-04 23:22:00 +00:00
2019-03-27 16:24:55 +00:00
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService;
2018-12-06 22:32:52 +00:00
use crate::config::ServiceConfig;
2019-04-05 23:46:44 +00:00
use crate::error::{DispatchError, Error};
2018-12-06 22:32:52 +00:00
use crate::error::{ParseError, PayloadError};
2019-06-28 08:34:26 +00:00
use crate::helpers::DataFactory;
use crate::httpmessage::HttpMessage;
2018-12-06 22:32:52 +00:00
use crate::request::Request;
use crate::response::Response;
2018-10-05 03:02:10 +00:00
use super::codec::Codec;
2019-04-07 17:29:26 +00:00
use super::payload::{Payload, PayloadSender, PayloadStatus};
2019-03-07 06:56:34 +00:00
use super::{Message, MessageType};
2018-10-04 23:22:00 +00:00
2019-04-06 07:16:04 +00:00
const LW_BUFFER_SIZE: usize = 4096;
const HW_BUFFER_SIZE: usize = 32_768;
2018-10-04 23:22:00 +00:00
const MAX_PIPELINED_MESSAGES: usize = 16;
bitflags! {
pub struct Flags: u8 {
const STARTED = 0b0000_0001;
2019-04-06 07:16:04 +00:00
const KEEPALIVE = 0b0000_0010;
const POLLED = 0b0000_0100;
const SHUTDOWN = 0b0000_1000;
const READ_DISCONNECT = 0b0001_0000;
const WRITE_DISCONNECT = 0b0010_0000;
const UPGRADE = 0b0100_0000;
2018-10-04 23:22:00 +00:00
}
}
2020-02-03 20:55:49 +00:00
#[pin_project::pin_project]
2018-10-04 23:22:00 +00:00
/// Dispatcher for HTTP/1.1 protocol
2019-04-08 21:51:16 +00:00
pub struct Dispatcher<T, S, B, X, U>
2018-11-17 05:09:33 +00:00
where
2019-04-05 23:46:44 +00:00
S: Service<Request = Request>,
S::Error: Into<Error>,
B: MessageBody,
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
2019-04-08 21:51:16 +00:00
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
2018-11-17 05:09:33 +00:00
{
2020-02-03 20:55:49 +00:00
#[pin]
inner: DispatcherState<T, S, B, X, U>,
}
#[pin_project(project = DispatcherStateProj)]
enum DispatcherState<T, S, B, X, U>
where
S: Service<Request = Request>,
S::Error: Into<Error>,
B: MessageBody,
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
2020-02-03 20:55:49 +00:00
Normal(#[pin] InnerDispatcher<T, S, B, X, U>),
Upgrade(Pin<Box<U::Future>>),
2018-11-17 05:09:33 +00:00
}
#[pin_project(project = InnerDispatcherProj)]
2019-04-08 21:51:16 +00:00
struct InnerDispatcher<T, S, B, X, U>
2018-10-04 23:22:00 +00:00
where
2019-04-05 23:46:44 +00:00
S: Service<Request = Request>,
S::Error: Into<Error>,
B: MessageBody,
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
2019-04-08 21:51:16 +00:00
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
2018-10-04 23:22:00 +00:00
{
service: CloneableService<S>,
2019-04-05 23:46:44 +00:00
expect: CloneableService<X>,
2019-04-08 21:51:16 +00:00
upgrade: Option<CloneableService<U>>,
2019-06-28 08:34:26 +00:00
on_connect: Option<Box<dyn DataFactory>>,
2018-10-04 23:22:00 +00:00
flags: Flags,
peer_addr: Option<net::SocketAddr>,
2019-03-07 06:56:34 +00:00
error: Option<DispatchError>,
2018-10-04 23:22:00 +00:00
2020-02-03 20:55:49 +00:00
#[pin]
2019-04-05 23:46:44 +00:00
state: State<S, B, X>,
2018-10-05 14:02:09 +00:00
payload: Option<PayloadSender>,
messages: VecDeque<DispatcherMessage>,
2018-10-05 04:14:18 +00:00
2018-10-05 06:39:11 +00:00
ka_expire: Instant,
ka_timer: Option<Delay>,
2019-04-06 07:16:04 +00:00
io: Option<T>,
2019-04-06 07:16:04 +00:00
read_buf: BytesMut,
write_buf: BytesMut,
codec: Codec,
2018-10-04 23:22:00 +00:00
}
enum DispatcherMessage {
2018-10-07 04:07:32 +00:00
Item(Request),
Upgrade(Request),
Error(Response<()>),
2018-10-07 04:07:32 +00:00
}
#[pin_project(project = StateProj)]
2019-04-05 23:46:44 +00:00
enum State<S, B, X>
where
S: Service<Request = Request>,
X: Service<Request = Request, Response = Request>,
B: MessageBody,
{
2018-10-04 23:22:00 +00:00
None,
ExpectCall(Pin<Box<X::Future>>),
ServiceCall(Pin<Box<S::Future>>),
2020-02-03 20:55:49 +00:00
SendPayload(#[pin] ResponseBody<B>),
2018-10-04 23:22:00 +00:00
}
2019-04-05 23:46:44 +00:00
impl<S, B, X> State<S, B, X>
where
S: Service<Request = Request>,
X: Service<Request = Request, Response = Request>,
B: MessageBody,
{
2018-10-04 23:22:00 +00:00
fn is_empty(&self) -> bool {
matches!(self, State::None)
2018-10-04 23:22:00 +00:00
}
2019-04-06 07:16:04 +00:00
fn is_call(&self) -> bool {
matches!(self, State::ServiceCall(_))
2019-04-06 07:16:04 +00:00
}
}
enum PollResponse {
Upgrade(Request),
DoNothing,
DrainWriteBuf,
}
impl PartialEq for PollResponse {
fn eq(&self, other: &PollResponse) -> bool {
2019-04-06 07:16:04 +00:00
match self {
2020-07-21 07:40:30 +00:00
PollResponse::DrainWriteBuf => matches!(other, PollResponse::DrainWriteBuf),
PollResponse::DoNothing => matches!(other, PollResponse::DoNothing),
_ => false,
2019-04-06 07:16:04 +00:00
}
}
2018-10-04 23:22:00 +00:00
}
2019-04-08 21:51:16 +00:00
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
2018-10-04 23:22:00 +00:00
where
2019-12-02 11:33:11 +00:00
T: AsyncRead + AsyncWrite + Unpin,
2019-04-04 17:59:34 +00:00
S: Service<Request = Request>,
2019-04-05 23:46:44 +00:00
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
2020-01-31 20:16:31 +00:00
B: MessageBody,
2019-04-05 23:46:44 +00:00
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
2019-04-08 21:51:16 +00:00
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
2018-10-04 23:22:00 +00:00
{
2018-10-05 03:02:10 +00:00
/// Create http/1 dispatcher.
2019-06-28 08:34:26 +00:00
pub(crate) fn new(
2019-04-05 23:46:44 +00:00
stream: T,
config: ServiceConfig,
service: CloneableService<S>,
expect: CloneableService<X>,
2019-04-08 21:51:16 +00:00
upgrade: Option<CloneableService<U>>,
2019-06-28 08:34:26 +00:00
on_connect: Option<Box<dyn DataFactory>>,
2019-12-02 11:33:11 +00:00
peer_addr: Option<net::SocketAddr>,
2019-04-05 23:46:44 +00:00
) -> Self {
2019-03-07 06:56:34 +00:00
Dispatcher::with_timeout(
2019-04-06 07:16:04 +00:00
stream,
Codec::new(config.clone()),
2019-03-07 06:56:34 +00:00
config,
2019-04-06 07:16:04 +00:00
BytesMut::with_capacity(HW_BUFFER_SIZE),
2019-03-07 06:56:34 +00:00
None,
service,
2019-04-05 23:46:44 +00:00
expect,
2019-04-08 21:51:16 +00:00
upgrade,
2019-06-28 08:34:26 +00:00
on_connect,
2019-12-02 11:33:11 +00:00
peer_addr,
2019-03-07 06:56:34 +00:00
)
2018-10-05 06:39:11 +00:00
}
/// Create http/1 dispatcher with slow request timeout.
2019-06-28 08:34:26 +00:00
pub(crate) fn with_timeout(
2019-04-06 07:16:04 +00:00
io: T,
codec: Codec,
2018-10-29 23:39:46 +00:00
config: ServiceConfig,
2019-04-06 07:16:04 +00:00
read_buf: BytesMut,
2018-10-29 23:39:46 +00:00
timeout: Option<Delay>,
service: CloneableService<S>,
2019-04-05 23:46:44 +00:00
expect: CloneableService<X>,
2019-04-08 21:51:16 +00:00
upgrade: Option<CloneableService<U>>,
2019-06-28 08:34:26 +00:00
on_connect: Option<Box<dyn DataFactory>>,
2019-12-02 11:33:11 +00:00
peer_addr: Option<net::SocketAddr>,
2018-10-05 06:39:11 +00:00
) -> Self {
2018-10-05 17:03:10 +00:00
let keepalive = config.keep_alive_enabled();
let flags = if keepalive {
2019-04-06 07:16:04 +00:00
Flags::KEEPALIVE
2018-10-05 06:39:11 +00:00
} else {
2018-11-19 01:52:56 +00:00
Flags::empty()
2018-10-05 06:39:11 +00:00
};
2018-10-04 23:22:00 +00:00
2018-10-08 22:24:51 +00:00
// keep-alive timer
2018-10-05 06:39:11 +00:00
let (ka_expire, ka_timer) = if let Some(delay) = timeout {
(delay.deadline(), Some(delay))
} else if let Some(delay) = config.keep_alive_timer() {
(delay.deadline(), Some(delay))
} else {
(config.now(), None)
};
2018-10-05 03:02:10 +00:00
Dispatcher {
inner: DispatcherState::Normal(InnerDispatcher {
2019-04-06 07:16:04 +00:00
write_buf: BytesMut::with_capacity(HW_BUFFER_SIZE),
2018-11-17 05:09:33 +00:00
payload: None,
state: State::None,
error: None,
messages: VecDeque::new(),
io: Some(io),
codec,
read_buf,
2018-11-17 05:09:33 +00:00
service,
2019-04-05 23:46:44 +00:00
expect,
2019-04-08 21:51:16 +00:00
upgrade,
2019-06-28 08:34:26 +00:00
on_connect,
2018-11-17 05:09:33 +00:00
flags,
2019-12-02 11:33:11 +00:00
peer_addr,
2018-11-17 05:09:33 +00:00
ka_expire,
ka_timer,
}),
2018-10-04 23:22:00 +00:00
}
}
2018-11-17 05:09:33 +00:00
}
2018-10-04 23:22:00 +00:00
2019-04-08 21:51:16 +00:00
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
2018-11-17 05:09:33 +00:00
where
2019-12-02 11:33:11 +00:00
T: AsyncRead + AsyncWrite + Unpin,
2019-04-04 17:59:34 +00:00
S: Service<Request = Request>,
2019-04-05 23:46:44 +00:00
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
2020-01-31 20:16:31 +00:00
B: MessageBody,
2019-04-05 23:46:44 +00:00
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
2019-04-08 21:51:16 +00:00
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
2018-11-17 05:09:33 +00:00
{
2019-12-07 18:46:51 +00:00
fn can_read(&self, cx: &mut Context<'_>) -> bool {
if self
.flags
.intersects(Flags::READ_DISCONNECT | Flags::UPGRADE)
{
false
2019-04-06 07:16:04 +00:00
} else if let Some(ref info) = self.payload {
info.need_read(cx) == PayloadStatus::Read
2018-10-04 23:22:00 +00:00
} else {
true
}
}
// if checked is set to true, delay disconnect until all tasks have finished.
2020-02-03 20:55:49 +00:00
fn client_disconnected(self: Pin<&mut Self>) {
let this = self.project();
this.flags
2019-04-06 07:16:04 +00:00
.insert(Flags::READ_DISCONNECT | Flags::WRITE_DISCONNECT);
2020-02-03 20:55:49 +00:00
if let Some(mut payload) = this.payload.take() {
payload.set_error(PayloadError::Incomplete(None));
2018-10-04 23:22:00 +00:00
}
}
/// Flush stream
2019-04-06 07:16:04 +00:00
///
2020-04-21 03:09:35 +00:00
/// true - got WouldBlock
/// false - didn't get WouldBlock
2020-02-27 02:10:55 +00:00
fn poll_flush(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Result<bool, DispatchError> {
2019-04-06 07:16:04 +00:00
if self.write_buf.is_empty() {
return Ok(false);
}
let len = self.write_buf.len();
let mut written = 0;
let InnerDispatcherProj { io, write_buf, .. } = self.project();
let mut io = Pin::new(io.as_mut().unwrap());
2019-04-06 07:16:04 +00:00
while written < len {
2020-02-27 02:10:55 +00:00
match io.as_mut().poll_write(cx, &write_buf[written..]) {
Poll::Ready(Ok(0)) => {
2019-04-06 07:16:04 +00:00
return Err(DispatchError::Io(io::Error::new(
io::ErrorKind::WriteZero,
"",
)));
2018-10-04 23:22:00 +00:00
}
Poll::Ready(Ok(n)) => {
2019-04-06 07:16:04 +00:00
written += n;
}
Poll::Pending => {
2019-04-06 07:16:04 +00:00
if written > 0 {
2020-02-03 20:55:49 +00:00
write_buf.advance(written);
2018-10-04 23:22:00 +00:00
}
2019-04-06 07:16:04 +00:00
return Ok(true);
2018-10-04 23:22:00 +00:00
}
Poll::Ready(Err(err)) => return Err(DispatchError::Io(err)),
2018-10-04 23:22:00 +00:00
}
}
2020-02-03 20:55:49 +00:00
if written == write_buf.len() {
unsafe { write_buf.set_len(0) }
2019-11-19 05:08:03 +00:00
} else {
2020-02-03 20:55:49 +00:00
write_buf.advance(written);
2019-04-06 07:16:04 +00:00
}
Ok(false)
2018-10-04 23:22:00 +00:00
}
2018-11-21 15:49:24 +00:00
fn send_response(
2020-02-03 20:55:49 +00:00
self: Pin<&mut Self>,
message: Response<()>,
2018-11-21 15:49:24 +00:00
body: ResponseBody<B>,
2019-04-05 23:46:44 +00:00
) -> Result<State<S, B, X>, DispatchError> {
2020-02-03 20:55:49 +00:00
let mut this = self.project();
this.codec
.encode(Message::Item((message, body.size())), &mut this.write_buf)
2018-11-17 05:09:33 +00:00
.map_err(|err| {
2020-02-03 20:55:49 +00:00
if let Some(mut payload) = this.payload.take() {
2018-11-17 05:09:33 +00:00
payload.set_error(PayloadError::Incomplete(None));
}
DispatchError::Io(err)
})?;
2020-02-03 20:55:49 +00:00
this.flags.set(Flags::KEEPALIVE, this.codec.keepalive());
match body.size() {
2019-03-27 16:24:55 +00:00
BodySize::None | BodySize::Empty => Ok(State::None),
2018-11-18 04:21:28 +00:00
_ => Ok(State::SendPayload(body)),
2018-11-17 05:09:33 +00:00
}
}
2020-02-03 20:55:49 +00:00
fn send_continue(self: Pin<&mut Self>) {
2020-02-27 02:10:55 +00:00
self.project()
.write_buf
2019-04-06 07:16:04 +00:00
.extend_from_slice(b"HTTP/1.1 100 Continue\r\n\r\n");
2019-04-05 23:46:44 +00:00
}
fn poll_response(
2020-02-03 20:55:49 +00:00
mut self: Pin<&mut Self>,
2019-12-07 18:46:51 +00:00
cx: &mut Context<'_>,
) -> Result<PollResponse, DispatchError> {
2018-10-04 23:22:00 +00:00
loop {
2020-02-03 20:55:49 +00:00
let mut this = self.as_mut().project();
let state = match this.state.project() {
StateProj::None => match this.messages.pop_front() {
2018-11-17 05:09:33 +00:00
Some(DispatcherMessage::Item(req)) => {
2020-02-03 20:55:49 +00:00
Some(self.as_mut().handle_request(req, cx)?)
2018-10-29 23:39:46 +00:00
}
2020-02-27 02:10:55 +00:00
Some(DispatcherMessage::Error(res)) => Some(
self.as_mut()
.send_response(res, ResponseBody::Other(Body::Empty))?,
),
Some(DispatcherMessage::Upgrade(req)) => {
return Ok(PollResponse::Upgrade(req));
}
2018-11-17 05:09:33 +00:00
None => None,
2018-10-04 23:22:00 +00:00
},
StateProj::ExpectCall(fut) => match fut.as_mut().poll(cx) {
2020-02-27 02:10:55 +00:00
Poll::Ready(Ok(req)) => {
self.as_mut().send_continue();
this = self.as_mut().project();
2020-03-07 15:52:39 +00:00
this.state
.set(State::ServiceCall(Box::pin(this.service.call(req))));
2020-02-27 02:10:55 +00:00
continue;
2019-03-11 23:42:33 +00:00
}
2020-02-27 02:10:55 +00:00
Poll::Ready(Err(e)) => {
let res: Response = e.into().into();
let (res, body) = res.replace_body(());
Some(self.as_mut().send_response(res, body.into_body())?)
2019-03-11 23:42:33 +00:00
}
2020-02-27 02:10:55 +00:00
Poll::Pending => None,
},
StateProj::ServiceCall(fut) => match fut.as_mut().poll(cx) {
2020-02-27 02:10:55 +00:00
Poll::Ready(Ok(res)) => {
let (res, body) = res.into().replace_body(());
let state = self.as_mut().send_response(res, body)?;
this = self.as_mut().project();
this.state.set(state);
continue;
}
Poll::Ready(Err(e)) => {
let res: Response = e.into().into();
let (res, body) = res.replace_body(());
Some(self.as_mut().send_response(res, body.into_body())?)
}
Poll::Pending => None,
},
StateProj::SendPayload(mut stream) => {
2018-11-14 18:52:40 +00:00
loop {
2020-02-03 20:55:49 +00:00
if this.write_buf.len() < HW_BUFFER_SIZE {
match stream.as_mut().poll_next(cx) {
Poll::Ready(Some(Ok(item))) => {
2020-02-03 20:55:49 +00:00
this.codec.encode(
2019-04-06 07:16:04 +00:00
Message::Chunk(Some(item)),
2020-02-03 20:55:49 +00:00
&mut this.write_buf,
2019-04-06 07:16:04 +00:00
)?;
2018-10-08 22:24:51 +00:00
continue;
}
Poll::Ready(None) => {
2020-02-03 20:55:49 +00:00
this.codec.encode(
2019-04-06 07:16:04 +00:00
Message::Chunk(None),
2020-02-03 20:55:49 +00:00
&mut this.write_buf,
2019-04-06 07:16:04 +00:00
)?;
2020-02-03 20:55:49 +00:00
this = self.as_mut().project();
this.state.set(State::None);
2018-10-08 22:24:51 +00:00
}
Poll::Ready(Some(Err(_))) => {
return Err(DispatchError::Unknown)
}
Poll::Pending => return Ok(PollResponse::DoNothing),
2018-11-14 18:52:40 +00:00
}
} else {
return Ok(PollResponse::DrainWriteBuf);
2018-10-08 22:24:51 +00:00
}
2018-11-14 18:52:40 +00:00
break;
2018-10-08 22:24:51 +00:00
}
2019-04-06 07:16:04 +00:00
continue;
2018-10-04 23:22:00 +00:00
}
};
2020-02-03 20:55:49 +00:00
this = self.as_mut().project();
2019-04-06 07:16:04 +00:00
// set new state
if let Some(state) = state {
2020-02-03 20:55:49 +00:00
this.state.set(state);
2019-04-06 07:16:04 +00:00
if !self.state.is_empty() {
continue;
}
} else {
// if read-backpressure is enabled and we consumed some data.
// we may read more data and retry
if self.state.is_call() {
2020-02-03 20:55:49 +00:00
if self.as_mut().poll_request(cx)? {
2018-10-04 23:22:00 +00:00
continue;
}
2019-04-06 07:16:04 +00:00
} else if !self.messages.is_empty() {
continue;
2018-10-04 23:22:00 +00:00
}
}
2019-04-06 07:16:04 +00:00
break;
2018-10-04 23:22:00 +00:00
}
Ok(PollResponse::DoNothing)
2018-10-04 23:22:00 +00:00
}
fn handle_request(
2020-02-03 20:55:49 +00:00
mut self: Pin<&mut Self>,
req: Request,
2019-12-07 18:46:51 +00:00
cx: &mut Context<'_>,
) -> Result<State<S, B, X>, DispatchError> {
2019-04-05 23:46:44 +00:00
// Handle `EXPECT: 100-Continue` header
let req = if req.head().expect() {
let mut task = Box::pin(self.as_mut().project().expect.call(req));
match task.as_mut().poll(cx) {
Poll::Ready(Ok(req)) => {
2020-02-03 20:55:49 +00:00
self.as_mut().send_continue();
2019-04-05 23:46:44 +00:00
req
}
Poll::Pending => return Ok(State::ExpectCall(task)),
Poll::Ready(Err(e)) => {
2019-04-05 23:46:44 +00:00
let e = e.into();
let res: Response = e.into();
let (res, body) = res.replace_body(());
return self.send_response(res, body.into_body());
}
}
} else {
req
};
// Call service
let mut task = Box::pin(self.as_mut().project().service.call(req));
match task.as_mut().poll(cx) {
Poll::Ready(Ok(res)) => {
let (res, body) = res.into().replace_body(());
2018-11-17 05:09:33 +00:00
self.send_response(res, body)
2018-10-07 05:36:57 +00:00
}
Poll::Pending => Ok(State::ServiceCall(task)),
Poll::Ready(Err(e)) => {
2019-04-06 07:16:04 +00:00
let res: Response = e.into().into();
2019-03-11 23:42:33 +00:00
let (res, body) = res.replace_body(());
self.send_response(res, body.into_body())
}
2018-10-07 05:36:57 +00:00
}
}
2018-10-09 17:36:40 +00:00
/// Process one incoming requests
pub(self) fn poll_request(
2020-02-03 20:55:49 +00:00
mut self: Pin<&mut Self>,
2019-12-07 18:46:51 +00:00
cx: &mut Context<'_>,
) -> Result<bool, DispatchError> {
2018-10-09 17:36:40 +00:00
// limit a mount of non processed requests
if self.messages.len() >= MAX_PIPELINED_MESSAGES || !self.can_read(cx) {
2018-10-09 17:36:40 +00:00
return Ok(false);
2018-10-04 23:22:00 +00:00
}
let mut updated = false;
2020-02-03 20:55:49 +00:00
let mut this = self.as_mut().project();
2018-10-29 23:39:46 +00:00
loop {
2020-02-03 20:55:49 +00:00
match this.codec.decode(&mut this.read_buf) {
2019-04-06 07:16:04 +00:00
Ok(Some(msg)) => {
2018-10-09 17:36:40 +00:00
updated = true;
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::STARTED);
2018-10-09 17:36:40 +00:00
match msg {
2019-02-06 19:44:15 +00:00
Message::Item(mut req) => {
2020-02-03 20:55:49 +00:00
let pl = this.codec.message_type();
req.head_mut().peer_addr = *this.peer_addr;
// set on_connect data
2020-02-03 20:55:49 +00:00
if let Some(ref on_connect) = this.on_connect {
2019-06-28 08:34:26 +00:00
on_connect.set(&mut req.extensions_mut());
}
2020-02-03 20:55:49 +00:00
if pl == MessageType::Stream && this.upgrade.is_some() {
this.messages.push_back(DispatcherMessage::Upgrade(req));
break;
}
if pl == MessageType::Payload || pl == MessageType::Stream {
let (ps, pl) = Payload::create(false);
let (req1, _) =
req.replace_payload(crate::Payload::H1(pl));
req = req1;
2020-02-03 20:55:49 +00:00
*this.payload = Some(ps);
2018-10-09 17:36:40 +00:00
}
2018-10-04 23:22:00 +00:00
2018-10-09 17:36:40 +00:00
// handle request early
2020-02-03 20:55:49 +00:00
if this.state.is_empty() {
let state = self.as_mut().handle_request(req, cx)?;
this = self.as_mut().project();
this.state.set(state);
2018-10-09 17:36:40 +00:00
} else {
2020-02-03 20:55:49 +00:00
this.messages.push_back(DispatcherMessage::Item(req));
2018-10-09 17:36:40 +00:00
}
}
Message::Chunk(Some(chunk)) => {
2020-02-03 20:55:49 +00:00
if let Some(ref mut payload) = this.payload {
2018-10-09 17:36:40 +00:00
payload.feed_data(chunk);
} else {
error!(
"Internal server error: unexpected payload chunk"
);
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::READ_DISCONNECT);
this.messages.push_back(DispatcherMessage::Error(
Response::InternalServerError().finish().drop_body(),
2018-10-09 17:36:40 +00:00
));
2020-02-03 20:55:49 +00:00
*this.error = Some(DispatchError::InternalError);
2018-11-06 03:32:03 +00:00
break;
2018-10-09 17:36:40 +00:00
}
}
Message::Chunk(None) => {
2020-02-03 20:55:49 +00:00
if let Some(mut payload) = this.payload.take() {
2018-10-09 17:36:40 +00:00
payload.feed_eof();
} else {
error!("Internal server error: unexpected eof");
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::READ_DISCONNECT);
this.messages.push_back(DispatcherMessage::Error(
Response::InternalServerError().finish().drop_body(),
2018-10-09 17:36:40 +00:00
));
2020-02-03 20:55:49 +00:00
*this.error = Some(DispatchError::InternalError);
2018-11-06 03:32:03 +00:00
break;
2018-10-09 17:36:40 +00:00
}
}
2018-10-04 23:22:00 +00:00
}
2018-10-09 17:36:40 +00:00
}
2019-04-06 07:16:04 +00:00
Ok(None) => break,
2018-10-09 17:36:40 +00:00
Err(ParseError::Io(e)) => {
2020-02-03 20:55:49 +00:00
self.as_mut().client_disconnected();
this = self.as_mut().project();
*this.error = Some(DispatchError::Io(e));
2018-10-09 17:36:40 +00:00
break;
}
Err(e) => {
2020-02-03 20:55:49 +00:00
if let Some(mut payload) = this.payload.take() {
2018-10-09 17:36:40 +00:00
payload.set_error(PayloadError::EncodingCorrupted);
2018-10-07 16:48:53 +00:00
}
2018-10-04 23:22:00 +00:00
2018-10-09 17:36:40 +00:00
// Malformed requests should be responded with 400
2020-02-03 20:55:49 +00:00
this.messages.push_back(DispatcherMessage::Error(
Response::BadRequest().finish().drop_body(),
));
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::READ_DISCONNECT);
*this.error = Some(e.into());
2018-10-09 17:36:40 +00:00
break;
2018-10-04 23:22:00 +00:00
}
}
}
2020-02-03 20:55:49 +00:00
if updated && this.ka_timer.is_some() {
if let Some(expire) = this.codec.config().keep_alive_expire() {
*this.ka_expire = expire;
2018-10-05 06:39:11 +00:00
}
}
2018-10-04 23:22:00 +00:00
Ok(updated)
}
2018-10-05 06:39:11 +00:00
/// keep-alive timer
2020-02-27 02:10:55 +00:00
fn poll_keepalive(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Result<(), DispatchError> {
2020-02-03 20:55:49 +00:00
let mut this = self.as_mut().project();
if this.ka_timer.is_none() {
// shutdown timeout
2020-02-03 20:55:49 +00:00
if this.flags.contains(Flags::SHUTDOWN) {
if let Some(interval) = this.codec.config().client_disconnect_timer() {
*this.ka_timer = Some(delay_until(interval));
} else {
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::READ_DISCONNECT);
if let Some(mut payload) = this.payload.take() {
2019-05-25 10:07:40 +00:00
payload.set_error(PayloadError::Incomplete(None));
}
return Ok(());
}
} else {
return Ok(());
}
2018-11-17 05:09:33 +00:00
}
2020-02-03 20:55:49 +00:00
match Pin::new(&mut this.ka_timer.as_mut().unwrap()).poll(cx) {
Poll::Ready(()) => {
2018-11-17 05:09:33 +00:00
// if we get timeout during shutdown, drop connection
2020-02-03 20:55:49 +00:00
if this.flags.contains(Flags::SHUTDOWN) {
2018-11-17 05:09:33 +00:00
return Err(DispatchError::DisconnectTimeout);
2020-02-03 20:55:49 +00:00
} else if this.ka_timer.as_mut().unwrap().deadline() >= *this.ka_expire {
2018-11-20 18:55:50 +00:00
// check for any outstanding tasks
2020-02-03 20:55:49 +00:00
if this.state.is_empty() && this.write_buf.is_empty() {
if this.flags.contains(Flags::STARTED) {
2018-11-17 05:09:33 +00:00
trace!("Keep-alive timeout, close connection");
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::SHUTDOWN);
2018-11-17 05:09:33 +00:00
// start shutdown timer
2019-04-06 07:16:04 +00:00
if let Some(deadline) =
2020-02-03 20:55:49 +00:00
this.codec.config().client_disconnect_timer()
2018-11-17 05:09:33 +00:00
{
2020-02-03 20:55:49 +00:00
if let Some(mut timer) = this.ka_timer.as_mut() {
2018-11-08 17:30:53 +00:00
timer.reset(deadline);
let _ = Pin::new(&mut timer).poll(cx);
2019-01-29 18:14:00 +00:00
}
2018-10-07 17:09:48 +00:00
} else {
// no shutdown timeout, drop socket
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::WRITE_DISCONNECT);
2018-11-17 05:09:33 +00:00
return Ok(());
2018-10-05 06:39:11 +00:00
}
2018-11-17 05:09:33 +00:00
} else {
// timeout on first request (slow request) return 408
2020-02-03 20:55:49 +00:00
if !this.flags.contains(Flags::STARTED) {
2018-11-20 18:55:50 +00:00
trace!("Slow request timeout");
2020-02-03 20:55:49 +00:00
let _ = self.as_mut().send_response(
2018-11-20 18:55:50 +00:00
Response::RequestTimeout().finish().drop_body(),
2018-11-21 15:49:24 +00:00
ResponseBody::Other(Body::Empty),
2018-11-20 18:55:50 +00:00
);
2020-02-03 20:55:49 +00:00
this = self.as_mut().project();
2018-11-20 18:55:50 +00:00
} else {
trace!("Keep-alive connection timeout");
}
2020-02-03 20:55:49 +00:00
this.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
this.state.set(State::None);
2018-11-17 05:09:33 +00:00
}
2019-05-14 15:48:11 +00:00
} else if let Some(deadline) =
2020-02-03 20:55:49 +00:00
this.codec.config().keep_alive_expire()
2019-04-06 07:16:04 +00:00
{
2020-02-03 20:55:49 +00:00
if let Some(mut timer) = this.ka_timer.as_mut() {
2018-11-08 17:30:53 +00:00
timer.reset(deadline);
let _ = Pin::new(&mut timer).poll(cx);
2019-01-29 18:14:00 +00:00
}
2018-10-05 06:39:11 +00:00
}
2020-02-03 20:55:49 +00:00
} else if let Some(mut timer) = this.ka_timer.as_mut() {
timer.reset(*this.ka_expire);
let _ = Pin::new(&mut timer).poll(cx);
2018-10-05 06:39:11 +00:00
}
}
Poll::Pending => (),
2018-10-05 06:39:11 +00:00
}
Ok(())
}
2018-10-04 23:22:00 +00:00
}
2019-04-08 21:51:16 +00:00
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
2018-10-04 23:22:00 +00:00
where
2019-12-02 11:33:11 +00:00
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>,
2019-04-05 23:46:44 +00:00
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
2020-01-31 20:16:31 +00:00
B: MessageBody,
2019-04-05 23:46:44 +00:00
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
2019-04-08 21:51:16 +00:00
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
2018-10-04 23:22:00 +00:00
{
type Output = Result<(), DispatchError>;
2018-10-04 23:22:00 +00:00
#[inline]
2019-12-07 18:46:51 +00:00
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2020-02-03 20:55:49 +00:00
let this = self.as_mut().project();
match this.inner.project() {
DispatcherStateProj::Normal(mut inner) => {
2020-02-03 20:55:49 +00:00
inner.as_mut().poll_keepalive(cx)?;
if inner.flags.contains(Flags::SHUTDOWN) {
if inner.flags.contains(Flags::WRITE_DISCONNECT) {
Poll::Ready(Ok(()))
} else {
// flush buffer
2020-02-03 20:55:49 +00:00
inner.as_mut().poll_flush(cx)?;
if !inner.write_buf.is_empty() || inner.io.is_none() {
Poll::Pending
} else {
2020-02-27 02:10:55 +00:00
match Pin::new(inner.project().io)
.as_pin_mut()
.unwrap()
.poll_shutdown(cx)
{
Poll::Ready(res) => {
Poll::Ready(res.map_err(DispatchError::from))
}
Poll::Pending => Poll::Pending,
}
}
}
2019-04-06 07:16:04 +00:00
} else {
// read socket into a buf
2019-06-05 02:43:13 +00:00
let should_disconnect =
if !inner.flags.contains(Flags::READ_DISCONNECT) {
2020-02-03 20:55:49 +00:00
let mut inner_p = inner.as_mut().project();
2020-02-27 02:10:55 +00:00
read_available(
cx,
inner_p.io.as_mut().unwrap(),
&mut inner_p.read_buf,
)?
2019-06-05 02:43:13 +00:00
} else {
None
};
2019-04-06 07:16:04 +00:00
2020-02-03 20:55:49 +00:00
inner.as_mut().poll_request(cx)?;
if let Some(true) = should_disconnect {
2020-02-03 20:55:49 +00:00
let inner_p = inner.as_mut().project();
inner_p.flags.insert(Flags::READ_DISCONNECT);
if let Some(mut payload) = inner_p.payload.take() {
payload.feed_eof();
}
};
loop {
2020-02-03 20:55:49 +00:00
let inner_p = inner.as_mut().project();
let remaining =
2020-02-03 20:55:49 +00:00
inner_p.write_buf.capacity() - inner_p.write_buf.len();
if remaining < LW_BUFFER_SIZE {
2020-02-03 20:55:49 +00:00
inner_p.write_buf.reserve(HW_BUFFER_SIZE - remaining);
}
2020-02-03 20:55:49 +00:00
let result = inner.as_mut().poll_response(cx)?;
let drain = result == PollResponse::DrainWriteBuf;
2019-04-06 07:16:04 +00:00
// switch to upgrade handler
if let PollResponse::Upgrade(req) = result {
let inner_p = inner.as_mut().project();
let mut parts = FramedParts::with_read_buf(
inner_p.io.take().unwrap(),
2020-05-17 01:54:42 +00:00
std::mem::take(inner_p.codec),
std::mem::take(inner_p.read_buf),
2020-02-27 02:10:55 +00:00
);
2020-05-17 01:54:42 +00:00
parts.write_buf = std::mem::take(inner_p.write_buf);
let framed = Framed::from_parts(parts);
2020-02-27 02:10:55 +00:00
let upgrade =
inner_p.upgrade.take().unwrap().call((req, framed));
self.as_mut()
.project()
.inner
.set(DispatcherState::Upgrade(Box::pin(upgrade)));
2020-02-27 02:10:55 +00:00
return self.poll(cx);
}
2018-11-19 01:52:56 +00:00
2020-04-21 03:09:35 +00:00
// we didn't get WouldBlock from write operation,
// so data get written to kernel completely (OSX)
// and we have to write again otherwise response can get stuck
2020-02-03 20:55:49 +00:00
if inner.as_mut().poll_flush(cx)? || !drain {
break;
}
}
// client is gone
if inner.flags.contains(Flags::WRITE_DISCONNECT) {
return Poll::Ready(Ok(()));
}
2019-04-06 07:16:04 +00:00
let is_empty = inner.state.is_empty();
2019-04-06 07:16:04 +00:00
2020-02-03 20:55:49 +00:00
let inner_p = inner.as_mut().project();
// read half is closed and we do not processing any responses
2020-02-03 20:55:49 +00:00
if inner_p.flags.contains(Flags::READ_DISCONNECT) && is_empty {
inner_p.flags.insert(Flags::SHUTDOWN);
}
// keep-alive and stream errors
2020-02-03 20:55:49 +00:00
if is_empty && inner_p.write_buf.is_empty() {
if let Some(err) = inner_p.error.take() {
Poll::Ready(Err(err))
}
// disconnect if keep-alive is not enabled
2020-02-03 20:55:49 +00:00
else if inner_p.flags.contains(Flags::STARTED)
&& !inner_p.flags.intersects(Flags::KEEPALIVE)
{
2020-02-03 20:55:49 +00:00
inner_p.flags.insert(Flags::SHUTDOWN);
self.poll(cx)
}
// disconnect if shutdown
2020-02-03 20:55:49 +00:00
else if inner_p.flags.contains(Flags::SHUTDOWN) {
self.poll(cx)
} else {
Poll::Pending
}
} else {
Poll::Pending
}
2018-10-04 23:22:00 +00:00
}
}
DispatcherStateProj::Upgrade(fut) => fut.as_mut().poll(cx).map_err(|e| {
2020-02-27 02:10:55 +00:00
error!("Upgrade handler error: {}", e);
DispatchError::Upgrade
}),
}
2018-10-04 23:22:00 +00:00
}
}
2019-01-29 18:14:00 +00:00
fn read_available<T>(
2019-12-07 18:46:51 +00:00
cx: &mut Context<'_>,
io: &mut T,
buf: &mut BytesMut,
) -> Result<Option<bool>, io::Error>
2019-04-06 07:16:04 +00:00
where
T: AsyncRead + Unpin,
2019-04-06 07:16:04 +00:00
{
let mut read_some = false;
2019-04-06 07:16:04 +00:00
loop {
// If buf is full return but do not disconnect since
// there is more reading to be done
if buf.len() >= HW_BUFFER_SIZE {
return Ok(Some(false));
}
let remaining = buf.capacity() - buf.len();
if remaining < LW_BUFFER_SIZE {
buf.reserve(HW_BUFFER_SIZE - remaining);
2019-04-06 07:16:04 +00:00
}
match read(cx, io, buf) {
Poll::Pending => {
return if read_some { Ok(Some(false)) } else { Ok(None) };
}
Poll::Ready(Ok(n)) => {
2019-04-06 07:16:04 +00:00
if n == 0 {
return Ok(Some(true));
} else {
read_some = true;
}
}
Poll::Ready(Err(e)) => {
2019-04-06 07:16:04 +00:00
return if e.kind() == io::ErrorKind::WouldBlock {
if read_some {
Ok(Some(false))
} else {
Ok(None)
}
} else if e.kind() == io::ErrorKind::ConnectionReset && read_some {
Ok(Some(true))
} else {
Err(e)
}
2019-04-06 07:16:04 +00:00
}
}
}
}
fn read<T>(
2019-12-07 18:46:51 +00:00
cx: &mut Context<'_>,
io: &mut T,
buf: &mut BytesMut,
) -> Poll<Result<usize, io::Error>>
where
T: AsyncRead + Unpin,
{
Pin::new(io).poll_read_buf(cx, buf)
}
2019-01-29 18:14:00 +00:00
#[cfg(test)]
mod tests {
use actix_service::IntoService;
2019-12-13 05:24:57 +00:00
use futures_util::future::{lazy, ok};
2019-01-29 18:14:00 +00:00
use super::*;
use crate::error::Error;
2019-04-09 02:07:11 +00:00
use crate::h1::{ExpectHandler, UpgradeHandler};
2019-04-11 02:43:09 +00:00
use crate::test::TestBuffer;
2019-01-29 18:14:00 +00:00
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_req_parse_err() {
lazy(|cx| {
2019-04-11 02:43:09 +00:00
let buf = TestBuffer::new("GET /test HTTP/1\r\n\r\n");
2019-01-29 18:14:00 +00:00
2019-04-11 02:43:09 +00:00
let mut h1 = Dispatcher::<_, _, _, _, UpgradeHandler<TestBuffer>>::new(
2019-01-29 18:14:00 +00:00
buf,
ServiceConfig::default(),
2019-02-10 05:32:44 +00:00
CloneableService::new(
2019-03-23 16:40:20 +00:00
(|_| ok::<_, Error>(Response::Ok().finish())).into_service(),
2019-02-10 05:32:44 +00:00
),
2019-04-05 23:46:44 +00:00
CloneableService::new(ExpectHandler),
2019-04-09 02:07:11 +00:00
None,
2019-06-28 08:34:26 +00:00
None,
2019-12-02 11:33:11 +00:00
None,
2019-01-29 18:14:00 +00:00
);
2019-11-19 12:54:19 +00:00
match Pin::new(&mut h1).poll(cx) {
Poll::Pending => panic!(),
Poll::Ready(res) => assert!(res.is_err()),
}
2019-04-09 02:07:11 +00:00
if let DispatcherState::Normal(ref mut inner) = h1.inner {
2019-04-09 02:07:11 +00:00
assert!(inner.flags.contains(Flags::READ_DISCONNECT));
2020-02-27 02:10:55 +00:00
assert_eq!(
&inner.io.take().unwrap().write_buf[..26],
b"HTTP/1.1 400 Bad Request\r\n"
);
2019-04-09 02:07:11 +00:00
}
2019-11-26 05:25:50 +00:00
})
.await;
2019-01-29 18:14:00 +00:00
}
}