Skip to main content

actix_web/http/header/
range.rs

1use std::{
2    cmp,
3    fmt::{self, Display, Write},
4    str::FromStr,
5};
6
7use actix_http::{error::ParseError, header, HttpMessage};
8
9use super::{Header, HeaderName, HeaderValue, InvalidHeaderValue, TryIntoHeaderValue, Writer};
10
11/// `Range` header, defined
12/// in [RFC 7233 §3.1](https://www.rfc-editor.org/info/rfc7233/#section-3.1)
13///
14/// The "Range" header field on a GET request modifies the method semantics to request transfer of
15/// only one or more sub-ranges of the selected representation data, rather than the entire selected
16/// representation data.
17///
18/// # Note
19/// This is a request header. Servers should not send `Range` in responses; use
20/// [`ContentRange`](super::ContentRange) / the `Content-Range` header for partial responses.
21///
22/// # ABNF
23/// ```plain
24/// Range = byte-ranges-specifier / other-ranges-specifier
25/// other-ranges-specifier = other-range-unit "=" other-range-set
26/// other-range-set = 1*VCHAR
27///
28/// bytes-unit = "bytes"
29///
30/// byte-ranges-specifier = bytes-unit "=" byte-range-set
31/// byte-range-set = 1#(byte-range-spec / suffix-byte-range-spec)
32/// byte-range-spec = first-byte-pos "-" [last-byte-pos]
33/// suffix-byte-range-spec = "-" suffix-length
34/// suffix-length = 1*DIGIT
35/// first-byte-pos = 1*DIGIT
36/// last-byte-pos = 1*DIGIT
37/// ```
38///
39/// # Example Values
40/// * `bytes=1000-`
41/// * `bytes=-50`
42/// * `bytes=0-1,30-40`
43/// * `bytes=0-10,20-90,-100`
44/// * `custom_unit=0-123`
45/// * `custom_unit=xxx-yyy`
46///
47/// # Examples
48/// ```
49/// use actix_web::{http::header::{ByteRangeSpec, Range}, test};
50///
51/// let req = test::TestRequest::default()
52///     .insert_header(Range::Bytes(vec![
53///         ByteRangeSpec::FromTo(1, 100),
54///         ByteRangeSpec::From(200),
55///     ]))
56///     .insert_header(Range::Unregistered("letters".to_owned(), "a-f".to_owned()))
57///     .insert_header(Range::bytes(1, 100))
58///     .insert_header(Range::bytes_multi(vec![(1, 100), (200, 300)]))
59///     .to_http_request();
60/// # let _ = req;
61/// ```
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum Range {
64    /// Byte range.
65    Bytes(Vec<ByteRangeSpec>),
66
67    /// Custom range, with unit not registered at IANA.
68    ///
69    /// (`other-range-unit`: String , `other-range-set`: String)
70    Unregistered(String, String),
71}
72
73/// A range of bytes to fetch.
74///
75/// Each [`Range::Bytes`] header can contain one or more `ByteRangeSpec`s.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum ByteRangeSpec {
78    /// All bytes from `x` to `y`, inclusive.
79    ///
80    /// Serialized as `x-y`.
81    ///
82    /// Example: `bytes=500-999` would represent the second 500 bytes.
83    FromTo(u64, u64),
84
85    /// All bytes starting from `x`, inclusive.
86    ///
87    /// Serialized as `x-`.
88    ///
89    /// Example: For a file of 1000 bytes, `bytes=950-` would represent bytes 950-999, inclusive.
90    From(u64),
91
92    /// The last `y` bytes, inclusive.
93    ///
94    /// Using the spec terminology, this is `suffix-byte-range-spec`. Serialized as `-y`.
95    ///
96    /// Example: For a file of 1000 bytes, `bytes=-50` is equivalent to `bytes=950-`.
97    Last(u64),
98}
99
100impl_more::impl_display_enum! {
101    ByteRangeSpec:
102    FromTo(from, to) => "{from}-{to}",
103    Last(pos) => "-{pos}",
104    From(pos) => "{pos}-",
105}
106
107impl ByteRangeSpec {
108    /// Given the full length of the entity, attempt to normalize the byte range into an satisfiable
109    /// end-inclusive `(from, to)` range.
110    ///
111    /// The resulting range is guaranteed to be a satisfiable range within the bounds
112    /// of `0 <= from <= to < full_length`.
113    ///
114    /// If the byte range is deemed unsatisfiable, `None` is returned. An unsatisfiable range is
115    /// generally cause for a server to either reject the client request with a
116    /// `416 Range Not Satisfiable` status code, or to simply ignore the range header and serve the
117    /// full entity using a `200 OK` status code.
118    ///
119    /// This function closely follows [RFC 7233 §2.1]. As such, it considers ranges to be
120    /// satisfiable if they meet the following conditions:
121    ///
122    /// > If a valid byte-range-set includes at least one byte-range-spec with a first-byte-pos that
123    /// > is less than the current length of the representation, or at least one
124    /// > suffix-byte-range-spec with a non-zero suffix-length, then the byte-range-set is
125    /// > satisfiable. Otherwise, the byte-range-set is unsatisfiable.
126    ///
127    /// The function also computes remainder ranges based on the RFC:
128    ///
129    /// > If the last-byte-pos value is absent, or if the value is greater than or equal to the
130    /// > current length of the representation data, the byte range is interpreted as the remainder
131    /// > of the representation (i.e., the server replaces the value of last-byte-pos with a value
132    /// > that is one less than the current length of the selected representation).
133    ///
134    /// [RFC 7233 §2.1]: https://www.rfc-editor.org/info/rfc7233/#section-2.1
135    pub fn to_satisfiable_range(&self, full_length: u64) -> Option<(u64, u64)> {
136        // If the full length is zero, there is no satisfiable end-inclusive range.
137        if full_length == 0 {
138            return None;
139        }
140
141        match *self {
142            ByteRangeSpec::FromTo(from, to) => {
143                if from < full_length && from <= to {
144                    Some((from, cmp::min(to, full_length - 1)))
145                } else {
146                    None
147                }
148            }
149
150            ByteRangeSpec::From(from) => {
151                if from < full_length {
152                    Some((from, full_length - 1))
153                } else {
154                    None
155                }
156            }
157
158            ByteRangeSpec::Last(last) => {
159                if last > 0 {
160                    // From the RFC: If the selected representation is shorter than the specified
161                    // suffix-length, the entire representation is used.
162                    if last > full_length {
163                        Some((0, full_length - 1))
164                    } else {
165                        Some((full_length - last, full_length - 1))
166                    }
167                } else {
168                    None
169                }
170            }
171        }
172    }
173}
174
175impl Range {
176    /// Constructs a common byte range header.
177    ///
178    /// Eg: `bytes=from-to`
179    pub fn bytes(from: u64, to: u64) -> Range {
180        Range::Bytes(vec![ByteRangeSpec::FromTo(from, to)])
181    }
182
183    /// Constructs a byte range header with multiple subranges.
184    ///
185    /// Eg: `bytes=from1-to1,from2-to2,fromX-toX`
186    pub fn bytes_multi(ranges: Vec<(u64, u64)>) -> Range {
187        Range::Bytes(
188            ranges
189                .into_iter()
190                .map(|(from, to)| ByteRangeSpec::FromTo(from, to))
191                .collect(),
192        )
193    }
194}
195
196impl fmt::Display for Range {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        match self {
199            Range::Bytes(ranges) => {
200                write!(f, "bytes=")?;
201
202                for (i, range) in ranges.iter().enumerate() {
203                    if i != 0 {
204                        f.write_str(",")?;
205                    }
206
207                    Display::fmt(range, f)?;
208                }
209                Ok(())
210            }
211
212            Range::Unregistered(unit, range_str) => {
213                write!(f, "{}={}", unit, range_str)
214            }
215        }
216    }
217}
218
219impl FromStr for Range {
220    type Err = ParseError;
221
222    fn from_str(s: &str) -> Result<Range, ParseError> {
223        let (unit, val) = s.split_once('=').ok_or(ParseError::Header)?;
224
225        match (unit, val) {
226            ("bytes", ranges) => {
227                let ranges = from_comma_delimited(ranges);
228
229                if ranges.is_empty() {
230                    return Err(ParseError::Header);
231                }
232
233                Ok(Range::Bytes(ranges))
234            }
235
236            (_, "") => Err(ParseError::Header),
237            ("", _) => Err(ParseError::Header),
238
239            (unit, range_str) => Ok(Range::Unregistered(unit.to_owned(), range_str.to_owned())),
240        }
241    }
242}
243
244impl FromStr for ByteRangeSpec {
245    type Err = ParseError;
246
247    fn from_str(s: &str) -> Result<ByteRangeSpec, ParseError> {
248        let (start, end) = s.split_once('-').ok_or(ParseError::Header)?;
249
250        match (start, end) {
251            ("", end) => end
252                .parse()
253                .or(Err(ParseError::Header))
254                .map(ByteRangeSpec::Last),
255
256            (start, "") => start
257                .parse()
258                .or(Err(ParseError::Header))
259                .map(ByteRangeSpec::From),
260
261            (start, end) => match (start.parse(), end.parse()) {
262                (Ok(start), Ok(end)) if start <= end => Ok(ByteRangeSpec::FromTo(start, end)),
263                _ => Err(ParseError::Header),
264            },
265        }
266    }
267}
268
269impl Header for Range {
270    fn name() -> HeaderName {
271        header::RANGE
272    }
273
274    #[inline]
275    fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError> {
276        header::from_one_raw_str(msg.headers().get(Self::name()))
277    }
278}
279
280impl TryIntoHeaderValue for Range {
281    type Error = InvalidHeaderValue;
282
283    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
284        let mut wrt = Writer::new();
285        let _ = write!(wrt, "{}", self);
286        HeaderValue::from_maybe_shared(wrt.take())
287    }
288}
289
290/// Parses 0 or more items out of a comma delimited string, ignoring invalid items.
291fn from_comma_delimited<T: FromStr>(s: &str) -> Vec<T> {
292    s.split(',')
293        .filter_map(|x| match x.trim() {
294            "" => None,
295            y => Some(y),
296        })
297        .filter_map(|x| x.parse().ok())
298        .collect()
299}
300
301#[cfg(test)]
302mod tests {
303    use actix_http::{test::TestRequest, Request};
304
305    use super::*;
306
307    fn req(s: &str) -> Request {
308        TestRequest::default()
309            .insert_header((header::RANGE, s))
310            .finish()
311    }
312
313    #[test]
314    fn test_parse_bytes_range_valid() {
315        let r: Range = Header::parse(&req("bytes=1-100")).unwrap();
316        let r2: Range = Header::parse(&req("bytes=1-100,-")).unwrap();
317        let r3 = Range::bytes(1, 100);
318        assert_eq!(r, r2);
319        assert_eq!(r2, r3);
320
321        let r: Range = Header::parse(&req("bytes=1-100,200-")).unwrap();
322        let r2: Range = Header::parse(&req("bytes= 1-100 , 101-xxx,  200- ")).unwrap();
323        let r3 = Range::Bytes(vec![
324            ByteRangeSpec::FromTo(1, 100),
325            ByteRangeSpec::From(200),
326        ]);
327        assert_eq!(r, r2);
328        assert_eq!(r2, r3);
329
330        let r: Range = Header::parse(&req("bytes=1-100,-100")).unwrap();
331        let r2: Range = Header::parse(&req("bytes=1-100, ,,-100")).unwrap();
332        let r3 = Range::Bytes(vec![
333            ByteRangeSpec::FromTo(1, 100),
334            ByteRangeSpec::Last(100),
335        ]);
336        assert_eq!(r, r2);
337        assert_eq!(r2, r3);
338
339        let r: Range = Header::parse(&req("custom=1-100,-100")).unwrap();
340        let r2 = Range::Unregistered("custom".to_owned(), "1-100,-100".to_owned());
341        assert_eq!(r, r2);
342    }
343
344    #[test]
345    fn test_parse_unregistered_range_valid() {
346        let r: Range = Header::parse(&req("custom=1-100,-100")).unwrap();
347        let r2 = Range::Unregistered("custom".to_owned(), "1-100,-100".to_owned());
348        assert_eq!(r, r2);
349
350        let r: Range = Header::parse(&req("custom=abcd")).unwrap();
351        let r2 = Range::Unregistered("custom".to_owned(), "abcd".to_owned());
352        assert_eq!(r, r2);
353
354        let r: Range = Header::parse(&req("custom=xxx-yyy")).unwrap();
355        let r2 = Range::Unregistered("custom".to_owned(), "xxx-yyy".to_owned());
356        assert_eq!(r, r2);
357    }
358
359    #[test]
360    fn test_parse_invalid() {
361        let r: Result<Range, ParseError> = Header::parse(&req("bytes=1-a,-"));
362        assert_eq!(r.ok(), None);
363
364        let r: Result<Range, ParseError> = Header::parse(&req("bytes=1-2-3"));
365        assert_eq!(r.ok(), None);
366
367        let r: Result<Range, ParseError> = Header::parse(&req("abc"));
368        assert_eq!(r.ok(), None);
369
370        let r: Result<Range, ParseError> = Header::parse(&req("bytes=1-100="));
371        assert_eq!(r.ok(), None);
372
373        let r: Result<Range, ParseError> = Header::parse(&req("bytes="));
374        assert_eq!(r.ok(), None);
375
376        let r: Result<Range, ParseError> = Header::parse(&req("custom="));
377        assert_eq!(r.ok(), None);
378
379        let r: Result<Range, ParseError> = Header::parse(&req("=1-100"));
380        assert_eq!(r.ok(), None);
381    }
382
383    #[test]
384    fn test_fmt() {
385        let range = Range::Bytes(vec![
386            ByteRangeSpec::FromTo(0, 1000),
387            ByteRangeSpec::From(2000),
388        ]);
389        assert_eq!(&range.to_string(), "bytes=0-1000,2000-");
390
391        let range = Range::Bytes(vec![]);
392
393        assert_eq!(&range.to_string(), "bytes=");
394
395        let range = Range::Unregistered("custom".to_owned(), "1-xxx".to_owned());
396
397        assert_eq!(&range.to_string(), "custom=1-xxx");
398    }
399
400    #[test]
401    fn test_byte_range_spec_to_satisfiable_range() {
402        assert_eq!(
403            Some((0, 0)),
404            ByteRangeSpec::FromTo(0, 0).to_satisfiable_range(3)
405        );
406        assert_eq!(
407            Some((1, 2)),
408            ByteRangeSpec::FromTo(1, 2).to_satisfiable_range(3)
409        );
410        assert_eq!(
411            Some((1, 2)),
412            ByteRangeSpec::FromTo(1, 5).to_satisfiable_range(3)
413        );
414        assert_eq!(None, ByteRangeSpec::FromTo(3, 3).to_satisfiable_range(3));
415        assert_eq!(None, ByteRangeSpec::FromTo(2, 1).to_satisfiable_range(3));
416        assert_eq!(None, ByteRangeSpec::FromTo(0, 0).to_satisfiable_range(0));
417
418        assert_eq!(Some((0, 2)), ByteRangeSpec::From(0).to_satisfiable_range(3));
419        assert_eq!(Some((2, 2)), ByteRangeSpec::From(2).to_satisfiable_range(3));
420        assert_eq!(None, ByteRangeSpec::From(3).to_satisfiable_range(3));
421        assert_eq!(None, ByteRangeSpec::From(5).to_satisfiable_range(3));
422        assert_eq!(None, ByteRangeSpec::From(0).to_satisfiable_range(0));
423
424        assert_eq!(Some((1, 2)), ByteRangeSpec::Last(2).to_satisfiable_range(3));
425        assert_eq!(Some((2, 2)), ByteRangeSpec::Last(1).to_satisfiable_range(3));
426        assert_eq!(Some((0, 2)), ByteRangeSpec::Last(5).to_satisfiable_range(3));
427        assert_eq!(None, ByteRangeSpec::Last(0).to_satisfiable_range(3));
428        assert_eq!(None, ByteRangeSpec::Last(2).to_satisfiable_range(0));
429    }
430}