Skip to main content

mime/
parse.rs

1#[allow(unused, deprecated)]
2use std::ascii::AsciiExt;
3use std::error::Error;
4use std::fmt;
5use std::iter::Enumerate;
6use std::str::Bytes;
7
8use super::{Indexed, Mime, MimeIter, ParamSource, Source, CHARSET, UTF_8};
9
10#[derive(Debug)]
11pub enum ParseError {
12    MissingSlash,
13    MissingEqual,
14    MissingQuote,
15    InvalidToken { pos: usize, byte: u8 },
16}
17
18impl ParseError {
19    fn s(&self) -> &str {
20        use self::ParseError::*;
21
22        match *self {
23            MissingSlash => "a slash (/) was missing between the type and subtype",
24            MissingEqual => "an equals sign (=) was missing between a parameter and its value",
25            MissingQuote => "a quote (\") was missing from a parameter value",
26            InvalidToken { .. } => "an invalid token was encountered",
27        }
28    }
29}
30
31impl fmt::Display for ParseError {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        if let ParseError::InvalidToken { pos, byte } = *self {
34            write!(f, "{}, {:X} at position {}", self.s(), byte, pos)
35        } else {
36            f.write_str(self.s())
37        }
38    }
39}
40
41impl Error for ParseError {
42    // Minimum Rust is 1.15, Error::description was still required then
43    #[allow(deprecated)]
44    fn description(&self) -> &str {
45        self.s()
46    }
47}
48
49impl<'a> MimeIter<'a> {
50    /// A new iterator over mimes or media types
51    pub fn new(s: &'a str) -> Self {
52        Self { pos: 0, source: s }
53    }
54}
55
56impl<'a> Iterator for MimeIter<'a> {
57    type Item = Result<Mime, &'a str>;
58
59    fn next(&mut self) -> Option<Self::Item> {
60        loop {
61            let start = self.pos;
62            let len = self.source.len();
63
64            if start >= len {
65                return None;
66            }
67
68            match parse(&self.source[start..]) {
69                Ok(value) => {
70                    self.pos = len;
71                    return Some(Ok(value));
72                }
73                Err(ParseError::InvalidToken { pos, .. }) => {
74                    // The parser rejects non-ASCII bytes at the start of a
75                    // character. Skip the entire character, not just one byte.
76                    let invalid = start + pos;
77                    let next = invalid + self.source[invalid..].chars().next().unwrap().len_utf8();
78                    if pos == 0 {
79                        self.pos = next;
80                        continue;
81                    }
82                    let slice = &self.source[start..invalid];
83                    return match parse(slice) {
84                        Ok(mime) => {
85                            self.pos = next;
86                            Some(Ok(mime))
87                        }
88                        Err(_) => {
89                            self.pos = invalid;
90                            Some(Err(slice))
91                        }
92                    };
93                }
94                // No invalid character was found; the input is incomplete.
95                Err(_) => {
96                    self.pos = len;
97                    return None;
98                }
99            }
100        }
101    }
102}
103
104pub fn parse(s: &str) -> Result<Mime, ParseError> {
105    if s == "*/*" {
106        return Ok(::STAR_STAR);
107    }
108
109    let mut iter = s.bytes().enumerate();
110    // toplevel
111    let mut start;
112    let slash;
113    loop {
114        match iter.next() {
115            Some((_, c)) if is_token(c) => (),
116            Some((i, b'/')) if i > 0 => {
117                slash = i;
118                start = i + 1;
119                break;
120            }
121            None => return Err(ParseError::MissingSlash), // EOF and no toplevel is no Mime
122            Some((pos, byte)) => {
123                return Err(ParseError::InvalidToken {
124                    pos: pos,
125                    byte: byte,
126                })
127            }
128        };
129    }
130
131    // sublevel
132    let mut plus = None;
133    loop {
134        match iter.next() {
135            Some((i, b'+')) if i > start => {
136                plus = Some(i);
137            }
138            Some((i, b';')) if i > start => {
139                start = i;
140                break;
141            }
142            Some((_, c)) if is_token(c) => (),
143            None => {
144                return Ok(Mime {
145                    source: Source::Dynamic(s.to_ascii_lowercase()),
146                    slash: slash,
147                    plus: plus,
148                    params: ParamSource::None,
149                });
150            }
151            Some((pos, byte)) => {
152                return Err(ParseError::InvalidToken {
153                    pos: pos,
154                    byte: byte,
155                })
156            }
157        };
158    }
159
160    // params
161    let params = params_from_str(s, &mut iter, start)?;
162
163    let src = match params {
164        ParamSource::Utf8(_) => s.to_ascii_lowercase(),
165        ParamSource::Custom(semicolon, ref indices) => {
166            lower_ascii_with_params(s, semicolon, indices)
167        }
168        ParamSource::None => {
169            // Chop off the empty list
170            s[..start].to_ascii_lowercase()
171        }
172    };
173
174    Ok(Mime {
175        source: Source::Dynamic(src),
176        slash: slash,
177        plus: plus,
178        params: params,
179    })
180}
181
182fn params_from_str(
183    s: &str,
184    iter: &mut Enumerate<Bytes>,
185    mut start: usize,
186) -> Result<ParamSource, ParseError> {
187    let semicolon = start;
188    start += 1;
189    let mut params = ParamSource::None;
190    'params: while start < s.len() {
191        let name;
192        // name
193        'name: loop {
194            match iter.next() {
195                Some((i, b' ')) if i == start => {
196                    start = i + 1;
197                    continue 'params;
198                }
199                Some((_, c)) if is_token(c) => (),
200                Some((i, b'=')) if i > start => {
201                    name = Indexed(start, i);
202                    start = i + 1;
203                    break 'name;
204                }
205                None => return Err(ParseError::MissingEqual),
206                Some((pos, byte)) => {
207                    return Err(ParseError::InvalidToken {
208                        pos: pos,
209                        byte: byte,
210                    })
211                }
212            }
213        }
214
215        let value;
216        // values must be restrict-name-char or "anything goes"
217        let mut is_quoted = false;
218
219        'value: loop {
220            if is_quoted {
221                match iter.next() {
222                    Some((i, b'"')) if i > start => {
223                        value = Indexed(start, i);
224                        break 'value;
225                    }
226                    Some((_, c)) if is_restricted_quoted_char(c) => (),
227                    None => return Err(ParseError::MissingQuote),
228                    Some((pos, byte)) => {
229                        return Err(ParseError::InvalidToken {
230                            pos: pos,
231                            byte: byte,
232                        })
233                    }
234                }
235            } else {
236                match iter.next() {
237                    Some((i, b'"')) if i == start => {
238                        is_quoted = true;
239                        start = i + 1;
240                    }
241                    Some((_, c)) if is_token(c) => (),
242                    Some((i, b';')) if i > start => {
243                        value = Indexed(start, i);
244                        start = i + 1;
245                        break 'value;
246                    }
247                    None => {
248                        value = Indexed(start, s.len());
249                        start = s.len();
250                        break 'value;
251                    }
252
253                    Some((pos, byte)) => {
254                        return Err(ParseError::InvalidToken {
255                            pos: pos,
256                            byte: byte,
257                        })
258                    }
259                }
260            }
261        }
262
263        if is_quoted {
264            'ws: loop {
265                match iter.next() {
266                    Some((i, b';')) => {
267                        // next param
268                        start = i + 1;
269                        break 'ws;
270                    }
271                    Some((_, b' ')) => {
272                        // skip whitespace
273                    }
274                    None => {
275                        // eof
276                        start = s.len();
277                        break 'ws;
278                    }
279                    Some((pos, byte)) => {
280                        return Err(ParseError::InvalidToken {
281                            pos: pos,
282                            byte: byte,
283                        })
284                    }
285                }
286            }
287        }
288
289        match params {
290            ParamSource::Utf8(i) => {
291                let i = i + 2;
292                let charset = Indexed(i, "charset".len() + i);
293                let utf8 = Indexed(charset.1 + 1, charset.1 + "utf-8".len() + 1);
294                params = ParamSource::Custom(semicolon, vec![(charset, utf8), (name, value)]);
295            }
296            ParamSource::Custom(_, ref mut vec) => {
297                vec.push((name, value));
298            }
299            ParamSource::None => {
300                if semicolon + 2 == name.0 && CHARSET == &s[name.0..name.1] {
301                    // The compact form reconstructs fixed, unquoted offsets
302                    // if another parameter follows. Quotes change those offsets.
303                    if !is_quoted && UTF_8 == &s[value.0..value.1] {
304                        params = ParamSource::Utf8(semicolon);
305                        continue 'params;
306                    }
307                }
308                params = ParamSource::Custom(semicolon, vec![(name, value)]);
309            }
310        }
311    }
312    Ok(params)
313}
314
315fn lower_ascii_with_params(s: &str, semi: usize, params: &[(Indexed, Indexed)]) -> String {
316    let mut owned = s.to_owned();
317    owned[..semi].make_ascii_lowercase();
318
319    for &(ref name, ref value) in params {
320        owned[name.0..name.1].make_ascii_lowercase();
321        // Since we just converted this part of the string to lowercase,
322        // we can skip the `Name == &str` unicase check and do a faster
323        // memcmp instead.
324        if &owned[name.0..name.1] == CHARSET.source {
325            owned[value.0..value.1].make_ascii_lowercase();
326        }
327    }
328
329    owned
330}
331
332// From [RFC6838](http://tools.ietf.org/html/rfc6838#section-4.2):
333//
334// > All registered media types MUST be assigned top-level type and
335// > subtype names.  The combination of these names serves to uniquely
336// > identify the media type, and the subtype name facet (or the absence
337// > of one) identifies the registration tree.  Both top-level type and
338// > subtype names are case-insensitive.
339// >
340// > Type and subtype names MUST conform to the following ABNF:
341// >
342// >     type-name = restricted-name
343// >     subtype-name = restricted-name
344// >
345// >     restricted-name = restricted-name-first *126restricted-name-chars
346// >     restricted-name-first  = ALPHA / DIGIT
347// >     restricted-name-chars  = ALPHA / DIGIT / "!" / "#" /
348// >                              "$" / "&" / "-" / "^" / "_"
349// >     restricted-name-chars =/ "." ; Characters before first dot always
350// >                                  ; specify a facet name
351// >     restricted-name-chars =/ "+" ; Characters after last plus always
352// >                                  ; specify a structured syntax suffix
353
354// However, [HTTP](https://tools.ietf.org/html/rfc7231#section-3.1.1.1):
355//
356// >     media-type = type "/" subtype *( OWS ";" OWS parameter )
357// >     type       = token
358// >     subtype    = token
359// >     parameter  = token "=" ( token / quoted-string )
360//
361// Where token is defined as:
362//
363// >     token = 1*tchar
364// >     tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
365// >        "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
366//
367// So, clearly, ¯\_(Ä_/¯
368
369macro_rules! byte_map {
370    ($($flag:expr,)*) => ([
371        $($flag != 0,)*
372    ])
373}
374
375static TOKEN_MAP: [bool; 256] = byte_map![
376    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
377    0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
378    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
379    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0,
380    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
381    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
382    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
383    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
384];
385
386fn is_token(c: u8) -> bool {
387    TOKEN_MAP[c as usize]
388}
389
390fn is_restricted_quoted_char(c: u8) -> bool {
391    c > 31 && c != 127
392}
393
394#[test]
395#[allow(warnings)] // ... ranges deprecated
396fn test_lookup_tables() {
397    for (i, &valid) in TOKEN_MAP.iter().enumerate() {
398        let i = i as u8;
399        let should = match i {
400            b'a'...b'z'
401            | b'A'...b'Z'
402            | b'0'...b'9'
403            | b'!'
404            | b'#'
405            | b'$'
406            | b'%'
407            | b'&'
408            | b'\''
409            | b'*'
410            | b'+'
411            | b'-'
412            | b'.'
413            | b'^'
414            | b'_'
415            | b'`'
416            | b'|'
417            | b'~' => true,
418            _ => false,
419        };
420        assert_eq!(
421            valid, should,
422            "{:?} ({}) should be {}",
423            i as char, i, should
424        );
425    }
426}
427
428#[test]
429fn test_parse_iterator() {
430    let mut iter = MimeIter::new("application/json, application/json");
431    assert_eq!(
432        iter.next().unwrap().unwrap(),
433        parse("application/json").unwrap()
434    );
435    assert_eq!(
436        iter.next().unwrap().unwrap(),
437        parse("application/json").unwrap()
438    );
439    assert_eq!(iter.next(), None);
440
441    let mut iter = MimeIter::new("application/json");
442    assert_eq!(
443        iter.next().unwrap().unwrap(),
444        parse("application/json").unwrap()
445    );
446    assert_eq!(iter.next(), None);
447
448    let mut iter = MimeIter::new("application/json;  ");
449    assert_eq!(
450        iter.next().unwrap().unwrap(),
451        parse("application/json").unwrap()
452    );
453    assert_eq!(iter.next(), None);
454}
455
456#[test]
457fn test_parse_iterator_invalid() {
458    let mut iter = MimeIter::new("application/json, invalid, application/json");
459    assert_eq!(
460        iter.next().unwrap().unwrap(),
461        parse("application/json").unwrap()
462    );
463    assert_eq!(iter.next().unwrap().unwrap_err(), "invalid");
464    assert_eq!(
465        iter.next().unwrap().unwrap(),
466        parse("application/json").unwrap()
467    );
468    assert_eq!(iter.next(), None);
469}
470
471#[test]
472fn test_parse_iterator_many_empty_entries() {
473    let mut input = ",".repeat(10_000);
474    assert_eq!(MimeIter::new(&input).next(), None);
475
476    input.push_str("application/json");
477    input.push_str(&", ".repeat(10_000));
478    input.push_str("text/plain");
479    input.push_str(&",".repeat(10_000));
480
481    let mut iter = MimeIter::new(&input);
482    assert_eq!(iter.next().unwrap().unwrap(), ::APPLICATION_JSON);
483    assert_eq!(iter.next().unwrap().unwrap(), ::TEXT_PLAIN);
484    assert_eq!(iter.next(), None);
485    assert_eq!(iter.next(), None);
486}