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