From 7f26ed55cdad4a67300447cf92bf8e4975a5c978 Mon Sep 17 00:00:00 2001 From: trinity-1686a Date: Mon, 29 Nov 2021 11:52:42 +0100 Subject: Improved handling of HTTP ranges - correct HTTP code when range syntax is invalid (fix #140) - when multiple ranges are given, simply ignore and send whole file Co-authored-by: Trinity Pointard Reviewed-on: https://git.deuxfleurs.fr/Deuxfleurs/garage/pulls/157 Reviewed-by: Alex Co-authored-by: trinity-1686a Co-committed-by: trinity-1686a --- src/api/error.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) (limited to 'src/api/error.rs') diff --git a/src/api/error.rs b/src/api/error.rs index a57f926b..4ad8ef82 100644 --- a/src/api/error.rs +++ b/src/api/error.rs @@ -1,5 +1,8 @@ +use std::convert::TryInto; + use err_derive::Error; -use hyper::StatusCode; +use hyper::header::HeaderValue; +use hyper::{HeaderMap, StatusCode}; use garage_util::error::Error as GarageError; @@ -57,7 +60,7 @@ pub enum Error { /// The client sent a range header with invalid value #[error(display = "Invalid HTTP range: {:?}", _0)] - InvalidRange(#[error(from)] http_range::HttpRangeParseError), + InvalidRange(#[error(from)] (http_range::HttpRangeParseError, u64)), /// The client sent an invalid request #[error(display = "Bad request: {}", _0)] @@ -90,6 +93,7 @@ impl Error { Error::InternalError(_) | Error::Hyper(_) | Error::Http(_) => { StatusCode::INTERNAL_SERVER_ERROR } + Error::InvalidRange(_) => StatusCode::RANGE_NOT_SATISFIABLE, _ => StatusCode::BAD_REQUEST, } } @@ -127,6 +131,22 @@ impl Error { .into() }) } + + pub fn add_headers(&self, header_map: &mut HeaderMap) { + use hyper::header; + #[allow(clippy::single_match)] + match self { + Error::InvalidRange((_, len)) => { + header_map.append( + header::CONTENT_RANGE, + format!("bytes */{}", len) + .try_into() + .expect("header value only contain ascii"), + ); + } + _ => (), + } + } } /// Trait to map error to the Bad Request error code -- cgit v1.2.3