script/dom/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 base::id::WebViewId;
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, InsecureRequestsPolicy, PreloadEntry, PreloadKey,
17 Referrer, RequestBuilder, RequestId,
18};
19use net_traits::response::{Response, ResponseBody};
20use net_traits::{FetchMetadata, NetworkError, ReferrerPolicy, ResourceFetchTiming};
21pub use nom_rfc8288::complete::LinkDataOwned as LinkHeader;
22use nom_rfc8288::complete::link_lenient as parse_link_header;
23use servo_url::{ImmutableOrigin, ServoUrl};
24use strum_macros::IntoStaticStr;
25
26use crate::dom::bindings::inheritance::Castable;
27use crate::dom::bindings::refcounted::Trusted;
28use crate::dom::bindings::reflector::DomGlobal;
29use crate::dom::bindings::root::DomRoot;
30use crate::dom::csp::{GlobalCspReporting, Violation};
31use crate::dom::document::Document;
32use crate::dom::element::Element;
33use crate::dom::globalscope::GlobalScope;
34use crate::dom::medialist::MediaList;
35use crate::dom::performance::performanceresourcetiming::InitiatorType;
36use crate::dom::types::HTMLLinkElement;
37use crate::fetch::create_a_potential_cors_request;
38use crate::network_listener::{FetchResponseListener, ResourceTimingListener, submit_timing};
39use crate::script_runtime::CanGc;
40
41trait ValueForKeyInLinkHeader {
42 fn has_key_in_link_header(&self, key: &str) -> bool;
43 fn value_for_key_in_link_header(&self, key: &str) -> Option<&str>;
44}
45
46impl ValueForKeyInLinkHeader for LinkHeader {
47 fn has_key_in_link_header(&self, key: &str) -> bool {
48 self.params.iter().any(|p| p.key == key)
49 }
50 fn value_for_key_in_link_header(&self, key: &str) -> Option<&str> {
51 let param = self.params.iter().find(|p| p.key == key)?;
52 param.val.as_deref()
53 }
54}
55
56#[derive(PartialEq)]
57pub(crate) enum LinkProcessingPhase {
58 Media,
59 PreMedia,
60}
61
62/// <https://html.spec.whatwg.org/multipage/#link-processing-options>
63#[derive(Debug)]
64pub(crate) struct LinkProcessingOptions {
65 /// <https://html.spec.whatwg.org/multipage/#link-options-href>
66 pub(crate) href: String,
67 /// <https://html.spec.whatwg.org/multipage/#link-options-destination>
68 pub(crate) destination: Destination,
69 /// <https://html.spec.whatwg.org/multipage/#link-options-integrity>
70 pub(crate) integrity: String,
71 /// <https://html.spec.whatwg.org/multipage/#link-options-type>
72 pub(crate) link_type: String,
73 /// <https://html.spec.whatwg.org/multipage/#link-options-nonce>
74 pub(crate) cryptographic_nonce_metadata: String,
75 /// <https://html.spec.whatwg.org/multipage/#link-options-crossorigin>
76 pub(crate) cross_origin: Option<CorsSettings>,
77 /// <https://html.spec.whatwg.org/multipage/#link-options-referrer-policy>
78 pub(crate) referrer_policy: ReferrerPolicy,
79 /// <https://html.spec.whatwg.org/multipage/#link-options-policy-container>
80 pub(crate) policy_container: PolicyContainer,
81 /// <https://html.spec.whatwg.org/multipage/#link-options-source-set>
82 pub(crate) source_set: Option<()>,
83 /// <https://html.spec.whatwg.org/multipage/#link-options-base-url>
84 pub(crate) base_url: ServoUrl,
85 /// <https://html.spec.whatwg.org/multipage/#link-options-origin>
86 pub(crate) origin: ImmutableOrigin,
87 pub(crate) insecure_requests_policy: InsecureRequestsPolicy,
88 pub(crate) has_trustworthy_ancestor_origin: bool,
89 // https://html.spec.whatwg.org/multipage/#link-options-environment
90 // TODO
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 // FIXME: Step 10. Set request's client to options's environment.
200 // FIXME: Step 11. Set request's priority to options's fetch priority.
201 // FIXME: Use correct referrer
202 let builder = create_a_potential_cors_request(
203 Some(webview_id),
204 url,
205 self.destination,
206 self.cross_origin,
207 None,
208 Referrer::NoReferrer,
209 self.insecure_requests_policy,
210 self.has_trustworthy_ancestor_origin,
211 self.policy_container,
212 )
213 .initiator(Initiator::Link)
214 .origin(self.origin)
215 .integrity_metadata(self.integrity)
216 .cryptographic_nonce_metadata(self.cryptographic_nonce_metadata)
217 .referrer_policy(self.referrer_policy);
218
219 // Step 12. Return request.
220 Some(builder)
221 }
222
223 /// <https://html.spec.whatwg.org/multipage/#match-preload-type>
224 pub(crate) fn type_matches_destination(&self) -> bool {
225 // Step 1. If type is an empty string, then return true.
226 if self.link_type.is_empty() {
227 return true;
228 }
229 // Step 2. If destination is "fetch", then return true.
230 //
231 // Fetch is handled as an empty string destination in the spec:
232 // https://fetch.spec.whatwg.org/#concept-potential-destination-translate
233 let destination = self.destination;
234 if destination == Destination::None {
235 return true;
236 }
237 // Step 3. Let mimeTypeRecord be the result of parsing type.
238 let Ok(mime_type_record) = Mime::from_str(&self.link_type) else {
239 // Step 4. If mimeTypeRecord is failure, then return false.
240 return false;
241 };
242 // Step 5. If mimeTypeRecord is not supported by the user agent, then return false.
243 //
244 // We currently don't check if we actually support the mime type. Only if we can classify
245 // it according to the spec.
246 let Some(mime_type) = MimeClassifier::get_media_type(&mime_type_record) else {
247 return false;
248 };
249 // Step 6. If any of the following are true:
250 if
251 // destination is "audio" or "video", and mimeTypeRecord is an audio or video MIME type;
252 ((destination == Destination::Audio || destination == Destination::Video) &&
253 mime_type == MediaType::AudioVideo)
254 // destination is a script-like destination and mimeTypeRecord is a JavaScript MIME type;
255 || (destination.is_script_like() && mime_type == MediaType::JavaScript)
256 // destination is "image" and mimeTypeRecord is an image MIME type;
257 || (destination == Destination::Image && mime_type == MediaType::Image)
258 // destination is "font" and mimeTypeRecord is a font MIME type;
259 || (destination == Destination::Font && mime_type == MediaType::Font)
260 // destination is "json" and mimeTypeRecord is a JSON MIME type;
261 || (destination == Destination::Json && mime_type == MediaType::Json)
262 // destination is "style" and mimeTypeRecord's essence is text/css; or
263 || (destination == Destination::Style && mime_type_record == mime::TEXT_CSS)
264 // destination is "track" and mimeTypeRecord's essence is text/vtt,
265 || (destination == Destination::Track && mime_type_record.essence_str() == "text/vtt")
266 {
267 // then return true.
268 return true;
269 }
270 // Step 7. Return false.
271 false
272 }
273
274 /// <https://html.spec.whatwg.org/multipage/#preload>
275 pub(crate) fn preload(
276 self,
277 webview_id: WebViewId,
278 link: Option<Trusted<HTMLLinkElement>>,
279 document: &Document,
280 ) {
281 // Step 1. If options's type doesn't match options's destination, then return.
282 //
283 // Handled by callers, since we need to check the previous destination type
284 assert!(self.type_matches_destination());
285 // Step 2. If options's destination is "image" and options's source set is not null,
286 // then set options's href to the result of selecting an image source from options's source set.
287 // TODO
288 let integrity = self.integrity.clone();
289 // Step 3. Let request be the result of creating a link request given options.
290 let Some(request) = self.create_link_request(webview_id) else {
291 // Step 4. If request is null, then return.
292 return;
293 };
294 // Step 5. Let unsafeEndTime be 0.
295 // TODO
296 // Step 6. Let entry be a new preload entry whose integrity metadata is options's integrity.
297 let entry = PreloadEntry::new(integrity);
298 // Step 7. Let key be the result of creating a preload key given request.
299 let key = PreloadKey::new(&request);
300 // Step 8. If options's document is "pending", then set request's initiator type to "early hint".
301 // TODO
302 // Step 9. Let controller be null.
303 // Step 10. Let reportTiming given a Document document be to report timing for controller
304 // given document's relevant global object.
305 // Step 11. Set controller to the result of fetching request, with processResponseConsumeBody
306 // set to the following steps given a response response and null, failure, or a byte sequence bodyBytes:
307 let url = request.url.clone();
308 let fetch_context = LinkFetchContext {
309 url,
310 link,
311 document: Trusted::new(document),
312 global: Trusted::new(&document.global()),
313 type_: LinkFetchContextType::Preload(key, Box::new(entry)),
314 response_body: vec![],
315 };
316 document.fetch_background(request, fetch_context);
317 }
318}
319
320pub(crate) fn determine_cors_settings_for_token(token: &str) -> Option<CorsSettings> {
321 match_ignore_ascii_case! { token,
322 "anonymous" => Some(CorsSettings::Anonymous),
323 "use-credentials" => Some(CorsSettings::UseCredentials),
324 _ => None,
325 }
326}
327
328/// <https://html.spec.whatwg.org/multipage/#extract-links-from-headers>
329pub(crate) fn extract_links_from_headers(headers: &Option<Serde<HeaderMap>>) -> Vec<LinkHeader> {
330 // Step 1. Let links be a new list.
331 let mut links = Vec::new();
332 let Some(headers) = headers else {
333 return links;
334 };
335 // Step 2. Let rawLinkHeaders be the result of getting, decoding, and splitting `Link` from headers.
336 let Some(raw_link_headers) = get_decode_and_split_header_name("Link", headers) else {
337 return links;
338 };
339 // Step 3. For each linkHeader of rawLinkHeaders:
340 for link_header in raw_link_headers {
341 // Step 3.1. Let linkObject be the result of parsing linkHeader. [WEBLINK]
342 let Ok(parsed_link_header) = parse_link_header(&link_header) else {
343 continue;
344 };
345 for link_object in parsed_link_header {
346 let Some(link_object) = link_object else {
347 // Step 3.2. If linkObject["target_uri"] does not exist, then continue.
348 continue;
349 };
350 // Step 3.3. Append linkObject to links.
351 links.push(link_object.to_owned());
352 }
353 }
354 // Step 4. Return links.
355 links
356}
357
358/// <https://html.spec.whatwg.org/multipage/#process-link-headers>
359pub(crate) fn process_link_headers(
360 link_headers: &[LinkHeader],
361 document: &Document,
362 phase: LinkProcessingPhase,
363) {
364 // Step 1. Let links be the result of extracting links from response's header list.
365 //
366 // Already performed once when parsing headers by caller
367 // Step 2. For each linkObject in links:
368 for link_object in link_headers {
369 // Step 2.1. Let rel be linkObject["relation_type"].
370 let Some(rel) = link_object.value_for_key_in_link_header("rel") else {
371 continue;
372 };
373 // Step 2.2. Let attribs be linkObject["target_attributes"].
374 //
375 // Not applicable, that's in `link_object.params`
376 // Step 2.3. Let expectedPhase be "media" if either "srcset", "imagesrcset",
377 // or "media" exist in attribs; otherwise "pre-media".
378 let expected_phase = if link_object.has_key_in_link_header("srcset") ||
379 link_object.has_key_in_link_header("imagesrcset") ||
380 link_object.has_key_in_link_header("media")
381 {
382 LinkProcessingPhase::Media
383 } else {
384 LinkProcessingPhase::PreMedia
385 };
386 // Step 2.4. If expectedPhase is not phase, then continue.
387 if expected_phase != phase {
388 continue;
389 }
390 // Step 2.5. If attribs["media"] exists and attribs["media"] does not match the environment, then continue.
391 if let Some(media) = link_object.value_for_key_in_link_header("media") {
392 if !MediaList::matches_environment(document, media) {
393 continue;
394 }
395 }
396 // Step 2.6. Let options be a new link processing options with
397 let mut options = LinkProcessingOptions {
398 href: link_object.url.clone(),
399 destination: Destination::None,
400 integrity: String::new(),
401 link_type: String::new(),
402 cryptographic_nonce_metadata: String::new(),
403 cross_origin: None,
404 referrer_policy: ReferrerPolicy::EmptyString,
405 policy_container: document.policy_container().to_owned(),
406 source_set: None,
407 origin: document.origin().immutable().to_owned(),
408 base_url: document.base_url(),
409 insecure_requests_policy: document.insecure_requests_policy(),
410 has_trustworthy_ancestor_origin: document.has_trustworthy_ancestor_or_current_origin(),
411 };
412 // Step 2.7. Apply link options from parsed header attributes to options given attribs and rel.
413 // If that returned false, then return.
414 if !options.apply_link_options_from_parsed_header(link_object, rel) {
415 return;
416 }
417 // Step 2.8. If attribs["imagesrcset"] exists and attribs["imagesizes"] exists,
418 // then set options's source set to the result of creating a source set given
419 // linkObject["target_uri"], attribs["imagesrcset"], attribs["imagesizes"], and null.
420 // TODO
421 // Step 2.9. Run the process a link header steps for rel given options.
422 options.process_link_header(rel, document);
423 }
424}
425
426#[derive(Clone, IntoStaticStr)]
427#[strum(serialize_all = "lowercase")]
428pub(crate) enum LinkFetchContextType {
429 Prefetch,
430 Preload(PreloadKey, Box<PreloadEntry>),
431}
432
433impl From<LinkFetchContextType> for InitiatorType {
434 fn from(other: LinkFetchContextType) -> Self {
435 let name: &'static str = other.into();
436 InitiatorType::LocalName(name.to_owned())
437 }
438}
439
440pub(crate) struct LinkFetchContext {
441 /// The `<link>` element (if any) that caused this fetch
442 pub(crate) link: Option<Trusted<HTMLLinkElement>>,
443
444 pub(crate) global: Trusted<GlobalScope>,
445 pub(crate) document: Trusted<Document>,
446
447 /// The url being prefetched
448 pub(crate) url: ServoUrl,
449
450 /// The type of fetching we perform, used when report timings.
451 pub(crate) type_: LinkFetchContextType,
452
453 pub(crate) response_body: Vec<u8>,
454}
455
456impl FetchResponseListener for LinkFetchContext {
457 fn process_request_body(&mut self, _: RequestId) {}
458
459 fn process_request_eof(&mut self, _: RequestId) {}
460
461 fn process_response(
462 &mut self,
463 _: RequestId,
464 fetch_metadata: Result<FetchMetadata, NetworkError>,
465 ) {
466 _ = fetch_metadata;
467 }
468
469 fn process_response_chunk(&mut self, _: RequestId, mut chunk: Vec<u8>) {
470 if matches!(self.type_, LinkFetchContextType::Preload(..)) {
471 self.response_body.append(&mut chunk);
472 }
473 }
474
475 /// Step 7 of <https://html.spec.whatwg.org/multipage/#link-type-prefetch:fetch-and-process-the-linked-resource-2>
476 /// and step 3.1 of <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
477 fn process_response_eof(
478 mut self,
479 _: RequestId,
480 response_result: Result<ResourceFetchTiming, NetworkError>,
481 ) {
482 // Steps for https://html.spec.whatwg.org/multipage/#preload
483 if let LinkFetchContextType::Preload(key, entry) = &self.type_ {
484 let response = if let Ok(resource_timing) = &response_result {
485 // Step 11.1. If bodyBytes is a byte sequence, then set response's body to bodyBytes as a body.
486 let response = Response::new(self.url.clone(), resource_timing.clone());
487 *response.body.lock().unwrap() =
488 ResponseBody::Done(std::mem::take(&mut self.response_body));
489 response
490 } else {
491 // Step 11.2. Otherwise, set response to a network error.
492 Response::network_error(NetworkError::Internal("Failed to preload".into()))
493 };
494 // Step 11.5. If entry's on response available is null, then set entry's response to response;
495 // otherwise call entry's on response available given response.
496 let entry = entry.with_response(response);
497
498 // Step 12. Let commit be the following steps given a Document document:
499 // Step 12.1. If entry's response is not null, then call reportTiming given document.
500 // Step 12.2. Set document's map of preloaded resources[key] to entry.
501 // Step 13. If options's document is null, then set options's on document ready to commit. Otherwise, call commit with options's document.
502 let document_preloaded_resources = self.document.root().preloaded_resources();
503 let mut preloaded_resources_lock = document_preloaded_resources.lock();
504 preloaded_resources_lock
505 .as_mut()
506 .unwrap()
507 .insert(key.clone(), entry);
508 }
509
510 // Step 11.6. If processResponse is given, then call processResponse with response.
511 //
512 // Part of Preload
513 //
514 // Step 6. Let processPrefetchResponse be the following steps given a response response and null, failure, or a byte sequence bytesOrNull:
515 //
516 // Part of Prefetch
517 if let Some(link) = self.link.as_ref() {
518 link.root()
519 .fire_event_after_response(response_result.clone(), CanGc::note());
520 }
521
522 if let Ok(response) = response_result {
523 submit_timing(&self, &response, CanGc::note());
524 }
525 }
526
527 fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
528 let global = &self.resource_timing_global();
529 let source_position = self.link.as_ref().map(|link| {
530 let link = link.root();
531 link.upcast::<Element>()
532 .compute_source_position(link.line_number())
533 });
534 global.report_csp_violations(violations, None, source_position);
535 }
536}
537
538impl ResourceTimingListener for LinkFetchContext {
539 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
540 (self.type_.clone().into(), self.url.clone())
541 }
542
543 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
544 self.global.root()
545 }
546}