script/dom/html/
htmlmetaelement.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 content_security_policy::{Policy, PolicyDisposition, PolicySource};
8use dom_struct::dom_struct;
9use html5ever::{LocalName, Prefix, local_name};
10use js::rust::HandleObject;
11use net_traits::ReferrerPolicy;
12use paint_api::viewport_description::ViewportDescription;
13use servo_config::pref;
14use style::str::HTML_SPACE_CHARACTERS;
15
16use crate::dom::attr::Attr;
17use crate::dom::bindings::codegen::Bindings::HTMLMetaElementBinding::HTMLMetaElementMethods;
18use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
19use crate::dom::bindings::inheritance::Castable;
20use crate::dom::bindings::root::DomRoot;
21use crate::dom::bindings::str::DOMString;
22use crate::dom::document::Document;
23use crate::dom::element::{AttributeMutation, Element};
24use crate::dom::html::htmlelement::HTMLElement;
25use crate::dom::html::htmlheadelement::HTMLHeadElement;
26use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
27use crate::dom::virtualmethods::VirtualMethods;
28use crate::script_runtime::CanGc;
29
30#[dom_struct]
31pub(crate) struct HTMLMetaElement {
32    htmlelement: HTMLElement,
33}
34
35impl HTMLMetaElement {
36    fn new_inherited(
37        local_name: LocalName,
38        prefix: Option<Prefix>,
39        document: &Document,
40    ) -> HTMLMetaElement {
41        HTMLMetaElement {
42            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
43        }
44    }
45
46    pub(crate) fn new(
47        local_name: LocalName,
48        prefix: Option<Prefix>,
49        document: &Document,
50        proto: Option<HandleObject>,
51        can_gc: CanGc,
52    ) -> DomRoot<HTMLMetaElement> {
53        Node::reflect_node_with_proto(
54            Box::new(HTMLMetaElement::new_inherited(local_name, prefix, document)),
55            document,
56            proto,
57            can_gc,
58        )
59    }
60
61    fn process_attributes(&self) {
62        let element = self.upcast::<Element>();
63        if let Some(ref name) = element.get_name() {
64            let name = name.to_ascii_lowercase();
65            let name = name.trim_matches(HTML_SPACE_CHARACTERS);
66            if name == "referrer" {
67                self.apply_referrer();
68            }
69            if name == "viewport" {
70                self.parse_and_send_viewport_if_necessary();
71            }
72        // https://html.spec.whatwg.org/multipage/#attr-meta-http-equiv
73        } else if !self.HttpEquiv().is_empty() {
74            // TODO: Implement additional http-equiv candidates
75            match self.HttpEquiv().to_ascii_lowercase().as_str() {
76                "refresh" => self.declarative_refresh(),
77                "content-security-policy" => self.apply_csp_list(),
78                _ => {},
79            }
80        }
81    }
82
83    fn process_referrer_attribute(&self) {
84        let element = self.upcast::<Element>();
85        if let Some(ref name) = element.get_name() {
86            let name = name.to_ascii_lowercase();
87            let name = name.trim_matches(HTML_SPACE_CHARACTERS);
88
89            if name == "referrer" {
90                self.apply_referrer();
91            }
92        }
93    }
94
95    /// <https://html.spec.whatwg.org/multipage/#meta-referrer>
96    fn apply_referrer(&self) {
97        let doc = self.owner_document();
98        // From spec: For historical reasons, unlike other standard metadata names, the processing model for referrer
99        // is not responsive to element removals, and does not use tree order. Only the most-recently-inserted or
100        // most-recently-modified meta element in this state has an effect.
101        // Step 1. If element is not in a document tree, then return.
102        let meta_node = self.upcast::<Node>();
103        if !meta_node.is_in_a_document_tree() {
104            return;
105        }
106
107        // Step 2. If element does not have a name attribute whose value is an ASCII
108        // case-insensitive match for "referrer", then return.
109        if self.upcast::<Element>().get_name() != Some(atom!("referrer")) {
110            return;
111        }
112
113        // Step 3. If element does not have a content attribute, or that attribute's value is the
114        // empty string, then return.
115        if let Some(content) = self
116            .upcast::<Element>()
117            .get_attribute(&local_name!("content"))
118            .filter(|attr| !attr.value().is_empty())
119        {
120            // Step 4. Let value be the value of element's content attribute, converted to ASCII
121            // lowercase.
122            // Step 5. If value is one of the values given in the first column of the following
123            // table, then set value to the value given in the second column:
124            // Step 6. If value is a referrer policy, then set element's node document's policy
125            // container's referrer policy to policy.
126            doc.set_referrer_policy(ReferrerPolicy::from_with_legacy(&content.value()));
127        }
128    }
129
130    /// <https://drafts.csswg.org/css-viewport/#parsing-algorithm>
131    fn parse_and_send_viewport_if_necessary(&self) {
132        if !pref!(viewport_meta_enabled) {
133            return;
134        }
135
136        // Skip processing if this isn't the top level frame
137        if !self.owner_window().is_top_level() {
138            return;
139        }
140        let element = self.upcast::<Element>();
141        let Some(content) = element.get_attribute(&local_name!("content")) else {
142            return;
143        };
144
145        if let Ok(viewport) = ViewportDescription::from_str(&content.value()) {
146            self.owner_window()
147                .paint_api()
148                .viewport(self.owner_window().webview_id(), viewport);
149        }
150    }
151
152    /// <https://html.spec.whatwg.org/multipage/#attr-meta-http-equiv-content-security-policy>
153    fn apply_csp_list(&self) {
154        // Step 1. If the meta element is not a child of a head element, return.
155        if self
156            .upcast::<Node>()
157            .GetParentElement()
158            .is_none_or(|parent| !parent.is::<HTMLHeadElement>())
159        {
160            return;
161        };
162        // Step 2. If the meta element has no content attribute, or if that attribute's value is the empty string, then return.
163        let Some(content) = self
164            .upcast::<Element>()
165            .get_attribute(&local_name!("content"))
166        else {
167            return;
168        };
169        let content = content.value();
170        if content.is_empty() {
171            return;
172        }
173        // Step 3. Let policy be the result of executing Content Security Policy's
174        // parse a serialized Content Security Policy algorithm
175        // on the meta element's content attribute's value,
176        // with a source of "meta", and a disposition of "enforce".
177        let mut policy = Policy::parse(&content, PolicySource::Meta, PolicyDisposition::Enforce);
178        // Step 4. Remove all occurrences of the report-uri, frame-ancestors,
179        // and sandbox directives from policy.
180        policy.directive_set.retain(|directive| {
181            !matches!(
182                directive.name.as_str(),
183                "report-uri" | "frame-ancestors" | "sandbox"
184            )
185        });
186        // Step 5. Enforce the policy policy.
187        self.owner_document().enforce_csp_policy(policy);
188    }
189
190    /// <https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps>
191    fn declarative_refresh(&self) {
192        if !self.upcast::<Node>().is_in_a_document_tree() {
193            return;
194        }
195
196        // Step 2. Let input be the value of the element's content attribute.
197        let content = self.Content();
198        // Step 1. If the meta element has no content attribute, or if that attribute's value is the empty string, then return.
199        if !content.is_empty() {
200            // Step 3. Run the shared declarative refresh steps with the meta element's node document, input, and the meta element.
201            self.owner_document()
202                .shared_declarative_refresh_steps(&content.as_bytes());
203        }
204    }
205}
206
207impl HTMLMetaElementMethods<crate::DomTypeHolder> for HTMLMetaElement {
208    // https://html.spec.whatwg.org/multipage/#dom-meta-name
209    make_getter!(Name, "name");
210
211    // https://html.spec.whatwg.org/multipage/#dom-meta-name
212    make_atomic_setter!(SetName, "name");
213
214    // https://html.spec.whatwg.org/multipage/#dom-meta-content
215    make_getter!(Content, "content");
216
217    // https://html.spec.whatwg.org/multipage/#dom-meta-content
218    make_setter!(SetContent, "content");
219
220    // https://html.spec.whatwg.org/multipage/#dom-meta-httpequiv
221    make_getter!(HttpEquiv, "http-equiv");
222    // https://html.spec.whatwg.org/multipage/#dom-meta-httpequiv
223    make_atomic_setter!(SetHttpEquiv, "http-equiv");
224
225    // https://html.spec.whatwg.org/multipage/#dom-meta-scheme
226    make_getter!(Scheme, "scheme");
227    // https://html.spec.whatwg.org/multipage/#dom-meta-scheme
228    make_setter!(SetScheme, "scheme");
229}
230
231impl VirtualMethods for HTMLMetaElement {
232    fn super_type(&self) -> Option<&dyn VirtualMethods> {
233        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
234    }
235
236    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
237        if let Some(s) = self.super_type() {
238            s.bind_to_tree(context, can_gc);
239        }
240
241        if context.tree_connected {
242            self.process_attributes();
243        }
244    }
245
246    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
247        if let Some(s) = self.super_type() {
248            s.attribute_mutated(attr, mutation, can_gc);
249        }
250
251        self.process_referrer_attribute();
252    }
253
254    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
255        if let Some(s) = self.super_type() {
256            s.unbind_from_tree(context, can_gc);
257        }
258
259        if context.tree_connected {
260            self.process_referrer_attribute();
261        }
262    }
263}