Reject negative content length in http header

It's almost an illegal input for a Content-Length header with negative
value, so reject it. Otherwise it may cause unexpected behavor when
parsing/receiving http requests.

Signed-off-by: Liu Jiang <gerry@linux.alibaba.com>
This commit is contained in:
Liu Jiang
2020-03-23 21:24:16 +08:00
committed by Adrian Catangiu
parent aefdd1be46
commit 3832d38d8c

View File

@@ -106,11 +106,12 @@ impl Headers {
Header::ContentLength => {
let try_numeric: Result<i32, std::num::ParseIntError> =
std::str::FromStr::from_str(entry[1].trim());
if let Ok(content_length) = try_numeric {
self.content_length = content_length;
Ok(())
} else {
Err(RequestError::InvalidHeader)
match try_numeric {
Ok(content_length) if content_length >= 0 => {
self.content_length = content_length;
Ok(())
}
_ => Err(RequestError::InvalidHeader),
}
}
Header::ContentType => {
@@ -306,6 +307,15 @@ mod tests {
55
);
// Valid headers.
assert_eq!(
Headers::try_from(
b"Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\r\nContent-Length: -55\r\n\r\n"
)
.unwrap_err(),
RequestError::InvalidHeader
);
let bytes: [u8; 10] = [130, 140, 150, 130, 140, 150, 130, 140, 150, 160];
// Invalid headers.
assert!(Headers::try_from(&bytes[..]).is_err());