use std::future::Future as _;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll};
use hyper::body::{Body, Bytes, Frame};
use super::IncomingBody;
pub(super) struct LimitedBody {
pub(super) inner: IncomingBody,
pub(super) limit: u64,
pub(super) read: u64,
pub(super) flags: Arc<BodyFlags>,
}
impl Body for LimitedBody {
type Data = Bytes;
type Error = Box<dyn std::error::Error + Send + Sync>;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<std::result::Result<Frame<Self::Data>, Self::Error>>> {
let this = self.get_mut();
let frame = match Pin::new(&mut this.inner).poll_frame(cx) {
Poll::Ready(Some(Ok(frame))) => frame,
other => return other,
};
if let Some(data) = frame.data_ref() {
this.read += data.len() as u64;
if this.read > this.limit {
this.flags.oversized.store(true, Ordering::Relaxed);
return Poll::Ready(Some(Err(Box::new(BodyTooLarge(this.limit)))));
}
}
Poll::Ready(Some(Ok(frame)))
}
fn size_hint(&self) -> hyper::body::SizeHint {
self.inner.size_hint()
}
}
#[derive(Debug)]
struct BodyTooLarge(u64);
impl std::fmt::Display for BodyTooLarge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "request body exceeded the {} byte limit", self.0)
}
}
impl std::error::Error for BodyTooLarge {}
pub(super) struct StalledBody {
pub(super) inner: IncomingBody,
pub(super) budget: std::time::Duration,
pub(super) deadline: Option<Pin<Box<tokio::time::Sleep>>>,
pub(super) flags: Arc<BodyFlags>,
}
impl Body for StalledBody {
type Data = Bytes;
type Error = Box<dyn std::error::Error + Send + Sync>;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<std::result::Result<Frame<Self::Data>, Self::Error>>> {
let this = self.get_mut();
match Pin::new(&mut this.inner).poll_frame(cx) {
Poll::Ready(ready) => {
this.deadline = None;
Poll::Ready(ready)
}
Poll::Pending => {
let budget = this.budget;
let deadline = this
.deadline
.get_or_insert_with(|| Box::pin(tokio::time::sleep(budget)));
match deadline.as_mut().poll(cx) {
Poll::Ready(()) => {
this.flags.stalled.store(true, Ordering::Relaxed);
Poll::Ready(Some(Err(Box::new(BodyStalled(budget)))))
}
Poll::Pending => Poll::Pending,
}
}
}
}
fn size_hint(&self) -> hyper::body::SizeHint {
self.inner.size_hint()
}
}
#[derive(Debug)]
struct BodyStalled(std::time::Duration);
impl std::fmt::Display for BodyStalled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"the request body stalled: no bytes arrived within {} ms",
self.0.as_millis()
)
}
}
impl std::error::Error for BodyStalled {}
pub(crate) struct BodyGuards(pub(super) Arc<BodyFlags>);
#[derive(Default)]
pub(super) struct BodyFlags {
pub(super) oversized: AtomicBool,
pub(super) stalled: AtomicBool,
}
impl BodyGuards {
pub(crate) fn oversized(&self) -> bool {
self.0.oversized.load(Ordering::Relaxed)
}
pub(crate) fn stalled(&self) -> bool {
self.0.stalled.load(Ordering::Relaxed)
}
}