|
| 1 | +use std::fmt::{self, Write}; |
| 2 | +use std::str::FromStr; |
| 3 | + |
| 4 | +/// <https://mimesniff.spec.whatwg.org/#mime-type-representation> |
| 5 | +#[derive(Debug, PartialEq, Eq)] |
| 6 | +pub struct Mime { |
| 7 | + pub type_: String, |
| 8 | + pub subtype: String, |
| 9 | + /// (name, value) |
| 10 | + pub parameters: Vec<(String, String)> |
| 11 | +} |
| 12 | + |
| 13 | +#[derive(Debug)] |
| 14 | +pub struct MimeParsingError(()); |
| 15 | + |
| 16 | +/// <https://mimesniff.spec.whatwg.org/#parsing-a-mime-type> |
| 17 | +impl FromStr for Mime { |
| 18 | + type Err = MimeParsingError; |
| 19 | + |
| 20 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 21 | + parse(s).ok_or(MimeParsingError(())) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +fn parse(s: &str) -> Option<Mime> { |
| 26 | + let trimmed = s.trim_matches(ascii_whitespace); |
| 27 | + |
| 28 | + let (type_, rest) = split2(trimmed, '/'); |
| 29 | + require!(only_http_token_code_points(type_) && !type_.is_empty()); |
| 30 | + |
| 31 | + let (subtype, rest) = split2(rest?, ';'); |
| 32 | + let subtype = subtype.trim_right_matches(ascii_whitespace); |
| 33 | + require!(only_http_token_code_points(subtype) && !subtype.is_empty()); |
| 34 | + |
| 35 | + let mut parameters = Vec::new(); |
| 36 | + if let Some(rest) = rest { |
| 37 | + parse_parameters(rest, &mut parameters) |
| 38 | + } |
| 39 | + |
| 40 | + Some(Mime { |
| 41 | + type_: type_.to_ascii_lowercase(), |
| 42 | + subtype: subtype.to_ascii_lowercase(), |
| 43 | + parameters, |
| 44 | + }) |
| 45 | +} |
| 46 | + |
| 47 | +fn split2(s: &str, separator: char) -> (&str, Option<&str>) { |
| 48 | + let mut iter = s.splitn(2, separator); |
| 49 | + let first = iter.next().unwrap(); |
| 50 | + (first, iter.next()) |
| 51 | +} |
| 52 | + |
| 53 | +fn parse_parameters(s: &str, parameters: &mut Vec<(String, String)>) { |
| 54 | + let mut semicolon_separated = s.split(';'); |
| 55 | + |
| 56 | + while let Some(piece) = semicolon_separated.next() { |
| 57 | + let piece = piece.trim_left_matches(ascii_whitespace); |
| 58 | + let (name, value) = split2(piece, '='); |
| 59 | + if name.is_empty() || !only_http_token_code_points(name) || contains(¶meters, name) { |
| 60 | + continue |
| 61 | + } |
| 62 | + if let Some(value) = value { |
| 63 | + let value = if value.starts_with('"') { |
| 64 | + let max_len = value.len().saturating_sub(2); // without start or end quotes |
| 65 | + let mut unescaped_value = String::with_capacity(max_len); |
| 66 | + let mut chars = value[1..].chars(); |
| 67 | + 'until_closing_quote: loop { |
| 68 | + while let Some(c) = chars.next() { |
| 69 | + match c { |
| 70 | + '"' => break 'until_closing_quote, |
| 71 | + '\\' => unescaped_value.push(chars.next().unwrap_or('\\')), |
| 72 | + _ => unescaped_value.push(c) |
| 73 | + } |
| 74 | + } |
| 75 | + if let Some(piece) = semicolon_separated.next() { |
| 76 | + // A semicolon inside a quoted value is not a separator |
| 77 | + // for the next parameter, but part of the value. |
| 78 | + unescaped_value.push(';'); |
| 79 | + chars = piece.chars() |
| 80 | + } else { |
| 81 | + break |
| 82 | + } |
| 83 | + } |
| 84 | + if !valid_value(&unescaped_value) { |
| 85 | + continue |
| 86 | + } |
| 87 | + unescaped_value |
| 88 | + } else { |
| 89 | + let value = value.trim_right_matches(ascii_whitespace); |
| 90 | + if !valid_value(value) { |
| 91 | + continue |
| 92 | + } |
| 93 | + value.to_owned() |
| 94 | + }; |
| 95 | + parameters.push((name.to_ascii_lowercase(), value)) |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +fn contains(parameters: &[(String, String)], name: &str) -> bool { |
| 101 | + parameters.iter().any(|&(ref n, _)| n == name) |
| 102 | +} |
| 103 | + |
| 104 | +fn valid_value(s: &str) -> bool { |
| 105 | + s.chars().all(|c| { |
| 106 | + // <https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point> |
| 107 | + matches!(c, '\t' | ' '...'~' | '\u{80}'...'\u{FF}') |
| 108 | + }) && !s.is_empty() |
| 109 | +} |
| 110 | + |
| 111 | +/// <https://mimesniff.spec.whatwg.org/#serializing-a-mime-type> |
| 112 | +impl fmt::Display for Mime { |
| 113 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 114 | + f.write_str(&self.type_)?; |
| 115 | + f.write_str("/")?; |
| 116 | + f.write_str(&self.subtype)?; |
| 117 | + for &(ref name, ref value) in &self.parameters { |
| 118 | + f.write_str(";")?; |
| 119 | + f.write_str(name)?; |
| 120 | + f.write_str("=")?; |
| 121 | + if only_http_token_code_points(value) { |
| 122 | + f.write_str(value)? |
| 123 | + } else { |
| 124 | + f.write_str("\"")?; |
| 125 | + for c in value.chars() { |
| 126 | + if c == '"' || c == '\\' { |
| 127 | + f.write_str("\\")? |
| 128 | + } |
| 129 | + f.write_char(c)? |
| 130 | + } |
| 131 | + f.write_str("\"")? |
| 132 | + } |
| 133 | + } |
| 134 | + Ok(()) |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +fn ascii_whitespace(c: char) -> bool { |
| 139 | + matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0C') |
| 140 | +} |
| 141 | + |
| 142 | +fn only_http_token_code_points(s: &str) -> bool { |
| 143 | + s.bytes().all(|byte| IS_HTTP_TOKEN[byte as usize]) |
| 144 | +} |
| 145 | + |
| 146 | +macro_rules! byte_map { |
| 147 | + ($($flag:expr,)*) => ([ |
| 148 | + $($flag != 0,)* |
| 149 | + ]) |
| 150 | +} |
| 151 | + |
| 152 | +// Copied from https://github.com/hyperium/mime/blob/v0.3.5/src/parse.rs#L293 |
| 153 | +static IS_HTTP_TOKEN: [bool; 256] = byte_map![ |
| 154 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 155 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 156 | + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, |
| 157 | + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, |
| 158 | + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 159 | + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, |
| 160 | + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 161 | + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, |
| 162 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 163 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 164 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 165 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 166 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 167 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 168 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 169 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 170 | +]; |
0 commit comments