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