1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-26 03:21:08 +00:00

bound initial allocation in to_bytes_limited

This commit is contained in:
Rob Ede 2023-03-13 13:40:07 +00:00
parent 9e7a6fe57b
commit 44c5cdaa10
No known key found for this signature in database
GPG key ID: 97C636207D3EF933

View file

@ -32,7 +32,7 @@ use super::{BodySize, MessageBody};
pub async fn to_bytes<B: MessageBody>(body: B) -> Result<Bytes, B::Error> { pub async fn to_bytes<B: MessageBody>(body: B) -> Result<Bytes, B::Error> {
to_bytes_limited(body, usize::MAX) to_bytes_limited(body, usize::MAX)
.await .await
.expect("body should never overflow usize::MAX") .expect("body should never yield more than usize::MAX bytes")
} }
/// Error type returned from [`to_bytes_limited`] when body produced exceeds limit. /// Error type returned from [`to_bytes_limited`] when body produced exceeds limit.
@ -70,12 +70,14 @@ pub async fn to_bytes_limited<B: MessageBody>(
body: B, body: B,
limit: usize, limit: usize,
) -> Result<Result<Bytes, B::Error>, BodyLimitExceeded> { ) -> Result<Result<Bytes, B::Error>, BodyLimitExceeded> {
/// Sensible default (32kB) for initial, bounded allocation when collecting body bytes.
const INITIAL_ALLOC_BYTES: usize = 32 * 1024;
let cap = match body.size() { let cap = match body.size() {
BodySize::None | BodySize::Sized(0) => return Ok(Ok(Bytes::new())), BodySize::None | BodySize::Sized(0) => return Ok(Ok(Bytes::new())),
BodySize::Sized(size) if size as usize > limit => return Err(BodyLimitExceeded), BodySize::Sized(size) if size as usize > limit => return Err(BodyLimitExceeded),
BodySize::Sized(size) => size as usize, BodySize::Sized(size) => (size as usize).min(INITIAL_ALLOC_BYTES),
// good enough first guess for chunk size BodySize::Stream => INITIAL_ALLOC_BYTES,
BodySize::Stream => 32_768,
}; };
let mut exceeded_limit = false; let mut exceeded_limit = false;