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