net_traits/fetch/headers.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::iter::Peekable;
6use std::str::{Chars, FromStr};
7
8use data_url::mime::Mime as DataUrlMime;
9use headers::HeaderMap;
10
11/// <https://fetch.spec.whatwg.org/#http-tab-or-space>
12const HTTP_TAB_OR_SPACE: &[char] = &['\u{0009}', '\u{0020}'];
13
14/// <https://fetch.spec.whatwg.org/#concept-header-list-get>
15pub fn get_value_from_header_list(name: &str, headers: &HeaderMap) -> Option<Vec<u8>> {
16 let values = headers.get_all(name).iter().map(|val| val.as_bytes());
17
18 // Step 1: If list does not contain name, then return null.
19 if values.size_hint() == (0, Some(0)) {
20 return None;
21 }
22
23 // Step 2: Return the values of all headers in list whose name is a byte-case-insensitive match
24 // for name, separated from each other by 0x2C 0x20, in order.
25 Some(values.collect::<Vec<&[u8]>>().join(&[0x2C, 0x20][..]))
26}
27
28/// <https://fetch.spec.whatwg.org/#forbidden-method>
29pub fn is_forbidden_method(method: &[u8]) -> bool {
30 matches!(
31 method.to_ascii_lowercase().as_slice(),
32 b"connect" | b"trace" | b"track"
33 )
34}
35
36/// <https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split>
37pub fn get_decode_and_split_header_name(name: &str, headers: &HeaderMap) -> Option<Vec<String>> {
38 // Step 1: Let value be the result of getting name from list.
39 // Step 2: If value is null, then return null.
40 // Step 3: Return the result of getting, decoding, and splitting value.
41 get_value_from_header_list(name, headers).map(get_decode_and_split_header_value)
42}
43
44/// <https://fetch.spec.whatwg.org/#header-value-get-decode-and-split>
45pub fn get_decode_and_split_header_value(value: Vec<u8>) -> Vec<String> {
46 fn char_is_not_quote_or_comma(c: char) -> bool {
47 c != '\u{0022}' && c != '\u{002C}'
48 }
49
50 // Step 1: Let input be the result of isomorphic decoding value.
51 let input = value.into_iter().map(char::from).collect::<String>();
52
53 // Step 2: Let position be a position variable for input, initially pointing at the start of
54 // input.
55 let mut position = input.chars().peekable();
56
57 // Step 3: Let values be a list of strings, initially « ».
58 let mut values: Vec<String> = vec![];
59
60 // Step 4: Let temporaryValue be the empty string.
61 let mut temporary_value = String::new();
62
63 // Step 5: While true:
64 while position.peek().is_some() {
65 // Step 5.1: Append the result of collecting a sequence of code points that are not U+0022
66 // (") or U+002C (,) from input, given position, to temporaryValue.
67 temporary_value += &*collect_sequence(&mut position, char_is_not_quote_or_comma);
68
69 // Step 5.2: If position is not past the end of input and the code point at position within
70 // input is U+0022 ("):
71 if let Some(&ch) = position.peek() {
72 if ch == '\u{0022}' {
73 // Step 5.2.1: Append the result of collecting an HTTP quoted string from input,
74 // given position, to temporaryValue.
75 temporary_value += &*collect_http_quoted_string(&mut position, false);
76
77 // Step 5.2.2: If position is not past the end of input, then continue.
78 if position.peek().is_some() {
79 continue;
80 }
81 } else {
82 // Step 5.2.2: If position is not past the end of input, then continue.
83 position.next();
84 }
85 }
86
87 // Step 5.3: Remove all HTTP tab or space from the start and end of temporaryValue.
88 temporary_value = temporary_value.trim_matches(HTTP_TAB_OR_SPACE).to_string();
89
90 // Step 5.4: Append temporaryValue to values.
91 values.push(temporary_value);
92
93 // Step 5.5: Set temporaryValue to the empty string.
94 temporary_value = String::new();
95 }
96
97 values
98}
99
100/// <https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points>
101fn collect_sequence<F>(position: &mut Peekable<Chars>, condition: F) -> String
102where
103 F: Fn(char) -> bool,
104{
105 // Step 1: Let result be the empty string.
106 let mut result = String::new();
107
108 // Step 2: While position doesn’t point past the end of input and the code point at position
109 // within input meets the condition condition:
110 while let Some(&ch) = position.peek() {
111 if !condition(ch) {
112 break;
113 }
114
115 // Step 2.1: Append that code point to the end of result.
116 result.push(ch);
117
118 // Step 2.2: Advance position by 1.
119 position.next();
120 }
121
122 // Step 3: Return result.
123 result
124}
125
126/// <https://fetch.spec.whatwg.org/#collect-an-http-quoted-string>
127fn collect_http_quoted_string(position: &mut Peekable<Chars>, extract_value: bool) -> String {
128 fn char_is_not_quote_or_backslash(c: char) -> bool {
129 c != '\u{0022}' && c != '\u{005C}'
130 }
131
132 // Step 2: let value be the empty string
133 // We will store the 'extracted value' or the raw value
134 let mut value = String::new();
135
136 // Step 3, 4
137 let should_be_quote = position.next();
138 if let Some(ch) = should_be_quote {
139 if !extract_value {
140 value.push(ch)
141 }
142 }
143
144 // Step 5: While true:
145 loop {
146 // Step 5.1: Append the result of collecting a sequence of code points that are not U+0022
147 // (") or U+005C (\) from input, given position, to value.
148 value += &*collect_sequence(position, char_is_not_quote_or_backslash);
149
150 // Step 5.2: If position is past the end of input, then break.
151 if position.peek().is_none() {
152 break;
153 }
154
155 // Step 5.3: Let quoteOrBackslash be the code point at position within input.
156 // Step 5.4: Advance position by 1.
157 let quote_or_backslash = position.next().unwrap();
158
159 if !extract_value {
160 value.push(quote_or_backslash);
161 }
162
163 // Step 5.5: If quoteOrBackslash is U+005C (\), then:
164 if quote_or_backslash == '\u{005C}' {
165 if let Some(ch) = position.next() {
166 // Step 5.5.2: Append the code point at position within input to value.
167 value.push(ch);
168 } else {
169 // Step 5.5.1: If position is past the end of input, then append U+005C (\) to value and break.
170 if extract_value {
171 value.push('\u{005C}');
172 }
173
174 break;
175 }
176 } else {
177 // Step 5.6.1: Assert quote_or_backslash is a quote
178 assert_eq!(quote_or_backslash, '\u{0022}');
179
180 // Step 5.6.2: break
181 break;
182 }
183 }
184
185 // Step 6, 7
186 value
187}
188
189/// <https://fetch.spec.whatwg.org/#concept-header-extract-mime-type>
190/// This function uses data_url::Mime to parse the MIME Type because
191/// mime::Mime does not provide a parser following the Fetch spec
192/// see <https://github.com/hyperium/mime/issues/106>
193pub fn extract_mime_type_as_dataurl_mime(headers: &HeaderMap) -> Option<DataUrlMime> {
194 // > 1: Let charset be null.
195 let mut charset = None;
196 // > 2: Let essence be null.
197 let mut essence = String::new();
198 // > 3: Let mimeType be null.
199 let mut mime_type = None;
200
201 // > 4: Let values be the result of getting, decoding, and splitting `Content-Type`
202 // from headers.
203 // > 5: If values is null, then return failure.
204 let headers_values = get_decode_and_split_header_name("content-type", headers)?;
205
206 // > 6: For each value of values:
207 for header_value in headers_values.iter() {
208 // > 6.1: Let temporaryMimeType be the result of parsing value.
209 match DataUrlMime::from_str(header_value) {
210 // > 6.2: If temporaryMimeType is failure or its essence is "*/*", then continue.
211 Err(_) => continue,
212 Ok(temp_mime) => {
213 let temp_essence = format!("{}/{}", temp_mime.type_, temp_mime.subtype);
214
215 // > 6.2: If temporaryMimeType is failure or its essence is "*/*", then
216 // continue.
217 if temp_essence == "*/*" {
218 continue;
219 }
220
221 // > 6.3: Set mimeType to temporaryMimeType.
222 mime_type = Some(DataUrlMime {
223 type_: temp_mime.type_.to_string(),
224 subtype: temp_mime.subtype.to_string(),
225 parameters: temp_mime.parameters.clone(),
226 });
227
228 // > 6.4: If mimeType’s essence is not essence, then:
229 let temp_charset = &temp_mime.get_parameter("charset");
230 if temp_essence != essence {
231 // > 6.4.1: Set charset to null.
232 // > 6.4.2: If mimeType’s parameters["charset"] exists, then set
233 // charset to mimeType’s parameters["charset"].
234 charset = temp_charset.map(|c| c.to_string());
235 // > 6.4.3: Set essence to mimeType’s essence.
236 essence = temp_essence.to_owned();
237 } else {
238 // > 6.5: Otherwise, if mimeType’s parameters["charset"] does not exist,
239 // and charset is non-null, set mimeType’s parameters["charset"] to charset.
240 if temp_charset.is_none() && charset.is_some() {
241 let DataUrlMime {
242 type_: t,
243 subtype: st,
244 parameters: p,
245 } = mime_type.unwrap();
246 let mut params = p;
247 params.push(("charset".to_string(), charset.clone().unwrap()));
248 mime_type = Some(DataUrlMime {
249 type_: t.to_string(),
250 subtype: st.to_string(),
251 parameters: params,
252 })
253 }
254 }
255 },
256 }
257 }
258
259 // > 7: If mimeType is null, then return failure.
260 // > 8: Return mimeType.
261 mime_type
262}
263
264pub fn extract_mime_type(headers: &HeaderMap) -> Option<Vec<u8>> {
265 extract_mime_type_as_dataurl_mime(headers).map(|m| format!("{}", m).into_bytes())
266}
267
268pub fn extract_mime_type_as_mime(headers: &HeaderMap) -> Option<mime::Mime> {
269 extract_mime_type_as_dataurl_mime(headers).and_then(|mime: DataUrlMime| {
270 // Try to transform a data-url::mime::Mime into a mime::Mime
271 let mut mime_as_str = format!("{}/{}", mime.type_, mime.subtype);
272 for p in mime.parameters {
273 mime_as_str.push_str(format!("; {}={}", p.0, p.1).as_str());
274 }
275 mime_as_str.parse().ok()
276 })
277}