Skip to main content

script/dom/html/links/
relations.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
5//! Defines shared hyperlink behaviour for `<link>`, `<a>`, `<area>` and `<form>` elements.
6
7use html5ever::local_name;
8use js::context::JSContext;
9use malloc_size_of::malloc_size_of_is_0;
10use net_traits::request::Referrer;
11use servo_constellation_traits::{LoadData, LoadOrigin, NavigationHistoryBehavior};
12use style::str::HTML_SPACE_CHARACTERS;
13
14use crate::dom::bindings::inheritance::Castable;
15use crate::dom::bindings::str::DOMString;
16use crate::dom::element::referrer_policy_for_element;
17use crate::dom::html::htmlanchorelement::HTMLAnchorElement;
18use crate::dom::html::htmlareaelement::HTMLAreaElement;
19use crate::dom::html::htmlformelement::HTMLFormElement;
20use crate::dom::html::htmllinkelement::HTMLLinkElement;
21use crate::dom::node::NodeTraits;
22use crate::dom::types::Element;
23use crate::dom::window::windowproxy::WindowOpenType;
24use crate::navigation::navigate;
25
26bitflags::bitflags! {
27    /// Describes the different relations that can be specified on elements using the `rel`
28    /// attribute.
29    ///
30    /// Refer to <https://html.spec.whatwg.org/multipage/#linkTypes> for more information.
31    #[derive(Clone, Copy, Debug, PartialEq)]
32    pub(crate) struct LinkRelations: u32 {
33        /// <https://html.spec.whatwg.org/multipage/#rel-alternate>
34        const ALTERNATE = 1;
35
36        /// <https://html.spec.whatwg.org/multipage/#link-type-author>
37        const AUTHOR = 1 << 1;
38
39        /// <https://html.spec.whatwg.org/multipage/#link-type-bookmark>
40        const BOOKMARK = 1 << 2;
41
42        /// <https://html.spec.whatwg.org/multipage/#link-type-canonical>
43        const CANONICAL = 1 << 3;
44
45        /// <https://html.spec.whatwg.org/multipage/#link-type-dns-prefetch>
46        const DNS_PREFETCH = 1 << 4;
47
48        /// <https://html.spec.whatwg.org/multipage/#link-type-expect>
49        const EXPECT = 1 << 5;
50
51        /// <https://html.spec.whatwg.org/multipage/#link-type-external>
52        const EXTERNAL = 1 << 6;
53
54        /// <https://html.spec.whatwg.org/multipage/#link-type-help>
55        const HELP = 1 << 7;
56
57        /// <https://html.spec.whatwg.org/multipage/#rel-icon>
58        const ICON = 1 << 8;
59
60        /// <https://html.spec.whatwg.org/multipage/#link-type-license>
61        const LICENSE = 1 << 9;
62
63        /// <https://html.spec.whatwg.org/multipage/#link-type-next>
64        const NEXT = 1 << 10;
65
66        /// <https://html.spec.whatwg.org/multipage/#link-type-manifest>
67        const MANIFEST = 1 << 11;
68
69        /// <https://html.spec.whatwg.org/multipage/#link-type-modulepreload>
70        const MODULE_PRELOAD = 1 << 12;
71
72        /// <https://html.spec.whatwg.org/multipage/#link-type-nofollow>
73        const NO_FOLLOW = 1 << 13;
74
75        /// <https://html.spec.whatwg.org/multipage/#link-type-noopener>
76        const NO_OPENER = 1 << 14;
77
78        /// <https://html.spec.whatwg.org/multipage/#link-type-noreferrer>
79        const NO_REFERRER = 1 << 15;
80
81        /// <https://html.spec.whatwg.org/multipage/#link-type-opener>
82        const OPENER = 1 << 16;
83
84        /// <https://html.spec.whatwg.org/multipage/#link-type-pingback>
85        const PING_BACK = 1 << 17;
86
87        /// <https://html.spec.whatwg.org/multipage/#link-type-preconnect>
88        const PRECONNECT = 1 << 18;
89
90        /// <https://html.spec.whatwg.org/multipage/#link-type-prefetch>
91        const PREFETCH = 1 << 19;
92
93        /// <https://html.spec.whatwg.org/multipage/#link-type-preload>
94        const PRELOAD = 1 << 20;
95
96        /// <https://html.spec.whatwg.org/multipage/#link-type-prev>
97        const PREV = 1 << 21;
98
99        /// <https://html.spec.whatwg.org/multipage/#link-type-privacy-policy>
100        const PRIVACY_POLICY = 1 << 22;
101
102        /// <https://html.spec.whatwg.org/multipage/#link-type-search>
103        const SEARCH = 1 << 23;
104
105        /// <https://html.spec.whatwg.org/multipage/#link-type-stylesheet>
106        const STYLESHEET = 1 << 24;
107
108        /// <https://html.spec.whatwg.org/multipage/#link-type-tag>
109        const TAG = 1 << 25;
110
111        /// <https://html.spec.whatwg.org/multipage/#link-type-terms-of-service>
112        const TERMS_OF_SERVICE = 1 << 26;
113    }
114}
115
116impl LinkRelations {
117    /// The set of allowed relations for [`<link>`] elements
118    ///
119    /// [`<link>`]: https://html.spec.whatwg.org/multipage/#htmllinkelement
120    pub(crate) const ALLOWED_LINK_RELATIONS: Self = Self::ALTERNATE
121        .union(Self::CANONICAL)
122        .union(Self::AUTHOR)
123        .union(Self::DNS_PREFETCH)
124        .union(Self::EXPECT)
125        .union(Self::HELP)
126        .union(Self::ICON)
127        .union(Self::MANIFEST)
128        .union(Self::MODULE_PRELOAD)
129        .union(Self::LICENSE)
130        .union(Self::NEXT)
131        .union(Self::PING_BACK)
132        .union(Self::PRECONNECT)
133        .union(Self::PREFETCH)
134        .union(Self::PRELOAD)
135        .union(Self::PREV)
136        .union(Self::PRIVACY_POLICY)
137        .union(Self::SEARCH)
138        .union(Self::STYLESHEET)
139        .union(Self::TERMS_OF_SERVICE);
140
141    /// The set of allowed relations for [`<a>`] and [`<area>`] elements
142    ///
143    /// [`<a>`]: https://html.spec.whatwg.org/multipage/#the-a-element
144    /// [`<area>`]: https://html.spec.whatwg.org/multipage/#the-area-element
145    pub(crate) const ALLOWED_ANCHOR_OR_AREA_RELATIONS: Self = Self::ALTERNATE
146        .union(Self::AUTHOR)
147        .union(Self::BOOKMARK)
148        .union(Self::EXTERNAL)
149        .union(Self::HELP)
150        .union(Self::LICENSE)
151        .union(Self::NEXT)
152        .union(Self::NO_FOLLOW)
153        .union(Self::NO_OPENER)
154        .union(Self::NO_REFERRER)
155        .union(Self::OPENER)
156        .union(Self::PREV)
157        .union(Self::PRIVACY_POLICY)
158        .union(Self::SEARCH)
159        .union(Self::TAG)
160        .union(Self::TERMS_OF_SERVICE);
161
162    /// The set of allowed relations for [`<form>`] elements
163    ///
164    /// [`<form>`]: https://html.spec.whatwg.org/multipage/#the-form-element
165    pub(crate) const ALLOWED_FORM_RELATIONS: Self = Self::EXTERNAL
166        .union(Self::HELP)
167        .union(Self::LICENSE)
168        .union(Self::NEXT)
169        .union(Self::NO_FOLLOW)
170        .union(Self::NO_OPENER)
171        .union(Self::NO_REFERRER)
172        .union(Self::OPENER)
173        .union(Self::PREV)
174        .union(Self::SEARCH);
175
176    /// Compute the set of relations for an element given its `"rel"` attribute
177    ///
178    /// This function should only be used with [`<link>`], [`<a>`], [`<area>`] and [`<form>`] elements.
179    ///
180    /// [`<link>`]: https://html.spec.whatwg.org/multipage/#htmllinkelement
181    /// [`<a>`]: https://html.spec.whatwg.org/multipage/#the-a-element
182    /// [`<area>`]: https://html.spec.whatwg.org/multipage/#the-area-element
183    /// [`<form>`]: https://html.spec.whatwg.org/multipage/#the-form-element
184    pub(crate) fn for_element(element: &Element) -> Self {
185        let rel = element.get_attribute_string_ref(&local_name!("rel"));
186
187        let mut relations = rel
188            .map(|attribute| {
189                attribute
190                    .value()
191                    .split(HTML_SPACE_CHARACTERS)
192                    .map(Self::from_single_keyword)
193                    .collect()
194            })
195            .unwrap_or(Self::empty());
196
197        // For historical reasons, "rev=made" is treated as if the "author" relation was specified
198        let has_legacy_author_relation = element
199            .get_attribute_string_value(&local_name!("rev"))
200            .is_some_and(|rev| rev == "made");
201        if has_legacy_author_relation {
202            relations |= Self::AUTHOR;
203        }
204
205        let allowed_relations = if element.is::<HTMLLinkElement>() {
206            Self::ALLOWED_LINK_RELATIONS
207        } else if element.is::<HTMLAnchorElement>() || element.is::<HTMLAreaElement>() {
208            Self::ALLOWED_ANCHOR_OR_AREA_RELATIONS
209        } else if element.is::<HTMLFormElement>() {
210            Self::ALLOWED_FORM_RELATIONS
211        } else {
212            Self::empty()
213        };
214
215        relations & allowed_relations
216    }
217
218    /// Parse one single link relation keyword
219    ///
220    /// If the keyword is invalid then `Self::empty()` is returned.
221    fn from_single_keyword(keyword: &str) -> Self {
222        if keyword.eq_ignore_ascii_case("alternate") {
223            Self::ALTERNATE
224        } else if keyword.eq_ignore_ascii_case("canonical") {
225            Self::CANONICAL
226        } else if keyword.eq_ignore_ascii_case("author") {
227            Self::AUTHOR
228        } else if keyword.eq_ignore_ascii_case("bookmark") {
229            Self::BOOKMARK
230        } else if keyword.eq_ignore_ascii_case("dns-prefetch") {
231            Self::DNS_PREFETCH
232        } else if keyword.eq_ignore_ascii_case("expect") {
233            Self::EXPECT
234        } else if keyword.eq_ignore_ascii_case("external") {
235            Self::EXTERNAL
236        } else if keyword.eq_ignore_ascii_case("help") {
237            Self::HELP
238        } else if keyword.eq_ignore_ascii_case("icon") ||
239            keyword.eq_ignore_ascii_case("shortcut icon") ||
240            keyword.eq_ignore_ascii_case("apple-touch-icon")
241        {
242            // TODO: "apple-touch-icon" is not in the spec. Where did it come from? Do we need it?
243            //       There is also "apple-touch-icon-precomposed" listed in
244            //       https://github.com/servo/servo/blob/e43e4778421be8ea30db9d5c553780c042161522/components/script/dom/htmllinkelement.rs#L452-L467
245            Self::ICON
246        } else if keyword.eq_ignore_ascii_case("manifest") {
247            Self::MANIFEST
248        } else if keyword.eq_ignore_ascii_case("modulepreload") {
249            Self::MODULE_PRELOAD
250        } else if keyword.eq_ignore_ascii_case("license") ||
251            keyword.eq_ignore_ascii_case("copyright")
252        {
253            Self::LICENSE
254        } else if keyword.eq_ignore_ascii_case("next") {
255            Self::NEXT
256        } else if keyword.eq_ignore_ascii_case("nofollow") {
257            Self::NO_FOLLOW
258        } else if keyword.eq_ignore_ascii_case("noopener") {
259            Self::NO_OPENER
260        } else if keyword.eq_ignore_ascii_case("noreferrer") {
261            Self::NO_REFERRER
262        } else if keyword.eq_ignore_ascii_case("opener") {
263            Self::OPENER
264        } else if keyword.eq_ignore_ascii_case("pingback") {
265            Self::PING_BACK
266        } else if keyword.eq_ignore_ascii_case("preconnect") {
267            Self::PRECONNECT
268        } else if keyword.eq_ignore_ascii_case("prefetch") {
269            Self::PREFETCH
270        } else if keyword.eq_ignore_ascii_case("preload") {
271            Self::PRELOAD
272        } else if keyword.eq_ignore_ascii_case("prev") || keyword.eq_ignore_ascii_case("previous") {
273            Self::PREV
274        } else if keyword.eq_ignore_ascii_case("privacy-policy") {
275            Self::PRIVACY_POLICY
276        } else if keyword.eq_ignore_ascii_case("search") {
277            Self::SEARCH
278        } else if keyword.eq_ignore_ascii_case("stylesheet") {
279            Self::STYLESHEET
280        } else if keyword.eq_ignore_ascii_case("tag") {
281            Self::TAG
282        } else if keyword.eq_ignore_ascii_case("terms-of-service") {
283            Self::TERMS_OF_SERVICE
284        } else {
285            Self::empty()
286        }
287    }
288
289    /// <https://html.spec.whatwg.org/multipage/#get-an-element%27s-noopener>
290    pub(crate) fn get_element_noopener(&self, target_attribute_value: Option<&DOMString>) -> bool {
291        // Step 1. If element's link types include the noopener or noreferrer keyword, then return true.
292        if self.contains(Self::NO_OPENER) || self.contains(Self::NO_REFERRER) {
293            return true;
294        }
295
296        // Step 2. If element's link types do not include the opener keyword and
297        //         target is an ASCII case-insensitive match for "_blank", then return true.
298        let target_is_blank =
299            target_attribute_value.is_some_and(|target| target.eq_ignore_ascii_case("_blank"));
300        if !self.contains(Self::OPENER) && target_is_blank {
301            return true;
302        }
303
304        // Step 3. Return false.
305        false
306    }
307}
308
309malloc_size_of_is_0!(LinkRelations);
310
311/// <https://html.spec.whatwg.org/multipage/#valid-navigable-target-name>
312fn valid_navigable_target_name(target: &DOMString) -> bool {
313    // > A valid navigable target name is any string with at least one character that does not contain both
314    // > an ASCII tab or newline and a U+003C (<), and it does not start with a U+005F (_).
315    // > (Names starting with a U+005F (_) are reserved for special keywords.)
316    if target.is_empty() {
317        return false;
318    }
319    if target.contains_tab_or_newline() && target.contains("\u{003C}") {
320        return false;
321    }
322    if target.starts_with('\u{005F}') {
323        return false;
324    }
325    true
326}
327
328/// <https://html.spec.whatwg.org/multipage/#valid-navigable-target-name-or-keyword>
329pub(crate) fn valid_navigable_target_name_or_keyword(target: &DOMString) -> bool {
330    // > A valid navigable target name or keyword is any string that is either a valid navigable target name
331    // > or that is an ASCII case-insensitive match for one of: _blank, _self, _parent, or _top.
332    if valid_navigable_target_name(target) {
333        return true;
334    }
335    target.eq_ignore_ascii_case("_blank") ||
336        target.eq_ignore_ascii_case("_self") ||
337        target.eq_ignore_ascii_case("_parent") ||
338        target.eq_ignore_ascii_case("_top")
339}
340
341/// <https://html.spec.whatwg.org/multipage/#get-an-element%27s-target>
342pub(crate) fn get_element_target(
343    subject: &Element,
344    target: Option<DOMString>,
345) -> Option<DOMString> {
346    assert!(
347        subject.is::<HTMLAreaElement>() ||
348            subject.is::<HTMLAnchorElement>() ||
349            subject.is::<HTMLFormElement>()
350    );
351
352    // Step 1. If target is null, then:
353    let target = target.or_else(|| {
354        // Step 1.1. If element has a target attribute, then set target to that attribute's value.
355        //
356        // Note that for a target attribute to be valid, it must be a valid navigable target name
357        // or keyword
358        let element_target = subject.get_string_attribute(&local_name!("target"));
359        if valid_navigable_target_name_or_keyword(&element_target) {
360            Some(element_target)
361        } else {
362            // Step 1.2. Otherwise, if element's node document contains a base element with a target attribute,
363            // set target to the value of the target attribute of the first such base element.
364            subject
365                .owner_document()
366                .target_base_element()
367                .and_then(|base_element| {
368                    let element = base_element.upcast::<Element>();
369                    if element.has_attribute(&local_name!("target")) {
370                        Some(element.get_string_attribute(&local_name!("target")))
371                    } else {
372                        None
373                    }
374                })
375        }
376    });
377    // Step 2. If target is not null, and contains an ASCII tab or newline and a U+003C (<), then set target to "_blank".
378    if let Some(ref target) = target &&
379        target.contains_tab_or_newline() &&
380        target.contains("\u{003C}")
381    {
382        return Some(DOMString::from_static("_blank"));
383    }
384    // Step 3. Return target.
385    target
386}
387
388/// <https://html.spec.whatwg.org/multipage/#following-hyperlinks-2>
389pub(crate) fn follow_hyperlink(
390    cx: &mut JSContext,
391    subject: &Element,
392    relations: LinkRelations,
393    hyperlink_suffix: Option<String>,
394) {
395    // Step 1: If subject cannot navigate, then return.
396    if subject.cannot_navigate() {
397        return;
398    }
399
400    // Step 2: Let targetAttributeValue be the empty string.
401    // This is done below.
402
403    // Step 3: If subject is an a or area element, then set targetAttributeValue to the
404    //         result of getting an element's target given subject.
405    //
406    // Also allow the user to open links in a new WebView by pressing either the meta or
407    // control key (depending on the platform).
408    let document = subject.owner_document();
409    let target_attribute_value =
410        if subject.is::<HTMLAreaElement>() || subject.is::<HTMLAnchorElement>() {
411            if document
412                .event_handler()
413                .alternate_action_keyboard_modifier_active()
414            {
415                Some(DOMString::from_static("_blank"))
416            } else {
417                get_element_target(subject, None)
418            }
419        } else {
420            None
421        };
422
423    // Step 4: Let urlRecord be the result of encoding-parsing a URL given subject's href
424    //         attribute value, relative to subject's node document.
425    // Step 5: If urlRecord is failure, then return.
426    // TODO: Implement this.
427
428    // Step 6: Let noopener be the result of getting an element's noopener with subject,
429    //         urlRecord, and targetAttributeValue.
430    let noopener = relations.get_element_noopener(target_attribute_value.as_ref());
431
432    // Step 7: Let targetNavigable be the first return value of applying the rules for
433    //         choosing a navigable given targetAttributeValue, subject's node navigable, and
434    //         noopener.
435    let window = document.window();
436
437    let Some(source) = document.browsing_context() else {
438        return;
439    };
440    let (maybe_chosen, history_handling) = match target_attribute_value {
441        Some(name) => {
442            let (maybe_chosen, window_open_type) = source.choose_a_navigable(cx, &name, noopener);
443            let history_handling = if window_open_type != WindowOpenType::ExistingOrNone {
444                NavigationHistoryBehavior::Replace
445            } else {
446                NavigationHistoryBehavior::Push
447            };
448            (maybe_chosen, history_handling)
449        },
450        None => (Some(source), NavigationHistoryBehavior::Push),
451    };
452
453    // Step 8: If targetNavigable is null, then return.
454    let chosen = match maybe_chosen {
455        Some(proxy) => proxy,
456        None => return,
457    };
458
459    if let Some(target_document) = chosen.document() {
460        let target_window = target_document.window();
461        // Step 9: Let urlString be the result of applying the URL serializer to urlRecord.
462        // TODO: Implement this.
463
464        let mut href = subject
465            .get_attribute_string_value(&local_name!("href"))
466            .unwrap();
467
468        // Step 10: If hyperlinkSuffix is non-null, then append it to urlString.
469        if let Some(suffix) = hyperlink_suffix {
470            href.push_str(&suffix);
471        }
472        let Ok(url) = document.encoding_parse_a_url(&href) else {
473            return;
474        };
475
476        // Step 11: Let referrerPolicy be the current state of subject's referrerpolicy content attribute.
477        let referrer_policy = referrer_policy_for_element(subject);
478
479        // Step 12: If subject's link types includes the noreferrer keyword, then set
480        //          referrerPolicy to "no-referrer".
481        let referrer = if relations.contains(LinkRelations::NO_REFERRER) {
482            Referrer::NoReferrer
483        } else {
484            target_window.as_global_scope().get_referrer()
485        };
486
487        // Step 13: Navigate targetNavigable to urlString using subject's node document,
488        //          with referrerPolicy set to referrerPolicy, userInvolvement set to
489        //          userInvolvement, and sourceElement set to subject.
490        let secure = target_window.as_global_scope().is_secure_context();
491        let upgrade_insecure_navigations_set = window
492            .as_global_scope()
493            .upgrade_insecure_navigations_set()
494            .clone();
495        let load_data = LoadData::new(
496            LoadOrigin::Script(document.origin().snapshot()),
497            url,
498            document.about_base_url(),
499            Some(window.pipeline_id()),
500            referrer,
501            referrer_policy,
502            Some(secure),
503            Some(document.insecure_requests_policy()),
504            upgrade_insecure_navigations_set,
505            document.has_trustworthy_ancestor_origin(),
506            document.creation_sandboxing_flag_set_considering_parent_iframe(),
507        );
508        debug!("following hyperlink to {}", load_data.url);
509        navigate(cx, target_window, history_handling, false, load_data);
510    };
511}