Bug 1852740: add tests for the `fetchpriority` attribute in Link headers. r=necko...
[gecko.git] / dom / base / LinkStyle.cpp
blob9cf80d1c54f8162ce1d9eb89268a71eb016cc9f4
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /*
8 * A base class which implements nsIStyleSheetLinkingElement and can
9 * be subclassed by various content nodes that want to load
10 * stylesheets (<style>, <link>, processing instructions, etc).
13 #include "mozilla/dom/LinkStyle.h"
15 #include "mozilla/StyleSheet.h"
16 #include "mozilla/StyleSheetInlines.h"
17 #include "mozilla/css/Loader.h"
18 #include "mozilla/dom/Element.h"
19 #include "mozilla/dom/FragmentOrElement.h"
20 #include "mozilla/dom/HTMLLinkElement.h"
21 #include "mozilla/dom/HTMLStyleElement.h"
22 #include "mozilla/dom/SVGStyleElement.h"
23 #include "mozilla/dom/ShadowRoot.h"
24 #include "mozilla/dom/SRILogHelper.h"
25 #include "mozilla/Preferences.h"
26 #include "mozilla/StaticPrefs_dom.h"
27 #include "nsIContent.h"
28 #include "mozilla/dom/Document.h"
29 #include "nsUnicharUtils.h"
30 #include "nsCRT.h"
31 #include "nsXPCOMCIDInternal.h"
32 #include "nsUnicharInputStream.h"
33 #include "nsContentUtils.h"
34 #include "nsStyleUtil.h"
35 #include "nsQueryObject.h"
37 namespace mozilla::dom {
39 LinkStyle::SheetInfo::SheetInfo(
40 const Document& aDocument, nsIContent* aContent,
41 already_AddRefed<nsIURI> aURI,
42 already_AddRefed<nsIPrincipal> aTriggeringPrincipal,
43 already_AddRefed<nsIReferrerInfo> aReferrerInfo,
44 mozilla::CORSMode aCORSMode, const nsAString& aTitle,
45 const nsAString& aMedia, const nsAString& aIntegrity,
46 const nsAString& aNonce, HasAlternateRel aHasAlternateRel,
47 IsInline aIsInline, IsExplicitlyEnabled aIsExplicitlyEnabled)
48 : mContent(aContent),
49 mURI(aURI),
50 mTriggeringPrincipal(aTriggeringPrincipal),
51 mReferrerInfo(aReferrerInfo),
52 mCORSMode(aCORSMode),
53 mTitle(aTitle),
54 mMedia(aMedia),
55 mIntegrity(aIntegrity),
56 mNonce(aNonce),
57 mHasAlternateRel(aHasAlternateRel == HasAlternateRel::Yes),
58 mIsInline(aIsInline == IsInline::Yes),
59 mIsExplicitlyEnabled(aIsExplicitlyEnabled) {
60 MOZ_ASSERT(!mIsInline || aContent);
61 MOZ_ASSERT_IF(aContent, aContent->OwnerDoc() == &aDocument);
62 MOZ_ASSERT(mReferrerInfo);
63 MOZ_ASSERT(mIntegrity.IsEmpty() || !mIsInline,
64 "Integrity only applies to <link>");
67 LinkStyle::SheetInfo::~SheetInfo() = default;
68 LinkStyle::LinkStyle() = default;
70 LinkStyle::~LinkStyle() { LinkStyle::SetStyleSheet(nullptr); }
72 StyleSheet* LinkStyle::GetSheetForBindings() const {
73 if (mStyleSheet && mStyleSheet->IsComplete()) {
74 return mStyleSheet;
76 return nullptr;
79 void LinkStyle::GetTitleAndMediaForElement(const Element& aSelf,
80 nsString& aTitle, nsString& aMedia) {
81 // Only honor title as stylesheet name for elements in the document (that is,
82 // ignore for Shadow DOM), per [1] and [2]. See [3].
84 // [1]: https://html.spec.whatwg.org/#attr-link-title
85 // [2]: https://html.spec.whatwg.org/#attr-style-title
86 // [3]: https://github.com/w3c/webcomponents/issues/535
87 if (aSelf.IsInUncomposedDoc()) {
88 aSelf.GetAttr(nsGkAtoms::title, aTitle);
89 aTitle.CompressWhitespace();
92 aSelf.GetAttr(nsGkAtoms::media, aMedia);
93 // The HTML5 spec is formulated in terms of the CSSOM spec, which specifies
94 // that media queries should be ASCII lowercased during serialization.
96 // FIXME(emilio): How does it matter? This is going to be parsed anyway, CSS
97 // should take care of serializing it properly.
98 nsContentUtils::ASCIIToLower(aMedia);
101 bool LinkStyle::IsCSSMimeTypeAttributeForStyleElement(const Element& aSelf) {
102 // Per
103 // https://html.spec.whatwg.org/multipage/semantics.html#the-style-element:update-a-style-block
104 // step 4, for style elements we should only accept empty and "text/css" type
105 // attribute values.
106 nsAutoString type;
107 aSelf.GetAttr(nsGkAtoms::type, type);
108 return type.IsEmpty() || type.LowerCaseEqualsLiteral("text/css");
111 void LinkStyle::Unlink() { LinkStyle::SetStyleSheet(nullptr); }
113 void LinkStyle::Traverse(nsCycleCollectionTraversalCallback& cb) {
114 LinkStyle* tmp = this;
115 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheet);
118 void LinkStyle::SetStyleSheet(StyleSheet* aStyleSheet) {
119 if (mStyleSheet) {
120 mStyleSheet->SetOwningNode(nullptr);
123 mStyleSheet = aStyleSheet;
124 if (mStyleSheet) {
125 mStyleSheet->SetOwningNode(&AsContent());
129 void LinkStyle::GetCharset(nsAString& aCharset) { aCharset.Truncate(); }
131 static uint32_t ToLinkMask(const nsAString& aLink) {
132 // Keep this in sync with sSupportedRelValues in HTMLLinkElement.cpp
133 uint32_t mask = 0;
134 if (aLink.EqualsLiteral("prefetch")) {
135 mask = LinkStyle::ePREFETCH;
136 } else if (aLink.EqualsLiteral("dns-prefetch")) {
137 mask = LinkStyle::eDNS_PREFETCH;
138 } else if (aLink.EqualsLiteral("stylesheet")) {
139 mask = LinkStyle::eSTYLESHEET;
140 } else if (aLink.EqualsLiteral("next")) {
141 mask = LinkStyle::eNEXT;
142 } else if (aLink.EqualsLiteral("alternate")) {
143 mask = LinkStyle::eALTERNATE;
144 } else if (aLink.EqualsLiteral("preconnect")) {
145 mask = LinkStyle::ePRECONNECT;
146 } else if (aLink.EqualsLiteral("preload")) {
147 mask = LinkStyle::ePRELOAD;
148 } else if (aLink.EqualsLiteral("modulepreload")) {
149 mask = LinkStyle::eMODULE_PRELOAD;
152 return mask;
155 uint32_t LinkStyle::ParseLinkTypes(const nsAString& aTypes) {
156 uint32_t linkMask = 0;
157 nsAString::const_iterator start, done;
158 aTypes.BeginReading(start);
159 aTypes.EndReading(done);
160 if (start == done) return linkMask;
162 nsAString::const_iterator current(start);
163 bool inString = !nsContentUtils::IsHTMLWhitespace(*current);
164 nsAutoString subString;
166 while (current != done) {
167 if (nsContentUtils::IsHTMLWhitespace(*current)) {
168 if (inString) {
169 nsContentUtils::ASCIIToLower(Substring(start, current), subString);
170 linkMask |= ToLinkMask(subString);
171 inString = false;
173 } else {
174 if (!inString) {
175 start = current;
176 inString = true;
179 ++current;
181 if (inString) {
182 nsContentUtils::ASCIIToLower(Substring(start, current), subString);
183 linkMask |= ToLinkMask(subString);
185 return linkMask;
188 Result<LinkStyle::Update, nsresult> LinkStyle::UpdateStyleSheetInternal(
189 Document* aOldDocument, ShadowRoot* aOldShadowRoot,
190 ForceUpdate aForceUpdate) {
191 return DoUpdateStyleSheet(aOldDocument, aOldShadowRoot, nullptr,
192 aForceUpdate);
195 LinkStyle* LinkStyle::FromNode(Element& aElement) {
196 nsAtom* name = aElement.NodeInfo()->NameAtom();
197 if (name == nsGkAtoms::link) {
198 MOZ_ASSERT(aElement.IsHTMLElement() == !!aElement.AsLinkStyle());
199 return aElement.IsHTMLElement() ? static_cast<HTMLLinkElement*>(&aElement)
200 : nullptr;
202 if (name == nsGkAtoms::style) {
203 if (aElement.IsHTMLElement()) {
204 MOZ_ASSERT(aElement.AsLinkStyle());
205 return static_cast<HTMLStyleElement*>(&aElement);
207 if (aElement.IsSVGElement()) {
208 MOZ_ASSERT(aElement.AsLinkStyle());
209 return static_cast<SVGStyleElement*>(&aElement);
212 MOZ_ASSERT(!aElement.AsLinkStyle());
213 return nullptr;
216 void LinkStyle::BindToTree() {
217 if (mUpdatesEnabled) {
218 nsContentUtils::AddScriptRunner(NS_NewRunnableFunction(
219 "LinkStyle::BindToTree",
220 [this, pin = RefPtr{&AsContent()}] { UpdateStyleSheetInternal(); }));
224 Result<LinkStyle::Update, nsresult> LinkStyle::DoUpdateStyleSheet(
225 Document* aOldDocument, ShadowRoot* aOldShadowRoot,
226 nsICSSLoaderObserver* aObserver, ForceUpdate aForceUpdate) {
227 nsIContent& thisContent = AsContent();
228 if (thisContent.IsInSVGUseShadowTree()) {
229 // Stylesheets in <use>-cloned subtrees are disabled until we figure out
230 // how they should behave.
231 return Update{};
234 if (mStyleSheet && (aOldDocument || aOldShadowRoot)) {
235 MOZ_ASSERT(!(aOldDocument && aOldShadowRoot),
236 "ShadowRoot content is never in document, thus "
237 "there should not be a old document and old "
238 "ShadowRoot simultaneously.");
240 // We're removing the link element from the document or shadow tree, unload
241 // the stylesheet.
243 // We want to do this even if updates are disabled, since otherwise a sheet
244 // with a stale linking element pointer will be hanging around -- not good!
245 if (mStyleSheet->IsComplete()) {
246 if (aOldShadowRoot) {
247 aOldShadowRoot->RemoveStyleSheet(*mStyleSheet);
248 } else {
249 aOldDocument->RemoveStyleSheet(*mStyleSheet);
253 SetStyleSheet(nullptr);
256 Document* doc = thisContent.GetComposedDoc();
258 // Loader could be null during unlink, see bug 1425866.
259 if (!doc || !doc->CSSLoader() || !doc->CSSLoader()->GetEnabled()) {
260 return Update{};
263 // When static documents are created, stylesheets are cloned manually.
264 if (!mUpdatesEnabled || doc->IsStaticDocument()) {
265 return Update{};
268 Maybe<SheetInfo> info = GetStyleSheetInfo();
269 if (aForceUpdate == ForceUpdate::No && mStyleSheet && info &&
270 !info->mIsInline && info->mURI) {
271 if (nsIURI* oldURI = mStyleSheet->GetSheetURI()) {
272 bool equal;
273 nsresult rv = oldURI->Equals(info->mURI, &equal);
274 if (NS_SUCCEEDED(rv) && equal) {
275 return Update{};
280 if (mStyleSheet) {
281 if (mStyleSheet->IsComplete()) {
282 if (thisContent.IsInShadowTree()) {
283 ShadowRoot* containingShadow = thisContent.GetContainingShadow();
284 // Could be null only during unlink.
285 if (MOZ_LIKELY(containingShadow)) {
286 containingShadow->RemoveStyleSheet(*mStyleSheet);
288 } else {
289 doc->RemoveStyleSheet(*mStyleSheet);
293 SetStyleSheet(nullptr);
296 if (!info) {
297 return Update{};
300 if (!info->mURI && !info->mIsInline) {
301 // If href is empty and this is not inline style then just bail
302 return Update{};
305 if (info->mIsInline) {
306 nsAutoString text;
307 if (!nsContentUtils::GetNodeTextContent(&thisContent, false, text,
308 fallible)) {
309 return Err(NS_ERROR_OUT_OF_MEMORY);
312 MOZ_ASSERT(thisContent.NodeInfo()->NameAtom() != nsGkAtoms::link,
313 "<link> is not 'inline', and needs different CSP checks");
314 MOZ_ASSERT(thisContent.IsElement());
315 nsresult rv = NS_OK;
316 if (!nsStyleUtil::CSPAllowsInlineStyle(
317 thisContent.AsElement(), doc, info->mTriggeringPrincipal,
318 mLineNumber, mColumnNumber, text, &rv)) {
319 if (NS_FAILED(rv)) {
320 return Err(rv);
322 return Update{};
325 // Parse the style sheet.
326 return doc->CSSLoader()->LoadInlineStyle(*info, text, aObserver);
328 if (thisContent.IsElement()) {
329 nsAutoString integrity;
330 thisContent.AsElement()->GetAttr(nsGkAtoms::integrity, integrity);
331 if (!integrity.IsEmpty()) {
332 MOZ_LOG(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug,
333 ("LinkStyle::DoUpdateStyleSheet, integrity=%s",
334 NS_ConvertUTF16toUTF8(integrity).get()));
337 auto resultOrError = doc->CSSLoader()->LoadStyleLink(*info, aObserver);
338 if (resultOrError.isErr()) {
339 // Don't propagate LoadStyleLink() errors further than this, since some
340 // consumers (e.g. nsXMLContentSink) will completely abort on innocuous
341 // things like a stylesheet load being blocked by the security system.
342 return Update{};
344 return resultOrError;
347 } // namespace mozilla::dom