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