Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/common/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,7 @@ impl Time {
pub(crate) fn check(&self, dur: Dur, name: &'static str) -> Option<Duration> {
match dur {
Dur::Default(Some(dur)) => match self {
Time::Empty => {
warn!("timeout `{}` has default, but no timer set", name,);
None
}
Time::Empty => None,
Time::Timer(..) => Some(dur),
},
Dur::Configured(Some(dur)) => match self {
Expand Down
16 changes: 14 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ pub(super) enum Kind {
/// User took too long to send headers.
#[cfg(all(feature = "http1", feature = "server"))]
HeaderTimeout,
/// User took too long to start sending another request.
#[cfg(all(feature = "http1", feature = "server"))]
IdleTimeout,
/// Error while reading a body from connection.
#[cfg(all(
any(feature = "client", feature = "server"),
Expand Down Expand Up @@ -310,11 +313,13 @@ impl Error {
/// Returns true if the error was caused by a timeout.
///
/// For HTTP/1 servers, this includes the header read timeout (see
/// [`header_read_timeout`](crate::server::conn::http1::Builder::header_read_timeout)).
/// [`header_read_timeout`](crate::server::conn::http1::Builder::header_read_timeout))
/// and the idle timeout (see
/// [`idle_timeout`](crate::server::conn::http1::Builder::idle_timeout)).
/// It also covers any timeout set via a user-provided timer.
pub fn is_timeout(&self) -> bool {
#[cfg(all(feature = "http1", feature = "server"))]
if matches!(self.inner.kind, Kind::HeaderTimeout) {
if matches!(self.inner.kind, Kind::HeaderTimeout | Kind::IdleTimeout) {
return true;
}
self.find_source::<TimedOut>().is_some()
Expand Down Expand Up @@ -437,6 +442,11 @@ impl Error {
Error::new(Kind::HeaderTimeout)
}

#[cfg(all(feature = "http1", feature = "server"))]
pub(super) fn new_idle_timeout() -> Error {
Error::new(Kind::IdleTimeout)
}

#[cfg(feature = "http1")]
#[cfg(feature = "server")]
pub(super) fn new_user_unsupported_status_code() -> Error {
Expand Down Expand Up @@ -540,6 +550,8 @@ impl Error {
Kind::Canceled => "operation was canceled",
#[cfg(all(feature = "http1", feature = "server"))]
Kind::HeaderTimeout => "read header from client timeout",
#[cfg(all(feature = "http1", feature = "server"))]
Kind::IdleTimeout => "idle connection timeout",
#[cfg(all(
any(feature = "client", feature = "server"),
any(feature = "http1", feature = "http2")
Expand Down
117 changes: 80 additions & 37 deletions src/proto/h1/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,11 @@ where
#[cfg(feature = "server")]
h1_header_read_timeout: None,
#[cfg(feature = "server")]
h1_header_read_timeout_fut: None,
h1_timeout_fut: None,
#[cfg(feature = "server")]
h1_header_read_timeout_running: false,
h1_idle_timeout: None,
#[cfg(feature = "server")]
h1_read_head_timeout_phase: None,
#[cfg(feature = "server")]
date_header: true,
#[cfg(feature = "server")]
Expand Down Expand Up @@ -151,6 +153,11 @@ where
self.state.h1_header_read_timeout = Some(val);
}

#[cfg(feature = "server")]
pub(crate) fn set_http1_idle_timeout(&mut self, val: Duration) {
self.state.h1_idle_timeout = Some(val);
}

#[cfg(feature = "server")]
pub(crate) fn set_allow_half_close(&mut self) {
self.state.allow_half_close = true;
Expand Down Expand Up @@ -220,25 +227,6 @@ where
debug_assert!(self.can_read_head());
trace!("Conn::read_head");

#[cfg(feature = "server")]
if !self.state.h1_header_read_timeout_running {
if let Some(h1_header_read_timeout) = self.state.h1_header_read_timeout {
let deadline = self.state.timer.now() + h1_header_read_timeout;
self.state.h1_header_read_timeout_running = true;
match &mut self.state.h1_header_read_timeout_fut {
Some(h1_header_read_timeout_fut) => {
trace!("resetting h1 header read timeout timer");
self.state.timer.reset(h1_header_read_timeout_fut, deadline);
}
None => {
trace!("setting h1 header read timeout timer");
self.state.h1_header_read_timeout_fut =
Some(self.state.timer.sleep_until(deadline));
}
}
}
}

let msg = match self.io.parse::<T>(
cx,
&mut ParseContext {
Expand All @@ -259,17 +247,8 @@ where
Poll::Ready(Err(e)) => return self.on_read_head_error(e),
Poll::Pending => {
#[cfg(feature = "server")]
if self.state.h1_header_read_timeout_running {
if let Some(h1_header_read_timeout_fut) =
&mut self.state.h1_header_read_timeout_fut
{
if Pin::new(h1_header_read_timeout_fut).poll(cx).is_ready() {
self.state.h1_header_read_timeout_running = false;

warn!("read header from client timeout");
return Poll::Ready(Some(Err(crate::Error::new_header_timeout())));
}
}
if let Poll::Ready(err) = self.poll_read_head_timeout(cx) {
return Poll::Ready(Some(Err(err)));
}

return Poll::Pending;
Expand All @@ -278,7 +257,7 @@ where

#[cfg(feature = "server")]
{
self.state.h1_header_read_timeout_running = false;
self.state.h1_read_head_timeout_phase = None;
}

// Note: don't deconstruct `msg` into local variables, it appears
Expand Down Expand Up @@ -335,6 +314,53 @@ where
Poll::Ready(Some(Ok((msg.head, msg.decode, wants))))
}

/// Polls the header read timeout or, if waiting for another request, the
/// idle timeout.
#[cfg(feature = "server")]
fn poll_read_head_timeout(&mut self, cx: &mut Context<'_>) -> Poll<crate::Error> {
let phase = if self.state.is_idle() && self.io.read_buf().len() < IDLE_TIMEOUT_MIN_BYTES {
ReadHeadTimeoutPhase::Idle
} else {
ReadHeadTimeoutPhase::Header
};

let timeout = match phase {
ReadHeadTimeoutPhase::Idle => self.state.h1_idle_timeout,
ReadHeadTimeoutPhase::Header => self.state.h1_header_read_timeout,
};
let timeout = match timeout {
Some(timeout) => timeout,
None => return Poll::Pending,
};

if self.state.h1_read_head_timeout_phase != Some(phase) {
self.state.h1_read_head_timeout_phase = Some(phase);
trace!("setting h1 {:?} timeout timer: {:?}", phase, timeout);
let timer = &self.state.timer;
let deadline = timer.now() + timeout;
match &mut self.state.h1_timeout_fut {
Some(fut) => timer.reset(fut, deadline),
fut @ None => *fut = Some(timer.sleep_until(deadline)),
}
}

if let Some(fut) = &mut self.state.h1_timeout_fut {
if Pin::new(fut).poll(cx).is_ready() {
return Poll::Ready(match phase {
ReadHeadTimeoutPhase::Idle => {
debug!("idle connection timeout");
crate::Error::new_idle_timeout()
}
ReadHeadTimeoutPhase::Header => {
warn!("read header from client timeout");
crate::Error::new_header_timeout()
}
});
}
}
Poll::Pending
}

fn on_read_head_error<Z>(&mut self, e: crate::Error) -> Poll<Option<crate::Result<Z>>> {
// If we are currently waiting on a message, then an empty
// message should be reported as an error. If not, it is just
Expand Down Expand Up @@ -964,9 +990,12 @@ struct State {
#[cfg(feature = "server")]
h1_header_read_timeout: Option<Duration>,
#[cfg(feature = "server")]
h1_header_read_timeout_fut: Option<Pin<Box<dyn Sleep>>>,
h1_timeout_fut: Option<Pin<Box<dyn Sleep>>>,
#[cfg(feature = "server")]
h1_idle_timeout: Option<Duration>,
/// Whether `h1_timeout_fut` is a header read timeout or an idle timeout.
#[cfg(feature = "server")]
h1_header_read_timeout_running: bool,
h1_read_head_timeout_phase: Option<ReadHeadTimeoutPhase>,
#[cfg(feature = "server")]
date_header: bool,
#[cfg(feature = "server")]
Expand Down Expand Up @@ -996,6 +1025,20 @@ struct State {
allow_trailer_fields: bool,
}

#[cfg(feature = "server")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReadHeadTimeoutPhase {
Idle,
Header,
}

/// After the first request, this many bytes must be received before the idle
/// timeout ends and the next header read timeout begins. The current value
/// matches Go's `net/http`, such that a few stray bytes like CRLF don't end the
/// idle period.
#[cfg(feature = "server")]
const IDLE_TIMEOUT_MIN_BYTES: usize = 4;

#[derive(Debug)]
enum Reading {
Init,
Expand Down Expand Up @@ -1161,8 +1204,8 @@ impl State {
}

#[cfg(feature = "server")]
if self.h1_header_read_timeout.is_some() {
// Next read will start and poll the header read timeout,
if self.h1_idle_timeout.is_some() || self.h1_header_read_timeout.is_some() {
// Next read will start and poll the idle/header read timeout,
// so we can close the connection if another header isn't
// received in a timely manner.
self.notify_read = true;
Expand Down
36 changes: 34 additions & 2 deletions src/server/conn/http1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub struct Builder {
h1_max_headers: Option<usize>,
h1_max_header_size: Option<usize>,
h1_header_read_timeout: Dur,
h1_idle_timeout: Dur,
h1_writev: Option<bool>,
max_buf_size: Option<usize>,
pipeline_flush: bool,
Expand Down Expand Up @@ -251,6 +252,7 @@ impl Builder {
h1_max_headers: None,
h1_max_header_size: None,
h1_header_read_timeout: Dur::Default(Some(Duration::from_secs(30))),
h1_idle_timeout: Dur::Default(Some(Duration::from_secs(60))),
h1_writev: None,
max_buf_size: None,
pipeline_flush: false,
Expand Down Expand Up @@ -358,8 +360,10 @@ impl Builder {
self
}

/// Set a timeout for reading client request headers. If a client does not
/// transmit the entire header within this time, the connection is closed.
/// Set a timeout for reading client request headers, starting when a
/// connection opens (first request) and upon the start of a subsequent
/// request's header. If a client does not transmit the entire header within
/// this time, the connection is closed.
///
/// Requires a [`Timer`] set by [`Builder::timer`] to take effect. Panics if `header_read_timeout` is configured
/// without a [`Timer`].
Expand All @@ -372,6 +376,24 @@ impl Builder {
self
}

/// Set a timeout for idleness on keep-alive connections. If a client does
/// not start transmitting the header within this time after the last
/// response, the connection is closed.
///
/// Once the client starts transmitting such a header,
/// [`Builder::header_read_timeout`] applies instead.
///
/// Requires a [`Timer`] set by [`Builder::timer`] to take effect. Panics if `idle_timeout` is configured
/// without a [`Timer`].
///
/// Pass `None` to disable.
///
/// Default is 60 seconds.
pub fn idle_timeout(&mut self, idle_timeout: impl Into<Option<Duration>>) -> &mut Self {
self.h1_idle_timeout = Dur::Configured(idle_timeout.into());
self
}

/// Set whether HTTP/1 connections should try to use vectored writes,
/// or always flatten into a single buffer.
///
Expand Down Expand Up @@ -496,12 +518,22 @@ impl Builder {
if let Some(max_header_size) = self.h1_max_header_size {
conn.set_http1_max_header_size(max_header_size);
}
if matches!(self.timer, Time::Empty)
&& [self.h1_header_read_timeout, self.h1_idle_timeout]
.iter()
.any(|dur| matches!(dur, Dur::Default(Some(_))))
{
warn!("default header_read_timeout and/or idle_timeout disabled: no timer set");
}
if let Some(dur) = self
.timer
.check(self.h1_header_read_timeout, "header_read_timeout")
{
conn.set_http1_header_read_timeout(dur);
}
if let Some(dur) = self.timer.check(self.h1_idle_timeout, "idle_timeout") {
conn.set_http1_idle_timeout(dur);
}
if let Some(writev) = self.h1_writev {
if writev {
conn.set_write_strategy_queue();
Expand Down
Loading
Loading