1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* A base class which implements nsIStyleSheetLinkingElement and can
* be subclassed by various content nodes that want to load
* stylesheets (<style>, <link>, processing instructions, etc).
*/
#include "mozilla/dom/LinkStyle.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
#include "mozilla/css/Loader.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/FragmentOrElement.h"
#include "mozilla/dom/HTMLLinkElement.h"
#include "mozilla/dom/HTMLStyleElement.h"
#include "mozilla/dom/SRILogHelper.h"
#include "mozilla/dom/SVGStyleElement.h"
#include "mozilla/dom/ShadowRoot.h"
#include "nsCRT.h"
#include "nsContentUtils.h"
#include "nsIContent.h"
#include "nsQueryObject.h"
#include "nsStyleUtil.h"
#include "nsUnicharInputStream.h"
#include "nsUnicharUtils.h"
#include "nsXPCOMCIDInternal.h"
namespace mozilla::dom {
LinkStyle::SheetInfo::SheetInfo(
const Document& aDocument, nsIContent* aContent,
already_AddRefed<nsIURI> aURI,
already_AddRefed<nsIPrincipal> aTriggeringPrincipal,
already_AddRefed<nsIReferrerInfo> aReferrerInfo,
mozilla::CORSMode aCORSMode, const nsAString& aTitle,
const nsAString& aMedia, const nsAString& aIntegrity,
const nsAString& aNonce, HasAlternateRel aHasAlternateRel,
IsInline aIsInline, IsExplicitlyEnabled aIsExplicitlyEnabled,
FetchPriority aFetchPriority)
: mContent(aContent),
mURI(aURI),
mTriggeringPrincipal(aTriggeringPrincipal),
mReferrerInfo(aReferrerInfo),
mCORSMode(aCORSMode),
mTitle(aTitle),
mMedia(aMedia),
mIntegrity(aIntegrity),
mNonce(aNonce),
mFetchPriority(aFetchPriority),
mHasAlternateRel(aHasAlternateRel == HasAlternateRel::Yes),
mIsInline(aIsInline == IsInline::Yes),
mIsExplicitlyEnabled(aIsExplicitlyEnabled) {
MOZ_ASSERT(!mIsInline || aContent);
MOZ_ASSERT_IF(aContent, aContent->OwnerDoc() == &aDocument);
MOZ_ASSERT(mReferrerInfo);
MOZ_ASSERT(mIntegrity.IsEmpty() || !mIsInline,
"Integrity only applies to <link>");
}
LinkStyle::SheetInfo::~SheetInfo() = default;
LinkStyle::LinkStyle() = default;
LinkStyle::~LinkStyle() { LinkStyle::SetStyleSheet(nullptr); }
StyleSheet* LinkStyle::GetSheetForBindings() const {
if (mStyleSheet && mStyleSheet->IsComplete()) {
return mStyleSheet;
}
return nullptr;
}
void LinkStyle::GetTitleAndMediaForElement(const Element& aSelf,
nsString& aTitle, nsString& aMedia) {
// Only honor title as stylesheet name for elements in the document (that is,
// ignore for Shadow DOM), per [1] and [2]. See [3].
//
// [1]: https://html.spec.whatwg.org/#attr-link-title
// [2]: https://html.spec.whatwg.org/#attr-style-title
// [3]: https://github.com/w3c/webcomponents/issues/535
if (aSelf.IsInUncomposedDoc()) {
aSelf.GetAttr(nsGkAtoms::title, aTitle);
aTitle.CompressWhitespace();
}
aSelf.GetAttr(nsGkAtoms::media, aMedia);
// The HTML5 spec is formulated in terms of the CSSOM spec, which specifies
// that media queries should be ASCII lowercased during serialization.
//
// FIXME(emilio): How does it matter? This is going to be parsed anyway, CSS
// should take care of serializing it properly.
nsContentUtils::ASCIIToLower(aMedia);
}
bool LinkStyle::IsCSSMimeTypeAttributeForStyleElement(const Element& aSelf) {
// Per
// https://html.spec.whatwg.org/multipage/semantics.html#the-style-element:update-a-style-block
// step 4, for style elements we should only accept empty and "text/css" type
// attribute values.
nsAutoString type;
aSelf.GetAttr(nsGkAtoms::type, type);
return type.IsEmpty() || type.LowerCaseEqualsLiteral("text/css");
}
void LinkStyle::Unlink() { LinkStyle::SetStyleSheet(nullptr); }
void LinkStyle::Traverse(nsCycleCollectionTraversalCallback& cb) {
LinkStyle* tmp = this;
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheet);
}
void LinkStyle::SetStyleSheet(StyleSheet* aStyleSheet) {
if (mStyleSheet) {
mStyleSheet->SetOwningNode(nullptr);
}
mStyleSheet = aStyleSheet;
if (mStyleSheet) {
mStyleSheet->SetOwningNode(&AsContent());
}
}
void LinkStyle::GetCharset(nsAString& aCharset) { aCharset.Truncate(); }
static uint32_t ToLinkMask(const nsAString& aLink) {
// Keep this in sync with sSupportedRelValues in HTMLLinkElement.cpp
uint32_t mask = 0;
if (aLink.EqualsLiteral("prefetch")) {
mask = LinkStyle::ePREFETCH;
} else if (aLink.EqualsLiteral("dns-prefetch")) {
mask = LinkStyle::eDNS_PREFETCH;
} else if (aLink.EqualsLiteral("stylesheet")) {
mask = LinkStyle::eSTYLESHEET;
} else if (aLink.EqualsLiteral("next")) {
mask = LinkStyle::eNEXT;
} else if (aLink.EqualsLiteral("alternate")) {
mask = LinkStyle::eALTERNATE;
} else if (aLink.EqualsLiteral("preconnect")) {
mask = LinkStyle::ePRECONNECT;
} else if (aLink.EqualsLiteral("preload")) {
mask = LinkStyle::ePRELOAD;
} else if (aLink.EqualsLiteral("modulepreload")) {
mask = LinkStyle::eMODULE_PRELOAD;
}
return mask;
}
uint32_t LinkStyle::ParseLinkTypes(const nsAString& aTypes) {
uint32_t linkMask = 0;
nsAString::const_iterator start, done;
aTypes.BeginReading(start);
aTypes.EndReading(done);
if (start == done) return linkMask;
nsAString::const_iterator current(start);
bool inString = !nsContentUtils::IsHTMLWhitespace(*current);
nsAutoString subString;
while (current != done) {
if (nsContentUtils::IsHTMLWhitespace(*current)) {
if (inString) {
nsContentUtils::ASCIIToLower(Substring(start, current), subString);
linkMask |= ToLinkMask(subString);
inString = false;
}
} else {
if (!inString) {
start = current;
inString = true;
}
}
++current;
}
if (inString) {
nsContentUtils::ASCIIToLower(Substring(start, current), subString);
linkMask |= ToLinkMask(subString);
}
return linkMask;
}
Result<LinkStyle::Update, nsresult> LinkStyle::UpdateStyleSheetInternal(
Document* aOldDocument, ShadowRoot* aOldShadowRoot,
ForceUpdate aForceUpdate) {
return DoUpdateStyleSheet(aOldDocument, aOldShadowRoot, nullptr,
aForceUpdate);
}
LinkStyle* LinkStyle::FromNode(Element& aElement) {
nsAtom* name = aElement.NodeInfo()->NameAtom();
if (name == nsGkAtoms::link) {
MOZ_ASSERT(aElement.IsHTMLElement() == !!aElement.AsLinkStyle());
return aElement.IsHTMLElement() ? static_cast<HTMLLinkElement*>(&aElement)
: nullptr;
}
if (name == nsGkAtoms::style) {
if (aElement.IsHTMLElement()) {
MOZ_ASSERT(aElement.AsLinkStyle());
return static_cast<HTMLStyleElement*>(&aElement);
}
if (aElement.IsSVGElement()) {
MOZ_ASSERT(aElement.AsLinkStyle());
return static_cast<SVGStyleElement*>(&aElement);
}
}
MOZ_ASSERT(!aElement.AsLinkStyle());
return nullptr;
}
void LinkStyle::BindToTree() {
if (mUpdatesEnabled) {
nsContentUtils::AddScriptRunner(NS_NewRunnableFunction(
"LinkStyle::BindToTree",
[this, pin = RefPtr{&AsContent()}] { UpdateStyleSheetInternal(); }));
}
}
Result<LinkStyle::Update, nsresult> LinkStyle::DoUpdateStyleSheet(
Document* aOldDocument, ShadowRoot* aOldShadowRoot,
nsICSSLoaderObserver* aObserver, ForceUpdate aForceUpdate) {
nsIContent& thisContent = AsContent();
if (thisContent.IsInSVGUseShadowTree()) {
// Stylesheets in <use>-cloned subtrees are disabled until we figure out
// how they should behave.
return Update{};
}
if (mStyleSheet && (aOldDocument || aOldShadowRoot)) {
MOZ_ASSERT(!(aOldDocument && aOldShadowRoot),
"ShadowRoot content is never in document, thus "
"there should not be a old document and old "
"ShadowRoot simultaneously.");
// We're removing the link element from the document or shadow tree, unload
// the stylesheet.
//
// We want to do this even if updates are disabled, since otherwise a sheet
// with a stale linking element pointer will be hanging around -- not good!
if (mStyleSheet->IsComplete()) {
if (aOldShadowRoot) {
aOldShadowRoot->RemoveStyleSheet(*mStyleSheet);
} else {
aOldDocument->RemoveStyleSheet(*mStyleSheet);
}
}
SetStyleSheet(nullptr);
}
Document* doc = thisContent.GetComposedDoc();
// Loader could be null during unlink, see bug 1425866.
// ... No need to update if updating is disabled, as well.
if (!doc || !doc->CSSLoader() || !doc->CSSLoader()->GetEnabled() ||
!mUpdatesEnabled) {
return Update{};
}
// When static documents are created, we need to finish up cloning
// the stylesheet (See documentation for MaybeFinishCopyStyleSheet).
if (doc->IsStaticDocument()) {
MaybeFinishCopyStyleSheet(doc);
return Update{};
}
Maybe<SheetInfo> info = GetStyleSheetInfo();
if (aForceUpdate == ForceUpdate::No && mStyleSheet && info &&
!info->mIsInline && info->mURI) {
if (nsIURI* oldURI = mStyleSheet->GetSheetURI()) {
bool equal;
nsresult rv = oldURI->Equals(info->mURI, &equal);
if (NS_SUCCEEDED(rv) && equal) {
return Update{};
}
}
}
if (mStyleSheet) {
if (mStyleSheet->IsComplete()) {
if (thisContent.IsInShadowTree()) {
ShadowRoot* containingShadow = thisContent.GetContainingShadow();
// Could be null only during unlink.
if (MOZ_LIKELY(containingShadow)) {
containingShadow->RemoveStyleSheet(*mStyleSheet);
}
} else {
doc->RemoveStyleSheet(*mStyleSheet);
}
}
SetStyleSheet(nullptr);
}
if (!info) {
return Update{};
}
if (!info->mURI && !info->mIsInline) {
// If href is empty and this is not inline style then just bail
return Update{};
}
if (info->mIsInline) {
nsAutoString text;
if (!nsContentUtils::GetNodeTextContent(&thisContent, false, text,
fallible)) {
return Err(NS_ERROR_OUT_OF_MEMORY);
}
MOZ_ASSERT(thisContent.NodeInfo()->NameAtom() != nsGkAtoms::link,
"<link> is not 'inline', and needs different CSP checks");
MOZ_ASSERT(thisContent.IsElement());
nsresult rv = NS_OK;
if (!nsStyleUtil::CSPAllowsInlineStyle(
thisContent.AsElement(), doc, info->mTriggeringPrincipal,
mLineNumber, mColumnNumber, text, &rv)) {
if (NS_FAILED(rv)) {
return Err(rv);
}
return Update{};
}
// Parse the style sheet.
return doc->CSSLoader()->LoadInlineStyle(*info, text, aObserver);
}
if (thisContent.IsElement()) {
nsAutoString integrity;
thisContent.AsElement()->GetAttr(nsGkAtoms::integrity, integrity);
if (!integrity.IsEmpty()) {
MOZ_LOG(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug,
("LinkStyle::DoUpdateStyleSheet, integrity=%s",
NS_ConvertUTF16toUTF8(integrity).get()));
}
}
auto resultOrError = doc->CSSLoader()->LoadStyleLink(*info, aObserver);
if (resultOrError.isErr()) {
// Don't propagate LoadStyleLink() errors further than this, since some
// consumers (e.g. nsXMLContentSink) will completely abort on innocuous
// things like a stylesheet load being blocked by the security system.
return Update{};
}
return resultOrError;
}
void LinkStyle::MaybeStartCopyStyleSheetTo(LinkStyle* aDest,
Document* aDoc) const {
MOZ_ASSERT(aDoc, "Copying to null Document?");
if (!aDoc->IsStaticDocument() || !mStyleSheet ||
!mStyleSheet->IsApplicable()) {
return;
}
// We don't yet if know we're in shadow root, so the only thing we can do is
// to keep an incomplete clone. Namely, the sheet does not have knowledge of
// its owning node and which document or shadow root it belongs to.
aDest->mStyleSheet = mStyleSheet->Clone(nullptr, nullptr);
}
void LinkStyle::MaybeFinishCopyStyleSheet(Document* aDocument) {
if (!mStyleSheet) {
return;
}
auto& thisContent = AsContent();
// Are we in the holdover copy state?
if (mStyleSheet->GetOwnerNode() == &thisContent) {
return;
}
MOZ_ASSERT(aDocument->IsStaticDocument(),
"Copying stylesheet over into a non-static document?");
DocumentOrShadowRoot* root = aDocument;
auto* shadowRoot = thisContent.GetContainingShadow();
if (shadowRoot) {
root = shadowRoot;
if (MOZ_UNLIKELY(!root)) {
// This can happen during unlink - just drop the holdover stylesheet.
mStyleSheet = nullptr;
return;
}
}
RefPtr<StyleSheet> sheet = mStyleSheet->Clone(nullptr, root);
SetStyleSheet(sheet.get());
aDocument->CSSLoader()->InsertSheetInTree(*sheet);
}
} // namespace mozilla::dom
|