script/dom/html/document_metadata/processingoptions.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::str::FromStr;
6
7use bytes::{Bytes, BytesMut};
8use cssparser::match_ignore_ascii_case;
9use http::header::HeaderMap;
10use hyper_serde::Serde;
11use mime::Mime;
12use net_traits::fetch::headers::get_decode_and_split_header_name;
13use net_traits::mime_classifier::{MediaType, MimeClassifier};
14use net_traits::policy_container::PolicyContainer;
15use net_traits::request::{
16 CorsSettings, Destination, Initiator, PreloadId, PreloadKey, Referrer, RequestBuilder,
17 RequestClient, RequestId,
18};
19use net_traits::{FetchMetadata, NetworkError, ReferrerPolicy, ResourceFetchTiming};
20pub use nom_rfc8288::complete::LinkDataOwned as LinkHeader;
21use nom_rfc8288::complete::link_lenient as parse_link_header;
22use servo_base::id::WebViewId;
23use servo_url::{ImmutableOrigin, ServoUrl};
24use strum::IntoStaticStr;
25
26use crate::dom::bindings::refcounted::Trusted;
27use crate::dom::bindings::reflector::DomGlobal;
28use crate::dom::bindings::root::DomRoot;
29use crate::dom::csp::{GlobalCspReporting, Violation};
30use crate::dom::document::Document;
31use crate::dom::globalscope::GlobalScope;
32use crate::dom::medialist::MediaList;
33use crate::dom::node::NodeTraits;
34use crate::dom::performance::performanceresourcetiming::InitiatorType;
35use crate::dom::srcset::SourceSet;
36use crate::dom::types::HTMLLinkElement;
37use crate::fetch::fetch::create_a_potential_cors_request;
38use crate::fetch::network_listener::{
39 FetchResponseListener, ResourceTimingListener, submit_timing,
40};
41
42trait ValueForKeyInLinkHeader {
43 fn has_key_in_link_header(&self, key: &str) -> bool;
44 fn value_for_key_in_link_header(&self, key: &str) -> Option<&str>;
45}
46
47impl ValueForKeyInLinkHeader for LinkHeader {
48 fn has_key_in_link_header(&self, key: &str) -> bool {
49 self.params.iter().any(|p| p.key == key)
50 }
51 fn value_for_key_in_link_header(&self, key: &str) -> Option<&str> {
52 let param = self.params.iter().find(|p| p.key == key)?;
53 param.val.as_deref()
54 }
55}
56
57#[derive(PartialEq)]
58pub(crate) enum LinkProcessingPhase {
59 Media,
60 PreMedia,
61}
62
63/// <https://html.spec.whatwg.org/multipage/#link-processing-options>
64#[derive(Debug)]
65pub(crate) struct LinkProcessingOptions {
66 /// <https://html.spec.whatwg.org/multipage/#link-options-href>
67 pub(crate) href: String,
68 /// <https://html.spec.whatwg.org/multipage/#link-options-destination>
69 pub(crate) destination: Destination,
70 /// <https://html.spec.whatwg.org/multipage/#link-options-integrity>
71 pub(crate) integrity: String,
72 /// <https://html.spec.whatwg.org/multipage/#link-options-type>
73 pub(crate) link_type: String,
74 /// <https://html.spec.whatwg.org/multipage/#link-options-nonce>
75 pub(crate) cryptographic_nonce_metadata: String,
76 /// <https://html.spec.whatwg.org/multipage/#link-options-crossorigin>
77 pub(crate) cross_origin: Option<CorsSettings>,
78 /// <https://html.spec.whatwg.org/multipage/#link-options-referrer-policy>
79 pub(crate) referrer_policy: ReferrerPolicy,
80 /// <https://html.spec.whatwg.org/multipage/#link-options-policy-container>
81 pub(crate) policy_container: PolicyContainer,
82 /// <https://html.spec.whatwg.org/multipage/#link-options-source-set>
83 pub(crate) source_set: Option<SourceSet>,
84 /// <https://html.spec.whatwg.org/multipage/#link-options-base-url>
85 pub(crate) base_url: ServoUrl,
86 /// <https://html.spec.whatwg.org/multipage/#link-options-origin>
87 pub(crate) origin: ImmutableOrigin,
88 pub(crate) referrer: Referrer,
89 // https://html.spec.whatwg.org/multipage/#link-options-environment
90 pub(crate) request_client: RequestClient,
91 // https://html.spec.whatwg.org/multipage/#link-options-document
92 // TODO
93 // https://html.spec.whatwg.org/multipage/#link-options-on-document-ready
94 // TODO
95 // https://html.spec.whatwg.org/multipage/#link-options-fetch-priority
96 // TODO
97}
98
99impl LinkProcessingOptions {
100 /// <https://html.spec.whatwg.org/multipage/#apply-link-options-from-parsed-header-attributes>
101 fn apply_link_options_from_parsed_header(
102 &mut self,
103 link_object: &LinkHeader,
104 rel: &str,
105 ) -> bool {
106 // Step 1. If rel is "preload":
107 if rel == "preload" {
108 // Step 1.1. If attribs["as"] does not exist, then return false.
109 let Some(as_) = link_object.value_for_key_in_link_header("as") else {
110 return false;
111 };
112 // Step 1.2. Let destination be the result of translating attribs["as"].
113 let Some(destination) = Self::translate_a_preload_destination(as_) else {
114 // Step 1.3. If destination is null, then return false.
115 return false;
116 };
117 // Step 1.4. Set options's destination to destination.
118 self.destination = destination;
119 }
120 // Step 2. If attribs["crossorigin"] exists and is an ASCII case-insensitive match for one of the
121 // CORS settings attribute keywords, then set options's crossorigin to the CORS settings attribute
122 // state corresponding to that keyword.
123 if let Some(cross_origin) = link_object.value_for_key_in_link_header("crossorigin") {
124 self.cross_origin = determine_cors_settings_for_token(cross_origin);
125 }
126 // Step 3. If attribs["integrity"] exists, then set options's integrity to attribs["integrity"].
127 if let Some(integrity) = link_object.value_for_key_in_link_header("integrity") {
128 self.integrity = integrity.to_owned();
129 }
130 // Step 4. If attribs["referrerpolicy"] exists and is an ASCII case-insensitive match for
131 // some referrer policy, then set options's referrer policy to that referrer policy.
132 if let Some(referrer_policy) = link_object.value_for_key_in_link_header("referrerpolicy") {
133 self.referrer_policy = ReferrerPolicy::from(referrer_policy);
134 }
135 // Step 5. If attribs["nonce"] exists, then set options's nonce to attribs["nonce"].
136 if let Some(nonce) = link_object.value_for_key_in_link_header("nonce") {
137 self.cryptographic_nonce_metadata = nonce.to_owned();
138 }
139 // Step 6. If attribs["type"] exists, then set options's type to attribs["type"].
140 if let Some(link_type) = link_object.value_for_key_in_link_header("type") {
141 self.link_type = link_type.to_owned();
142 }
143 // Step 7. If attribs["fetchpriority"] exists and is an ASCII case-insensitive match
144 // for a fetch priority attribute keyword, then set options's fetch priority to that
145 // fetch priority attribute keyword.
146 // TODO
147 // Step 8. Return true.
148 true
149 }
150
151 /// <https://html.spec.whatwg.org/multipage/#process-a-link-header>
152 fn process_link_header(self, rel: &str, document: &Document) {
153 if rel == "preload" {
154 // https://html.spec.whatwg.org/multipage/#link-type-preload:process-a-link-header
155 // The process a link header step for this type of link given a link processing options options
156 // is to preload options.
157 if !self.type_matches_destination() {
158 return;
159 }
160 self.preload(document.window().webview_id(), None, document);
161 }
162 }
163
164 /// <https://html.spec.whatwg.org/multipage/#translate-a-preload-destination>
165 pub(crate) fn translate_a_preload_destination(
166 potential_destination: &str,
167 ) -> Option<Destination> {
168 // Step 2. Return the result of translating destination.
169 Some(match potential_destination {
170 "fetch" => Destination::None,
171 "font" => Destination::Font,
172 "image" => Destination::Image,
173 "script" => Destination::Script,
174 "style" => Destination::Style,
175 "track" => Destination::Track,
176 // Step 1. If destination is not "fetch", "font", "image",
177 // "script", "style", or "track", then return null.
178 _ => return None,
179 })
180 }
181
182 /// <https://html.spec.whatwg.org/multipage/#create-a-link-request>
183 pub(crate) fn create_link_request(self, webview_id: WebViewId) -> Option<RequestBuilder> {
184 // Step 1. Assert: options's href is not the empty string.
185 assert!(!self.href.is_empty());
186
187 // Step 3. Let url be the result of encoding-parsing a URL given options's href, relative to options's base URL.
188 let Ok(url) = ServoUrl::parse_with_base(Some(&self.base_url), &self.href) else {
189 // Step 4. If url is failure, then return null.
190 return None;
191 };
192
193 // Step 5. Let request be the result of creating a potential-CORS request given
194 // url, options's destination, and options's crossorigin.
195 // Step 6. Set request's policy container to options's policy container.
196 // Step 7. Set request's integrity metadata to options's integrity.
197 // Step 8. Set request's cryptographic nonce metadata to options's cryptographic nonce metadata.
198 // Step 9. Set request's referrer policy to options's referrer policy.
199 // Step 10. Set request's client to options's environment.
200 // FIXME: Step 11. Set request's priority to options's fetch priority.
201 let builder = create_a_potential_cors_request(
202 Some(webview_id),
203 url,
204 self.destination,
205 self.cross_origin,
206 None,
207 self.referrer,
208 )
209 .policy_container(self.policy_container)
210 .client(self.request_client)
211 .initiator(Initiator::Link)
212 .origin(self.origin)
213 .integrity_metadata(self.integrity)
214 .cryptographic_nonce_metadata(self.cryptographic_nonce_metadata)
215 .referrer_policy(self.referrer_policy);
216
217 // Step 12. Return request.
218 Some(builder)
219 }
220
221 /// <https://html.spec.whatwg.org/multipage/#match-preload-type>
222 pub(crate) fn type_matches_destination(&self) -> bool {
223 // Step 1. If type is an empty string, then return true.
224 if self.link_type.is_empty() {
225 return true;
226 }
227 // Step 2. If destination is "fetch", then return true.
228 //
229 // Fetch is handled as an empty string destination in the spec:
230 // https://fetch.spec.whatwg.org/#concept-potential-destination-translate
231 let destination = self.destination;
232 if destination == Destination::None {
233 return true;
234 }
235 // Step 3. Let mimeTypeRecord be the result of parsing type.
236 let Ok(mime_type_record) = Mime::from_str(&self.link_type) else {
237 // Step 4. If mimeTypeRecord is failure, then return false.
238 return false;
239 };
240 // Step 5. If mimeTypeRecord is not supported by the user agent, then return false.
241 //
242 // We currently don't check if we actually support the mime type. Only if we can classify
243 // it according to the spec.
244 let Some(mime_type) = MimeClassifier::get_media_type(&mime_type_record) else {
245 return false;
246 };
247 // Step 6. If any of the following are true:
248 if
249 // destination is "audio" or "video", and mimeTypeRecord is an audio or video MIME type;
250 ((destination == Destination::Audio || destination == Destination::Video) &&
251 mime_type == MediaType::AudioVideo)
252 // destination is a script-like destination and mimeTypeRecord is a JavaScript MIME type;
253 || (destination.is_script_like() && mime_type == MediaType::JavaScript)
254 // destination is "image" and mimeTypeRecord is an image MIME type;
255 || (destination == Destination::Image && mime_type == MediaType::Image)
256 // destination is "font" and mimeTypeRecord is a font MIME type;
257 || (destination == Destination::Font && mime_type == MediaType::Font)
258 // destination is "json" and mimeTypeRecord is a JSON MIME type;
259 || (destination == Destination::Json && mime_type == MediaType::Json)
260 // destination is "style" and mimeTypeRecord's essence is text/css; or
261 || (destination == Destination::Style && mime_type_record == mime::TEXT_CSS)
262 // destination is "track" and mimeTypeRecord's essence is text/vtt,
263 || (destination == Destination::Track && mime_type_record.essence_str() == "text/vtt")
264 {
265 // then return true.
266 return true;
267 }
268 // Step 7. Return false.
269 false
270 }
271
272 /// <https://html.spec.whatwg.org/multipage/#preload>
273 pub(crate) fn preload(
274 mut self,
275 webview_id: WebViewId,
276 link: Option<Trusted<HTMLLinkElement>>,
277 document: &Document,
278 ) {
279 // Step 1. If options's type doesn't match options's destination, then return.
280 //
281 // Handled by callers, since we need to check the previous destination type
282 assert!(self.type_matches_destination());
283 // Step 2. If options's destination is "image" and options's source set is not null,
284 // then set options's href to the result of selecting an image source from options's source set.
285 if self.destination == Destination::Image &&
286 let Some(srcset) = &mut self.source_set
287 {
288 self.href = String::from(
289 srcset
290 .select_image_source_from_source_set(document)
291 .unwrap_or_default()
292 .0,
293 );
294 }
295 // Step 3. Let request be the result of creating a link request given options.
296 let Some(request) = self.create_link_request(webview_id) else {
297 // Step 4. If request is null, then return.
298 return;
299 };
300 let preload_id = PreloadId::default();
301 let request = request.preload_id(preload_id.clone());
302 // Step 5. Let unsafeEndTime be 0.
303 // TODO
304 // Step 6. Let entry be a new preload entry whose integrity metadata is options's integrity.
305 //
306 // This is performed in `CoreResourceManager::fetch`
307 // Step 7. Let key be the result of creating a preload key given request.
308 let key = PreloadKey::new(&request);
309 // Step 8. If options's document is "pending", then set request's initiator type to "early hint".
310 // TODO
311 // Step 9. Let controller be null.
312 // Step 10. Let reportTiming given a Document document be to report timing for controller
313 // given document's relevant global object.
314 let url = request.url.url();
315 let fetch_context = LinkFetchContext {
316 url,
317 link,
318 global: Trusted::new(&document.global()),
319 type_: LinkFetchContextType::Preload,
320 response_body: BytesMut::new(),
321 };
322 document.insert_preloaded_resource(key, preload_id);
323 // Step 11. Set controller to the result of fetching request, with processResponseConsumeBody
324 // set to the following steps given a response response and null, failure, or a byte sequence bodyBytes:
325 document.fetch_background(request, fetch_context);
326 }
327}
328
329pub(crate) fn determine_cors_settings_for_token(token: &str) -> Option<CorsSettings> {
330 match_ignore_ascii_case! { token,
331 "anonymous" => Some(CorsSettings::Anonymous),
332 "use-credentials" => Some(CorsSettings::UseCredentials),
333 _ => None,
334 }
335}
336
337/// <https://html.spec.whatwg.org/multipage/#extract-links-from-headers>
338pub(crate) fn extract_links_from_headers(headers: &Option<Serde<HeaderMap>>) -> Vec<LinkHeader> {
339 // Step 1. Let links be a new list.
340 let mut links = Vec::new();
341 let Some(headers) = headers else {
342 return links;
343 };
344 // Step 2. Let rawLinkHeaders be the result of getting, decoding, and splitting `Link` from headers.
345 let Some(raw_link_headers) = get_decode_and_split_header_name("Link", headers) else {
346 return links;
347 };
348 // Step 3. For each linkHeader of rawLinkHeaders:
349 for link_header in raw_link_headers {
350 // Step 3.1. Let linkObject be the result of parsing linkHeader. [WEBLINK]
351 let Ok(parsed_link_header) = parse_link_header(&link_header) else {
352 continue;
353 };
354 for link_object in parsed_link_header {
355 let Some(link_object) = link_object else {
356 // Step 3.2. If linkObject["target_uri"] does not exist, then continue.
357 continue;
358 };
359 // Step 3.3. Append linkObject to links.
360 links.push(link_object.to_owned());
361 }
362 }
363 // Step 4. Return links.
364 links
365}
366
367/// <https://html.spec.whatwg.org/multipage/#process-link-headers>
368pub(crate) fn process_link_headers(
369 link_headers: &[LinkHeader],
370 document: &Document,
371 phase: LinkProcessingPhase,
372) {
373 let global = document.owner_global();
374 // Step 1. Let links be the result of extracting links from response's header list.
375 //
376 // Already performed once when parsing headers by caller
377 // Step 2. For each linkObject in links:
378 for link_object in link_headers {
379 // Step 2.1. Let rel be linkObject["relation_type"].
380 let Some(rel) = link_object.value_for_key_in_link_header("rel") else {
381 continue;
382 };
383 // Step 2.2. Let attribs be linkObject["target_attributes"].
384 //
385 // Not applicable, that's in `link_object.params`
386 // Step 2.3. Let expectedPhase be "media" if either "srcset", "imagesrcset",
387 // or "media" exist in attribs; otherwise "pre-media".
388 let expected_phase = if link_object.has_key_in_link_header("srcset") ||
389 link_object.has_key_in_link_header("imagesrcset") ||
390 link_object.has_key_in_link_header("media")
391 {
392 LinkProcessingPhase::Media
393 } else {
394 LinkProcessingPhase::PreMedia
395 };
396 // Step 2.4. If expectedPhase is not phase, then continue.
397 if expected_phase != phase {
398 continue;
399 }
400 // Step 2.5. If attribs["media"] exists and attribs["media"] does not match the environment, then continue.
401 if let Some(media) = link_object.value_for_key_in_link_header("media") &&
402 !MediaList::matches_environment(document, media)
403 {
404 continue;
405 }
406 // Step 2.6. Let options be a new link processing options with
407 let mut options = LinkProcessingOptions {
408 href: link_object.url.clone(),
409 destination: Destination::None,
410 integrity: String::new(),
411 link_type: String::new(),
412 cryptographic_nonce_metadata: String::new(),
413 cross_origin: None,
414 referrer_policy: ReferrerPolicy::EmptyString,
415 policy_container: document.policy_container().to_owned(),
416 source_set: None,
417 origin: document.origin().immutable().to_owned(),
418 base_url: document.base_url(),
419 request_client: global.request_client(None),
420 referrer: global.get_referrer(),
421 };
422 // Step 2.7. Apply link options from parsed header attributes to options given attribs and rel.
423 // If that returned false, then return.
424 if !options.apply_link_options_from_parsed_header(link_object, rel) {
425 return;
426 }
427 // Step 2.8. If attribs["imagesrcset"] exists and attribs["imagesizes"] exists,
428 // then set options's source set to the result of creating a source set given
429 // linkObject["target_uri"], attribs["imagesrcset"], attribs["imagesizes"], and null.
430 if let Some(imagesrcset) = link_object.value_for_key_in_link_header("imagesrcset") &&
431 let Some(imagesizes) = link_object.value_for_key_in_link_header("imagesizes")
432 {
433 options.source_set = Some(SourceSet::create_source_set(
434 &link_object.url,
435 imagesrcset,
436 imagesizes,
437 document,
438 ))
439 }
440 // Step 2.9. Run the process a link header steps for rel given options.
441 options.process_link_header(rel, document);
442 }
443}
444
445#[derive(Clone, IntoStaticStr)]
446#[strum(serialize_all = "lowercase")]
447pub(crate) enum LinkFetchContextType {
448 Prefetch,
449 Preload,
450}
451
452impl From<LinkFetchContextType> for InitiatorType {
453 fn from(other: LinkFetchContextType) -> Self {
454 let name: &'static str = other.into();
455 InitiatorType::LocalName(name.to_owned())
456 }
457}
458
459pub(crate) struct LinkFetchContext {
460 /// The `<link>` element (if any) that caused this fetch
461 pub(crate) link: Option<Trusted<HTMLLinkElement>>,
462
463 pub(crate) global: Trusted<GlobalScope>,
464
465 /// The url being prefetched
466 pub(crate) url: ServoUrl,
467
468 /// The type of fetching we perform, used when report timings.
469 pub(crate) type_: LinkFetchContextType,
470
471 pub(crate) response_body: BytesMut,
472}
473
474impl FetchResponseListener for LinkFetchContext {
475 fn process_request_body(&mut self, _: RequestId) {}
476
477 fn process_response(
478 &mut self,
479 _: &mut js::context::JSContext,
480 _: RequestId,
481 fetch_metadata: Result<FetchMetadata, NetworkError>,
482 ) {
483 _ = fetch_metadata;
484 }
485
486 fn process_response_chunk(
487 &mut self,
488 _: &mut js::context::JSContext,
489 _: RequestId,
490 chunk: Bytes,
491 ) {
492 if matches!(self.type_, LinkFetchContextType::Preload) {
493 self.response_body.extend_from_slice(&chunk);
494 }
495 }
496
497 /// Step 7 of <https://html.spec.whatwg.org/multipage/#link-type-prefetch:fetch-and-process-the-linked-resource-2>
498 /// and step 3.1 of <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
499 fn process_response_eof(
500 self,
501 cx: &mut js::context::JSContext,
502 _: RequestId,
503 response_result: Result<(), NetworkError>,
504 timing: ResourceFetchTiming,
505 ) {
506 submit_timing(cx, &self, &response_result, &timing);
507
508 // Step 11.6. If processResponse is given, then call processResponse with response.
509 //
510 // Part of Preload
511 //
512 // Step 6. Let processPrefetchResponse be the following steps given a response response and null, failure, or a byte sequence bytesOrNull:
513 //
514 // Part of Prefetch
515 if let Some(link) = self.link.as_ref() {
516 link.root().fire_event_after_response(cx, response_result);
517 }
518 }
519
520 fn process_csp_violations(
521 &mut self,
522 cx: &mut js::context::JSContext,
523 _request_id: RequestId,
524 violations: Vec<Violation>,
525 ) {
526 let global = &self.resource_timing_global();
527 global.report_csp_violations(cx, violations, None, None);
528 }
529
530 fn process_content_length(&mut self, _request_id: RequestId, size: usize) {
531 self.response_body
532 .reserve(size.saturating_sub(self.response_body.len()));
533 }
534}
535
536impl ResourceTimingListener for LinkFetchContext {
537 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
538 (self.type_.clone().into(), self.url.clone())
539 }
540
541 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
542 self.global.root()
543 }
544}