diff --git a/_legacy/server/echo.md b/_legacy/server/echo.md index e083e96..0788b80 100644 --- a/_legacy/server/echo.md +++ b/_legacy/server/echo.md @@ -170,16 +170,29 @@ collect the full body. In this case, we can't really generate a `Response` immediately. Instead, we must wait for the full request body to be received. -We want to concatenate the request body, and map the result into our `reverse` function, and return the eventual result. We can make use of the `hyper::body::to_bytes` utility function to make this easy. +We want to concatenate the request body, and map the result into our `reverse` +function, and return the eventual result. We can make use of the +`hyper::body::to_bytes` utility function to make this easy. + +> Note: You must always be careful not to buffer without a max bounds. We'll +> set a 64kb maximum here. ```rust # extern crate hyper; -# use hyper::{Body, Method, Request, Response}; +# use hyper::{body::HttpBody, Body, Method, Request, Response}; # async fn echo(req: Request) -> Result, hyper::Error> { # let mut response = Response::default(); # match (req.method(), req.uri().path()) { // Yet another route inside our match block... (&Method::POST, "/echo/reverse") => { + // Protect our server from massive bodies. + let upper = req.body().size_hint().upper().unwrap_or(u64::MAX); + if upper > 1024 * 64 { + let mut resp = Response::new(Body::from("Body too big")); + *resp.status_mut() = hyper::StatusCode::PAYLOAD_TOO_LARGE; + return Ok(resp); + } + // Await the full body to be concatenated into a single `Bytes`... let full_body = hyper::body::to_bytes(req.into_body()).await?; diff --git a/_stable/server/echo.md b/_stable/server/echo.md index 4f9068a..658f0b6 100644 --- a/_stable/server/echo.md +++ b/_stable/server/echo.md @@ -191,18 +191,29 @@ stream to completion, collecting all the data and trailer frames into a `Collect We can easily turn the `Collected` body into a single `Bytes` by calling its `into_bytes` method. +> Note: You must always be careful not to buffer without a max bounds. We'll +> set a 64kb maximum here. + ```rust # extern crate hyper; # extern crate http_body_util; # use hyper::body::Bytes; # use http_body_util::{combinators::BoxBody, BodyExt, Empty, Full}; -# use hyper::{Method, Request, Response, StatusCode}; +# use hyper::{body::Body, Method, Request, Response, StatusCode}; # async fn echo( # req: Request, # ) -> Result>, hyper::Error> { # match (req.method(), req.uri().path()) { // Yet another route inside our match block... (&Method::POST, "/echo/reversed") => { + // Protect our server from massive bodies. + let upper = req.body().size_hint().upper().unwrap_or(u64::MAX); + if upper > 1024 * 64 { + let mut resp = Response::new(full("Body too big")); + *resp.status_mut() = hyper::StatusCode::PAYLOAD_TOO_LARGE; + return Ok(resp); + } + // Await the whole body to be collected into a single `Bytes`... let whole_body = req.collect().await?.to_bytes();