2021-05-25 04:21:20 +02:00
|
|
|
use std::{
|
|
|
|
cmp,
|
2021-06-17 18:57:58 +02:00
|
|
|
error::Error as StdError,
|
2021-05-25 04:21:20 +02:00
|
|
|
future::Future,
|
|
|
|
marker::PhantomData,
|
|
|
|
net,
|
|
|
|
pin::Pin,
|
|
|
|
rc::Rc,
|
|
|
|
task::{Context, Poll},
|
|
|
|
};
|
2019-02-06 20:44:15 +01:00
|
|
|
|
|
|
|
use actix_codec::{AsyncRead, AsyncWrite};
|
2021-12-02 19:16:34 +01:00
|
|
|
use actix_rt::time::{sleep, Sleep};
|
2019-02-06 20:44:15 +01:00
|
|
|
use actix_service::Service;
|
2021-05-25 04:21:20 +02:00
|
|
|
use actix_utils::future::poll_fn;
|
2019-02-06 20:44:15 +01:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2021-01-04 01:49:02 +01:00
|
|
|
use futures_core::ready;
|
2021-11-04 16:15:23 +01:00
|
|
|
use h2::{
|
|
|
|
server::{Connection, SendResponse},
|
|
|
|
Ping, PingPong,
|
|
|
|
};
|
2019-12-13 05:59:02 +01:00
|
|
|
use log::{error, trace};
|
2021-05-25 04:21:20 +02:00
|
|
|
use pin_project_lite::pin_project;
|
2019-02-06 20:44:15 +01:00
|
|
|
|
2021-06-17 18:57:58 +02:00
|
|
|
use crate::{
|
2021-12-04 20:40:47 +01:00
|
|
|
body::{BodySize, BoxBody, MessageBody},
|
2021-06-17 18:57:58 +02:00
|
|
|
config::ServiceConfig,
|
2021-12-09 12:27:29 +01:00
|
|
|
header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING},
|
2021-06-17 18:57:58 +02:00
|
|
|
service::HttpFlow,
|
2021-12-07 18:23:34 +01:00
|
|
|
Extensions, OnConnectData, Payload, Request, Response, ResponseHead,
|
2021-06-17 18:57:58 +02:00
|
|
|
};
|
2019-02-06 20:44:15 +01:00
|
|
|
|
|
|
|
const CHUNK_SIZE: usize = 16_384;
|
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
pin_project! {
|
|
|
|
/// Dispatcher for HTTP/2 protocol.
|
|
|
|
pub struct Dispatcher<T, S, B, X, U> {
|
|
|
|
flow: Rc<HttpFlow<S, X, U>>,
|
|
|
|
connection: Connection<T, Bytes>,
|
2021-12-07 18:23:34 +01:00
|
|
|
conn_data: Option<Rc<Extensions>>,
|
2021-05-25 04:21:20 +02:00
|
|
|
config: ServiceConfig,
|
|
|
|
peer_addr: Option<net::SocketAddr>,
|
2021-11-04 16:15:23 +01:00
|
|
|
ping_pong: Option<H2PingPong>,
|
|
|
|
_phantom: PhantomData<B>
|
2021-05-25 04:21:20 +02:00
|
|
|
}
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
|
|
|
|
2021-11-04 16:15:23 +01:00
|
|
|
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
|
|
|
|
where
|
|
|
|
T: AsyncRead + AsyncWrite + Unpin,
|
|
|
|
{
|
2019-06-28 10:34:26 +02:00
|
|
|
pub(crate) fn new(
|
2021-12-04 20:40:47 +01:00
|
|
|
mut conn: Connection<T, Bytes>,
|
2021-12-07 18:23:34 +01:00
|
|
|
flow: Rc<HttpFlow<S, X, U>>,
|
2019-02-06 20:44:15 +01:00
|
|
|
config: ServiceConfig,
|
2019-04-16 18:54:02 +02:00
|
|
|
peer_addr: Option<net::SocketAddr>,
|
2021-12-07 18:23:34 +01:00
|
|
|
conn_data: OnConnectData,
|
2021-12-02 19:16:34 +01:00
|
|
|
timer: Option<Pin<Box<Sleep>>>,
|
2019-02-06 20:44:15 +01:00
|
|
|
) -> Self {
|
2021-12-02 19:16:34 +01:00
|
|
|
let ping_pong = config.keep_alive().map(|dur| H2PingPong {
|
|
|
|
timer: timer
|
|
|
|
.map(|mut timer| {
|
|
|
|
// reset timer if it's received from new function.
|
|
|
|
timer.as_mut().reset(config.now() + dur);
|
|
|
|
timer
|
|
|
|
})
|
|
|
|
.unwrap_or_else(|| Box::pin(sleep(dur))),
|
2021-11-04 16:15:23 +01:00
|
|
|
on_flight: false,
|
2021-12-04 20:40:47 +01:00
|
|
|
ping_pong: conn.ping_pong().unwrap(),
|
2021-11-04 16:15:23 +01:00
|
|
|
});
|
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
Self {
|
2021-02-07 02:00:40 +01:00
|
|
|
flow,
|
2019-02-06 20:44:15 +01:00
|
|
|
config,
|
2019-04-16 18:54:02 +02:00
|
|
|
peer_addr,
|
2021-12-04 20:40:47 +01:00
|
|
|
connection: conn,
|
2021-12-07 18:23:34 +01:00
|
|
|
conn_data: conn_data.0.map(Rc::new),
|
2021-11-04 16:15:23 +01:00
|
|
|
ping_pong,
|
2021-01-04 01:49:02 +01:00
|
|
|
_phantom: PhantomData,
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-04 16:15:23 +01:00
|
|
|
struct H2PingPong {
|
|
|
|
timer: Pin<Box<Sleep>>,
|
|
|
|
on_flight: bool,
|
|
|
|
ping_pong: PingPong,
|
|
|
|
}
|
|
|
|
|
2021-01-06 19:43:52 +01:00
|
|
|
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
2019-02-06 20:44:15 +01:00
|
|
|
where
|
2019-12-02 12:33:11 +01:00
|
|
|
T: AsyncRead + AsyncWrite + Unpin,
|
2021-05-05 19:36:02 +02:00
|
|
|
|
2021-01-04 00:47:04 +01:00
|
|
|
S: Service<Request>,
|
2021-12-04 20:40:47 +01:00
|
|
|
S::Error: Into<Response<BoxBody>>,
|
2019-11-19 13:54:19 +01:00
|
|
|
S::Future: 'static,
|
2021-05-25 04:21:20 +02:00
|
|
|
S::Response: Into<Response<B>>,
|
2021-05-05 19:36:02 +02:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
B: MessageBody,
|
2019-02-06 20:44:15 +01:00
|
|
|
{
|
2021-05-25 04:21:20 +02:00
|
|
|
type Output = Result<(), crate::error::DispatchError>;
|
2019-02-06 20:44:15 +01:00
|
|
|
|
|
|
|
#[inline]
|
2019-12-07 19:46:51 +01:00
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
2019-11-15 10:54:11 +01:00
|
|
|
let this = self.get_mut();
|
|
|
|
|
2021-11-04 16:15:23 +01:00
|
|
|
loop {
|
|
|
|
match Pin::new(&mut this.connection).poll_accept(cx)? {
|
|
|
|
Poll::Ready(Some((req, tx))) => {
|
|
|
|
let (parts, body) = req.into_parts();
|
2021-12-24 18:47:47 +01:00
|
|
|
let payload = crate::h2::Payload::new(body);
|
|
|
|
let pl = Payload::H2 { payload };
|
2021-11-04 16:15:23 +01:00
|
|
|
let mut req = Request::with_payload(pl);
|
|
|
|
|
|
|
|
let head = req.head_mut();
|
|
|
|
head.uri = parts.uri;
|
|
|
|
head.method = parts.method;
|
|
|
|
head.version = parts.version;
|
|
|
|
head.headers = parts.headers.into();
|
|
|
|
head.peer_addr = this.peer_addr;
|
|
|
|
|
2021-12-07 18:23:34 +01:00
|
|
|
req.conn_data = this.conn_data.as_ref().map(Rc::clone);
|
2021-11-04 16:15:23 +01:00
|
|
|
|
|
|
|
let fut = this.flow.service.call(req);
|
|
|
|
let config = this.config.clone();
|
|
|
|
|
|
|
|
// multiplex request handling with spawn task
|
|
|
|
actix_rt::spawn(async move {
|
|
|
|
// resolve service call and send response.
|
|
|
|
let res = match fut.await {
|
|
|
|
Ok(res) => handle_response(res.into(), tx, config).await,
|
|
|
|
Err(err) => {
|
2021-12-04 20:40:47 +01:00
|
|
|
let res: Response<BoxBody> = err.into();
|
2021-11-04 16:15:23 +01:00
|
|
|
handle_response(res, tx, config).await
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// log error.
|
|
|
|
if let Err(err) = res {
|
|
|
|
match err {
|
|
|
|
DispatchError::SendResponse(err) => {
|
|
|
|
trace!("Error sending HTTP/2 response: {:?}", err)
|
|
|
|
}
|
|
|
|
DispatchError::SendData(err) => warn!("{:?}", err),
|
|
|
|
DispatchError::ResponseBody(err) => {
|
|
|
|
error!("Response payload stream error: {:?}", err)
|
|
|
|
}
|
|
|
|
}
|
2021-05-25 04:21:20 +02:00
|
|
|
}
|
2021-11-04 16:15:23 +01:00
|
|
|
});
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
2021-11-04 16:15:23 +01:00
|
|
|
Poll::Ready(None) => return Poll::Ready(Ok(())),
|
|
|
|
Poll::Pending => match this.ping_pong.as_mut() {
|
|
|
|
Some(ping_pong) => loop {
|
|
|
|
if ping_pong.on_flight {
|
|
|
|
// When have on flight ping pong. poll pong and and keep alive timer.
|
|
|
|
// on success pong received update keep alive timer to determine the next timing of
|
|
|
|
// ping pong.
|
|
|
|
match ping_pong.ping_pong.poll_pong(cx)? {
|
|
|
|
Poll::Ready(_) => {
|
|
|
|
ping_pong.on_flight = false;
|
|
|
|
|
2021-12-08 07:01:11 +01:00
|
|
|
let dead_line = this.config.keep_alive_expire().unwrap();
|
2021-11-04 16:15:23 +01:00
|
|
|
ping_pong.timer.as_mut().reset(dead_line);
|
|
|
|
}
|
|
|
|
Poll::Pending => {
|
2021-12-08 07:01:11 +01:00
|
|
|
return ping_pong.timer.as_mut().poll(cx).map(|_| Ok(()))
|
2021-11-04 16:15:23 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// When there is no on flight ping pong. keep alive timer is used to wait for next
|
|
|
|
// timing of ping pong. Therefore at this point it serves as an interval instead.
|
|
|
|
ready!(ping_pong.timer.as_mut().poll(cx));
|
|
|
|
|
|
|
|
ping_pong.ping_pong.send_ping(Ping::opaque())?;
|
|
|
|
|
|
|
|
let dead_line = this.config.keep_alive_expire().unwrap();
|
|
|
|
ping_pong.timer.as_mut().reset(dead_line);
|
|
|
|
|
|
|
|
ping_pong.on_flight = true;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
None => return Poll::Pending,
|
|
|
|
},
|
|
|
|
}
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
2021-05-25 04:21:20 +02:00
|
|
|
}
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
enum DispatchError {
|
|
|
|
SendResponse(h2::Error),
|
|
|
|
SendData(h2::Error),
|
2021-06-17 18:57:58 +02:00
|
|
|
ResponseBody(Box<dyn StdError>),
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
async fn handle_response<B>(
|
|
|
|
res: Response<B>,
|
|
|
|
mut tx: SendResponse<Bytes>,
|
|
|
|
config: ServiceConfig,
|
|
|
|
) -> Result<(), DispatchError>
|
2019-02-06 20:44:15 +01:00
|
|
|
where
|
2019-11-20 18:33:22 +01:00
|
|
|
B: MessageBody,
|
2019-02-06 20:44:15 +01:00
|
|
|
{
|
2021-05-25 04:21:20 +02:00
|
|
|
let (res, body) = res.replace_body(());
|
2021-01-04 01:49:02 +01:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
// prepare response.
|
|
|
|
let mut size = body.size();
|
|
|
|
let res = prepare_response(config, res.head(), &mut size);
|
|
|
|
let eof = size.is_eof();
|
2019-02-06 20:44:15 +01:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
// send response head and return on eof.
|
|
|
|
let mut stream = tx
|
|
|
|
.send_response(res, eof)
|
|
|
|
.map_err(DispatchError::SendResponse)?;
|
2019-02-06 20:44:15 +01:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
if eof {
|
|
|
|
return Ok(());
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
|
|
|
|
2021-12-09 12:27:29 +01:00
|
|
|
// poll response body and send chunks to client
|
2021-05-25 04:21:20 +02:00
|
|
|
actix_rt::pin!(body);
|
2021-05-05 19:36:02 +02:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
while let Some(res) = poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
|
|
|
let mut chunk = res.map_err(|err| DispatchError::ResponseBody(err.into()))?;
|
2021-01-04 01:49:02 +01:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
'send: loop {
|
2021-12-09 12:27:29 +01:00
|
|
|
let chunk_size = cmp::min(chunk.len(), CHUNK_SIZE);
|
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
// reserve enough space and wait for stream ready.
|
2021-12-09 12:27:29 +01:00
|
|
|
stream.reserve_capacity(chunk_size);
|
2021-01-04 01:49:02 +01:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
match poll_fn(|cx| stream.poll_capacity(cx)).await {
|
|
|
|
// No capacity left. drop body and return.
|
|
|
|
None => return Ok(()),
|
2021-05-09 21:12:48 +02:00
|
|
|
|
2021-12-09 12:27:29 +01:00
|
|
|
Some(Err(err)) => return Err(DispatchError::SendData(err)),
|
|
|
|
|
|
|
|
Some(Ok(cap)) => {
|
|
|
|
// split chunk to writeable size and send to client
|
2021-05-25 04:21:20 +02:00
|
|
|
let len = chunk.len();
|
2021-12-09 12:27:29 +01:00
|
|
|
let bytes = chunk.split_to(cmp::min(len, cap));
|
2021-05-25 04:21:20 +02:00
|
|
|
|
|
|
|
stream
|
|
|
|
.send_data(bytes, false)
|
|
|
|
.map_err(DispatchError::SendData)?;
|
|
|
|
|
|
|
|
// Current chuck completely sent. break send loop and poll next one.
|
|
|
|
if chunk.is_empty() {
|
|
|
|
break 'send;
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
|
|
|
}
|
2020-07-22 01:28:33 +02:00
|
|
|
}
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|
|
|
|
}
|
2021-05-25 04:21:20 +02:00
|
|
|
|
|
|
|
// response body streaming finished. send end of stream and return.
|
|
|
|
stream
|
|
|
|
.send_data(Bytes::new(), true)
|
|
|
|
.map_err(DispatchError::SendData)?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn prepare_response(
|
|
|
|
config: ServiceConfig,
|
|
|
|
head: &ResponseHead,
|
|
|
|
size: &mut BodySize,
|
|
|
|
) -> http::Response<()> {
|
|
|
|
let mut has_date = false;
|
|
|
|
let mut skip_len = size != &BodySize::Stream;
|
|
|
|
|
|
|
|
let mut res = http::Response::new(());
|
|
|
|
*res.status_mut() = head.status;
|
|
|
|
*res.version_mut() = http::Version::HTTP_2;
|
|
|
|
|
|
|
|
// Content length
|
|
|
|
match head.status {
|
|
|
|
http::StatusCode::NO_CONTENT
|
|
|
|
| http::StatusCode::CONTINUE
|
|
|
|
| http::StatusCode::PROCESSING => *size = BodySize::None,
|
|
|
|
http::StatusCode::SWITCHING_PROTOCOLS => {
|
|
|
|
skip_len = true;
|
|
|
|
*size = BodySize::Stream;
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
|
|
|
|
let _ = match size {
|
|
|
|
BodySize::None | BodySize::Stream => None,
|
2021-11-16 10:21:10 +01:00
|
|
|
|
2021-12-27 17:15:20 +01:00
|
|
|
BodySize::Sized(0) => {
|
|
|
|
#[allow(clippy::declare_interior_mutable_const)]
|
|
|
|
const HV_ZERO: HeaderValue = HeaderValue::from_static("0");
|
|
|
|
res.headers_mut().insert(CONTENT_LENGTH, HV_ZERO)
|
|
|
|
}
|
2021-11-16 10:21:10 +01:00
|
|
|
|
2021-05-25 04:21:20 +02:00
|
|
|
BodySize::Sized(len) => {
|
|
|
|
let mut buf = itoa::Buffer::new();
|
|
|
|
|
|
|
|
res.headers_mut().insert(
|
|
|
|
CONTENT_LENGTH,
|
|
|
|
HeaderValue::from_str(buf.format(*len)).unwrap(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// copy headers
|
|
|
|
for (key, value) in head.headers.iter() {
|
|
|
|
match *key {
|
|
|
|
// TODO: consider skipping other headers according to:
|
2021-12-02 04:45:04 +01:00
|
|
|
// https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.2
|
2021-05-25 04:21:20 +02:00
|
|
|
// omit HTTP/1.x only headers
|
|
|
|
CONNECTION | TRANSFER_ENCODING => continue,
|
|
|
|
CONTENT_LENGTH if skip_len => continue,
|
|
|
|
DATE => has_date = true,
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
|
|
|
|
res.headers_mut().append(key, value.clone());
|
|
|
|
}
|
|
|
|
|
|
|
|
// set date header
|
|
|
|
if !has_date {
|
|
|
|
let mut bytes = BytesMut::with_capacity(29);
|
|
|
|
config.set_date_header(&mut bytes);
|
|
|
|
res.headers_mut().insert(
|
|
|
|
DATE,
|
|
|
|
// SAFETY: serialized date-times are known ASCII strings
|
|
|
|
unsafe { HeaderValue::from_maybe_shared_unchecked(bytes.freeze()) },
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
res
|
2019-02-06 20:44:15 +01:00
|
|
|
}
|