-
Notifications
You must be signed in to change notification settings - Fork 54
/
Loader.cpp
2462 lines (2124 loc) · 85.6 KB
/
Loader.cpp
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- 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/. */
/* loading of CSS style sheets using the network APIs */
#include "mozilla/css/Loader.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/SRILogHelper.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/Logging.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/SystemGroup.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/URLPreloader.h"
#include "nsIRunnable.h"
#include "nsITimedChannel.h"
#include "nsSyncLoadService.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsIURI.h"
#include "nsNetUtil.h"
#include "nsIProtocolHandler.h"
#include "nsContentUtils.h"
#include "nsIScriptSecurityManager.h"
#include "nsContentPolicyUtils.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIClassOfService.h"
#include "nsIScriptError.h"
#include "nsMimeTypes.h"
#include "nsIStyleSheetLinkingElement.h"
#include "nsICSSLoaderObserver.h"
#include "nsThreadUtils.h"
#include "nsGkAtoms.h"
#include "nsIThreadInternal.h"
#include "nsINetworkPredictor.h"
#include "nsStringStream.h"
#include "mozilla/dom/MediaList.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/URL.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
#include "mozilla/ConsoleReportCollector.h"
#include "mozilla/ServoUtils.h"
#include "mozilla/css/StreamLoader.h"
#ifdef MOZ_XUL
#include "nsXULPrototypeCache.h"
#endif
#include "nsError.h"
#include "nsIContentSecurityPolicy.h"
#include "mozilla/dom/SRICheck.h"
#include "mozilla/Encoding.h"
using namespace mozilla::dom;
// 1024 bytes is specified in https://drafts.csswg.org/css-syntax/
#define SNIFFING_BUFFER_SIZE 1024
/**
* OVERALL ARCHITECTURE
*
* The CSS Loader gets requests to load various sorts of style sheets:
* inline style from <style> elements, linked style, @import-ed child
* sheets, non-document sheets. The loader handles the following tasks:
* 1) Creation of the actual style sheet objects: CreateSheet()
* 2) setting of the right media, title, enabled state, etc on the
* sheet: PrepareSheet()
* 3) Insertion of the sheet in the proper cascade order:
* InsertSheetInTree() and InsertChildSheet()
* 4) Load of the sheet: LoadSheet() including security checks
* 5) Parsing of the sheet: ParseSheet()
* 6) Cleanup: SheetComplete()
*
* The detailed documentation for these functions is found with the
* function implementations.
*
* The following helper object is used:
* SheetLoadData -- a small class that is used to store all the
* information needed for the loading of a sheet;
* this class handles listening for the stream
* loader completion and also handles charset
* determination.
*/
static mozilla::LazyLogModule sCssLoaderLog("nsCSSLoader");
static mozilla::LazyLogModule gSriPRLog("SRI");
#define LOG_ERROR(args) MOZ_LOG(sCssLoaderLog, mozilla::LogLevel::Error, args)
#define LOG_WARN(args) MOZ_LOG(sCssLoaderLog, mozilla::LogLevel::Warning, args)
#define LOG_DEBUG(args) MOZ_LOG(sCssLoaderLog, mozilla::LogLevel::Debug, args)
#define LOG(args) LOG_DEBUG(args)
#define LOG_ERROR_ENABLED() \
MOZ_LOG_TEST(sCssLoaderLog, mozilla::LogLevel::Error)
#define LOG_WARN_ENABLED() \
MOZ_LOG_TEST(sCssLoaderLog, mozilla::LogLevel::Warning)
#define LOG_DEBUG_ENABLED() \
MOZ_LOG_TEST(sCssLoaderLog, mozilla::LogLevel::Debug)
#define LOG_ENABLED() LOG_DEBUG_ENABLED()
#define LOG_URI(format, uri) \
PR_BEGIN_MACRO \
NS_ASSERTION(uri, "Logging null uri"); \
if (LOG_ENABLED()) { \
LOG((format, uri->GetSpecOrDefault().get())); \
} \
PR_END_MACRO
// And some convenience strings...
static const char* const gStateStrings[] = {
"eSheetStateUnknown", "eSheetNeedsParser", "eSheetPending", "eSheetLoading",
"eSheetComplete"};
namespace mozilla {
URIPrincipalReferrerPolicyAndCORSModeHashKey::
URIPrincipalReferrerPolicyAndCORSModeHashKey(css::SheetLoadData* aLoadData)
: nsURIHashKey(aLoadData->mURI),
mPrincipal(aLoadData->mLoaderPrincipal),
mCORSMode(aLoadData->mSheet->GetCORSMode()),
mReferrerPolicy(aLoadData->mSheet->GetReferrerPolicy()) {
MOZ_COUNT_CTOR(URIPrincipalReferrerPolicyAndCORSModeHashKey);
}
} // namespace mozilla
namespace mozilla {
namespace css {
/********************************
* SheetLoadData implementation *
********************************/
NS_IMPL_ISUPPORTS(SheetLoadData, nsIRunnable, nsIThreadObserver)
SheetLoadData::SheetLoadData(Loader* aLoader, const nsAString& aTitle,
nsIURI* aURI, StyleSheet* aSheet, bool aSyncLoad,
nsIStyleSheetLinkingElement* aOwningElement,
IsAlternate aIsAlternate,
MediaMatched aMediaMatches,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal,
nsINode* aRequestingNode)
: mLoader(aLoader),
mTitle(aTitle),
mEncoding(nullptr),
mURI(aURI),
mLineNumber(1),
mSheet(aSheet),
mNext(nullptr),
mPendingChildren(0),
mSyncLoad(aSyncLoad),
mIsNonDocumentSheet(false),
mIsLoading(false),
mIsBeingParsed(false),
mIsCancelled(false),
mMustNotify(false),
mWasAlternate(aIsAlternate == IsAlternate::Yes),
mMediaMatched(aMediaMatches == MediaMatched::Yes),
mUseSystemPrincipal(false),
mSheetAlreadyComplete(false),
mIsCrossOriginNoCORS(false),
mBlockResourceTiming(false),
mLoadFailed(false),
mOwningElement(aOwningElement),
mObserver(aObserver),
mLoaderPrincipal(aLoaderPrincipal),
mRequestingNode(aRequestingNode),
mPreloadEncoding(nullptr) {
MOZ_ASSERT(mLoader, "Must have a loader!");
}
SheetLoadData::SheetLoadData(Loader* aLoader, nsIURI* aURI, StyleSheet* aSheet,
SheetLoadData* aParentData,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal,
nsINode* aRequestingNode)
: mLoader(aLoader),
mEncoding(nullptr),
mURI(aURI),
mLineNumber(1),
mSheet(aSheet),
mNext(nullptr),
mParentData(aParentData),
mPendingChildren(0),
mSyncLoad(false),
mIsNonDocumentSheet(false),
mIsLoading(false),
mIsBeingParsed(false),
mIsCancelled(false),
mMustNotify(false),
mWasAlternate(false),
mMediaMatched(true),
mUseSystemPrincipal(false),
mSheetAlreadyComplete(false),
mIsCrossOriginNoCORS(false),
mBlockResourceTiming(false),
mLoadFailed(false),
mOwningElement(nullptr),
mObserver(aObserver),
mLoaderPrincipal(aLoaderPrincipal),
mRequestingNode(aRequestingNode),
mPreloadEncoding(nullptr) {
MOZ_ASSERT(mLoader, "Must have a loader!");
if (mParentData) {
mSyncLoad = mParentData->mSyncLoad;
mIsNonDocumentSheet = mParentData->mIsNonDocumentSheet;
mUseSystemPrincipal = mParentData->mUseSystemPrincipal;
++(mParentData->mPendingChildren);
}
MOZ_ASSERT(!mUseSystemPrincipal || mSyncLoad,
"Shouldn't use system principal for async loads");
}
SheetLoadData::SheetLoadData(Loader* aLoader, nsIURI* aURI, StyleSheet* aSheet,
bool aSyncLoad, bool aUseSystemPrincipal,
const Encoding* aPreloadEncoding,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal,
nsINode* aRequestingNode)
: mLoader(aLoader),
mEncoding(nullptr),
mURI(aURI),
mLineNumber(1),
mSheet(aSheet),
mNext(nullptr),
mPendingChildren(0),
mSyncLoad(aSyncLoad),
mIsNonDocumentSheet(true),
mIsLoading(false),
mIsBeingParsed(false),
mIsCancelled(false),
mMustNotify(false),
mWasAlternate(false),
mMediaMatched(true),
mUseSystemPrincipal(aUseSystemPrincipal),
mSheetAlreadyComplete(false),
mIsCrossOriginNoCORS(false),
mBlockResourceTiming(false),
mLoadFailed(false),
mOwningElement(nullptr),
mObserver(aObserver),
mLoaderPrincipal(aLoaderPrincipal),
mRequestingNode(aRequestingNode),
mPreloadEncoding(aPreloadEncoding) {
MOZ_ASSERT(mLoader, "Must have a loader!");
MOZ_ASSERT(!mUseSystemPrincipal || mSyncLoad,
"Shouldn't use system principal for async loads");
}
SheetLoadData::~SheetLoadData() {
NS_CSS_NS_RELEASE_LIST_MEMBER(SheetLoadData, this, mNext);
}
NS_IMETHODIMP
SheetLoadData::Run() {
mLoader->HandleLoadEvent(this);
return NS_OK;
}
NS_IMETHODIMP
SheetLoadData::OnDispatchedEvent() { return NS_OK; }
NS_IMETHODIMP
SheetLoadData::OnProcessNextEvent(nsIThreadInternal* aThread, bool aMayWait) {
// XXXkhuey this is insane!
// We want to fire our load even before or after event processing,
// whichever comes first.
FireLoadEvent(aThread);
return NS_OK;
}
NS_IMETHODIMP
SheetLoadData::AfterProcessNextEvent(nsIThreadInternal* aThread,
bool aEventWasProcessed) {
// XXXkhuey this too!
// We want to fire our load even before or after event processing,
// whichever comes first.
FireLoadEvent(aThread);
return NS_OK;
}
void SheetLoadData::FireLoadEvent(nsIThreadInternal* aThread) {
// First remove ourselves as a thread observer. But we need to keep
// ourselves alive while doing that!
RefPtr<SheetLoadData> kungFuDeathGrip(this);
aThread->RemoveObserver(this);
// Now fire the event
nsCOMPtr<nsINode> node = do_QueryInterface(mOwningElement);
NS_ASSERTION(node, "How did that happen???");
nsContentUtils::DispatchTrustedEvent(
node->OwnerDoc(), node,
mLoadFailed ? NS_LITERAL_STRING("error") : NS_LITERAL_STRING("load"),
CanBubble::eNo, Cancelable::eNo);
// And unblock onload
mLoader->UnblockOnload(true);
}
void SheetLoadData::ScheduleLoadEventIfNeeded() {
if (!mOwningElement) {
return;
}
nsCOMPtr<nsIThread> thread = do_GetCurrentThread();
nsCOMPtr<nsIThreadInternal> internalThread = do_QueryInterface(thread);
if (NS_SUCCEEDED(internalThread->AddObserver(this))) {
// Make sure to block onload here
mLoader->BlockOnload();
}
}
/*********************
* Style sheet reuse *
*********************/
bool LoaderReusableStyleSheets::FindReusableStyleSheet(
nsIURI* aURL, RefPtr<StyleSheet>& aResult) {
MOZ_ASSERT(aURL);
for (size_t i = mReusableSheets.Length(); i > 0; --i) {
size_t index = i - 1;
bool sameURI;
MOZ_ASSERT(mReusableSheets[index]->GetOriginalURI());
nsresult rv =
aURL->Equals(mReusableSheets[index]->GetOriginalURI(), &sameURI);
if (!NS_FAILED(rv) && sameURI) {
aResult = mReusableSheets[index];
mReusableSheets.RemoveElementAt(index);
return true;
}
}
return false;
}
/*************************
* Loader Implementation *
*************************/
Loader::Loader()
: mDocument(nullptr),
mDatasToNotifyOn(0),
mCompatMode(eCompatibility_FullStandards),
mEnabled(true),
mReporter(new ConsoleReportCollector())
#ifdef DEBUG
,
mSyncCallback(false)
#endif
{
}
Loader::Loader(DocGroup* aDocGroup) : Loader() { mDocGroup = aDocGroup; }
Loader::Loader(nsIDocument* aDocument) : Loader() {
mDocument = aDocument;
MOZ_ASSERT(mDocument, "We should get a valid document from the caller!");
}
Loader::~Loader() {
NS_ASSERTION(!mSheets || mSheets->mLoadingDatas.Count() == 0,
"How did we get destroyed when there are loading data?");
NS_ASSERTION(!mSheets || mSheets->mPendingDatas.Count() == 0,
"How did we get destroyed when there are pending data?");
// Note: no real need to revoke our stylesheet loaded events -- they
// hold strong references to us, so if we're going away that means
// they're all done.
}
void Loader::DropDocumentReference(void) {
mDocument = nullptr;
// Flush out pending datas just so we don't leak by accident. These
// loads should short-circuit through the mDocument check in
// LoadSheet and just end up in SheetComplete immediately
if (mSheets) {
StartDeferredLoads();
}
}
void Loader::DocumentStyleSheetSetChanged() {
MOZ_ASSERT(mDocument);
// start any pending alternates that aren't alternates anymore
if (!mSheets) {
return;
}
LoadDataArray arr(mSheets->mPendingDatas.Count());
for (auto iter = mSheets->mPendingDatas.Iter(); !iter.Done(); iter.Next()) {
SheetLoadData* data = iter.Data();
MOZ_ASSERT(data, "Must have a data");
// Note that we don't want to affect what the selected style set is, so
// use true for aHasAlternateRel.
auto isAlternate = data->mLoader->IsAlternateSheet(data->mTitle, true);
if (isAlternate == IsAlternate::No) {
arr.AppendElement(data);
iter.Remove();
}
}
mDatasToNotifyOn += arr.Length();
for (uint32_t i = 0; i < arr.Length(); ++i) {
--mDatasToNotifyOn;
LoadSheet(arr[i], eSheetNeedsParser, false);
}
}
static const char kCharsetSym[] = "@charset \"";
static bool GetCharsetFromData(const char* aStyleSheetData,
uint32_t aDataLength, nsACString& aCharset) {
aCharset.Truncate();
if (aDataLength <= sizeof(kCharsetSym) - 1) return false;
if (strncmp(aStyleSheetData, kCharsetSym, sizeof(kCharsetSym) - 1)) {
return false;
}
for (uint32_t i = sizeof(kCharsetSym) - 1; i < aDataLength; ++i) {
char c = aStyleSheetData[i];
if (c == '"') {
++i;
if (i < aDataLength && aStyleSheetData[i] == ';') {
return true;
}
// fail
break;
}
aCharset.Append(c);
}
// Did not see end quote or semicolon
aCharset.Truncate();
return false;
}
NotNull<const Encoding*> SheetLoadData::DetermineNonBOMEncoding(
nsACString const& aSegment, nsIChannel* aChannel) {
const Encoding* encoding;
nsAutoCString label;
// Check HTTP
if (aChannel && NS_SUCCEEDED(aChannel->GetContentCharset(label))) {
encoding = Encoding::ForLabel(label);
if (encoding) {
return WrapNotNull(encoding);
}
}
// Check @charset
auto sniffingLength = aSegment.Length();
if (sniffingLength > SNIFFING_BUFFER_SIZE) {
sniffingLength = SNIFFING_BUFFER_SIZE;
}
if (GetCharsetFromData(aSegment.BeginReading(), sniffingLength, label)) {
encoding = Encoding::ForLabel(label);
if (encoding == UTF_16BE_ENCODING || encoding == UTF_16LE_ENCODING) {
return UTF_8_ENCODING;
}
if (encoding) {
return WrapNotNull(encoding);
}
}
// Now try the charset on the <link> or processing instruction
// that loaded us
if (mOwningElement) {
nsAutoString label16;
mOwningElement->GetCharset(label16);
encoding = Encoding::ForLabel(label16);
if (encoding) {
return WrapNotNull(encoding);
}
}
// In the preload case, the value of the charset attribute on <link> comes
// in via mPreloadEncoding instead.
if (mPreloadEncoding) {
return WrapNotNull(mPreloadEncoding);
}
// Try charset from the parent stylesheet.
if (mParentData) {
encoding = mParentData->mEncoding;
if (encoding) {
return WrapNotNull(encoding);
}
}
if (mLoader->mDocument) {
// Use the document charset.
return mLoader->mDocument->GetDocumentCharacterSet();
}
return UTF_8_ENCODING;
}
already_AddRefed<nsIURI> SheetLoadData::GetReferrerURI() {
nsCOMPtr<nsIURI> uri;
if (mParentData) uri = mParentData->mSheet->GetSheetURI();
if (!uri && mLoader->mDocument) uri = mLoader->mDocument->GetDocumentURI();
return uri.forget();
}
void SheetLoadData::SetReferrerPolicyFromHeader(nsIChannel* aChannel) {
net::ReferrerPolicy policy =
nsContentUtils::GetReferrerPolicyFromChannel(aChannel);
if (policy == net::RP_Unset || policy == mSheet->GetReferrerPolicy()) {
return;
}
URIPrincipalReferrerPolicyAndCORSModeHashKey oldKey(
mURI, mLoaderPrincipal, mSheet->GetCORSMode(),
mSheet->GetReferrerPolicy());
mSheet->SetReferrerPolicy(policy);
mLoader->UpdateLoadingData(&oldKey, this);
}
static nsresult VerifySheetIntegrity(const SRIMetadata& aMetadata,
nsIChannel* aChannel,
const nsACString& aFirst,
const nsACString& aSecond,
const nsACString& aSourceFileURI,
nsIConsoleReportCollector* aReporter) {
NS_ENSURE_ARG_POINTER(aReporter);
if (MOZ_LOG_TEST(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug)) {
nsAutoCString requestURL;
nsCOMPtr<nsIURI> originalURI;
if (aChannel &&
NS_SUCCEEDED(aChannel->GetOriginalURI(getter_AddRefs(originalURI))) &&
originalURI) {
originalURI->GetAsciiSpec(requestURL);
}
MOZ_LOG(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug,
("VerifySheetIntegrity (unichar stream)"));
}
SRICheckDataVerifier verifier(aMetadata, aSourceFileURI, aReporter);
nsresult rv =
verifier.Update(aFirst.Length(), (const uint8_t*)aFirst.BeginReading());
NS_ENSURE_SUCCESS(rv, rv);
rv =
verifier.Update(aSecond.Length(), (const uint8_t*)aSecond.BeginReading());
NS_ENSURE_SUCCESS(rv, rv);
return verifier.Verify(aMetadata, aChannel, aSourceFileURI, aReporter);
}
/*
* Stream completion code shared by Stylo and the old style system.
*
* Here we need to check that the load did not give us an http error
* page and check the mimetype on the channel to make sure we're not
* loading non-text/css data in standards mode.
*/
nsresult SheetLoadData::VerifySheetReadyToParse(nsresult aStatus,
const nsACString& aBytes1,
const nsACString& aBytes2,
nsIChannel* aChannel) {
LOG(("SheetLoadData::VerifySheetReadyToParse"));
NS_ASSERTION(!mLoader->mSyncCallback, "Synchronous callback from necko");
if (mIsCancelled) {
// Just return. Don't call SheetComplete -- it's already been
// called and calling it again will lead to an extra NS_RELEASE on
// this data and a likely crash.
return NS_OK;
}
if (!mLoader->mDocument && !mIsNonDocumentSheet) {
// Sorry, we don't care about this load anymore
LOG_WARN((" No document and not non-document sheet; dropping load"));
mLoader->SheetComplete(this, NS_BINDING_ABORTED);
return NS_OK;
}
if (NS_FAILED(aStatus)) {
LOG_WARN(
(" Load failed: status 0x%" PRIx32, static_cast<uint32_t>(aStatus)));
// Handle sheet not loading error because source was a tracking URL.
// We make a note of this sheet node by including it in a dedicated
// array of blocked tracking nodes under its parent document.
//
// Multiple sheet load instances might be tied to this request,
// we annotate each one linked to a valid owning element (node).
if (aStatus == NS_ERROR_TRACKING_URI) {
nsIDocument* doc = mLoader->GetDocument();
if (doc) {
for (SheetLoadData* data = this; data; data = data->mNext) {
// mOwningElement may be null but AddBlockTrackingNode can cope
nsCOMPtr<nsIContent> content =
do_QueryInterface(data->mOwningElement);
doc->AddBlockedTrackingNode(content);
}
}
}
mLoader->SheetComplete(this, aStatus);
return NS_OK;
}
if (!aChannel) {
mLoader->SheetComplete(this, NS_OK);
return NS_OK;
}
nsCOMPtr<nsIURI> originalURI;
aChannel->GetOriginalURI(getter_AddRefs(originalURI));
// If the channel's original URI is "chrome:", we want that, since
// the observer code in nsXULPrototypeCache depends on chrome stylesheets
// having a chrome URI. (Whether or not chrome stylesheets come through
// this codepath seems nondeterministic.)
// Otherwise we want the potentially-HTTP-redirected URI.
nsCOMPtr<nsIURI> channelURI;
NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
if (!channelURI || !originalURI) {
NS_ERROR("Someone just violated the nsIRequest contract");
LOG_WARN((" Channel without a URI. Bad!"));
mLoader->SheetComplete(this, NS_ERROR_UNEXPECTED);
return NS_OK;
}
nsCOMPtr<nsIPrincipal> principal;
nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
nsresult result = NS_ERROR_NOT_AVAILABLE;
if (secMan) { // Could be null if we already shut down
if (mUseSystemPrincipal) {
result = secMan->GetSystemPrincipal(getter_AddRefs(principal));
} else {
result = secMan->GetChannelResultPrincipal(aChannel,
getter_AddRefs(principal));
}
}
if (NS_FAILED(result)) {
LOG_WARN((" Couldn't get principal"));
mLoader->SheetComplete(this, result);
return NS_OK;
}
mSheet->SetPrincipal(principal);
if (mLoaderPrincipal && mSheet->GetCORSMode() == CORS_NONE) {
bool subsumed;
result = mLoaderPrincipal->Subsumes(principal, &subsumed);
if (NS_FAILED(result) || !subsumed) {
mIsCrossOriginNoCORS = true;
}
}
// If it's an HTTP channel, we want to make sure this is not an
// error document we got.
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aChannel));
if (httpChannel) {
bool requestSucceeded;
result = httpChannel->GetRequestSucceeded(&requestSucceeded);
if (NS_SUCCEEDED(result) && !requestSucceeded) {
LOG((" Load returned an error page"));
mLoader->SheetComplete(this, NS_ERROR_NOT_AVAILABLE);
return NS_OK;
}
nsAutoCString sourceMapURL;
if (nsContentUtils::GetSourceMapURL(httpChannel, sourceMapURL)) {
mSheet->SetSourceMapURL(NS_ConvertUTF8toUTF16(sourceMapURL));
}
}
nsAutoCString contentType;
aChannel->GetContentType(contentType);
// In standards mode, a style sheet must have one of these MIME
// types to be processed at all. In quirks mode, we accept any
// MIME type, but only if the style sheet is same-origin with the
// requesting document or parent sheet. See bug 524223.
bool validType = contentType.EqualsLiteral("text/css") ||
contentType.EqualsLiteral(UNKNOWN_CONTENT_TYPE) ||
contentType.IsEmpty();
if (!validType) {
const char* errorMessage;
uint32_t errorFlag;
bool sameOrigin = true;
if (mLoaderPrincipal) {
bool subsumed;
result = mLoaderPrincipal->Subsumes(principal, &subsumed);
if (NS_FAILED(result) || !subsumed) {
sameOrigin = false;
}
}
if (sameOrigin && mLoader->mCompatMode == eCompatibility_NavQuirks) {
errorMessage = "MimeNotCssWarn";
errorFlag = nsIScriptError::warningFlag;
} else {
errorMessage = "MimeNotCss";
errorFlag = nsIScriptError::errorFlag;
}
const nsString& specUTF16 =
NS_ConvertUTF8toUTF16(channelURI->GetSpecOrDefault());
const nsString& ctypeUTF16 = NS_ConvertASCIItoUTF16(contentType);
const char16_t* strings[] = {specUTF16.get(), ctypeUTF16.get()};
nsCOMPtr<nsIURI> referrer = GetReferrerURI();
nsContentUtils::ReportToConsole(
errorFlag, NS_LITERAL_CSTRING("CSS Loader"), mLoader->mDocument,
nsContentUtils::eCSS_PROPERTIES, errorMessage, strings,
ArrayLength(strings), referrer);
if (errorFlag == nsIScriptError::errorFlag) {
LOG_WARN(
(" Ignoring sheet with improper MIME type %s", contentType.get()));
mLoader->SheetComplete(this, NS_ERROR_NOT_AVAILABLE);
return NS_OK;
}
}
SRIMetadata sriMetadata;
mSheet->GetIntegrity(sriMetadata);
if (sriMetadata.IsEmpty()) {
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();
if (loadInfo && loadInfo->GetEnforceSRI()) {
LOG((" Load was blocked by SRI"));
MOZ_LOG(gSriPRLog, mozilla::LogLevel::Debug,
("css::Loader::OnStreamComplete, required SRI not found"));
mLoader->SheetComplete(this, NS_ERROR_SRI_CORRUPT);
// log the failed load to web console
nsCOMPtr<nsIContentSecurityPolicy> csp;
loadInfo->LoadingPrincipal()->GetCsp(getter_AddRefs(csp));
nsAutoCString spec;
mLoader->mDocument->GetDocumentURI()->GetAsciiSpec(spec);
// line number unknown. mRequestingNode doesn't bear this info.
csp->LogViolationDetails(
nsIContentSecurityPolicy::VIOLATION_TYPE_REQUIRE_SRI_FOR_STYLE,
nullptr, // triggering element
nullptr, // nsICSPEventListener
NS_ConvertUTF8toUTF16(spec), EmptyString(), 0, 0, EmptyString(),
EmptyString());
return NS_OK;
}
} else {
nsAutoCString sourceUri;
if (mLoader->mDocument && mLoader->mDocument->GetDocumentURI()) {
mLoader->mDocument->GetDocumentURI()->GetAsciiSpec(sourceUri);
}
nsresult rv = VerifySheetIntegrity(sriMetadata, aChannel, aBytes1, aBytes2,
sourceUri, mLoader->mReporter);
nsCOMPtr<nsILoadGroup> loadGroup;
aChannel->GetLoadGroup(getter_AddRefs(loadGroup));
if (loadGroup) {
mLoader->mReporter->FlushConsoleReports(loadGroup);
} else {
mLoader->mReporter->FlushConsoleReports(mLoader->mDocument);
}
if (NS_FAILED(rv)) {
LOG((" Load was blocked by SRI"));
MOZ_LOG(gSriPRLog, mozilla::LogLevel::Debug,
("css::Loader::OnStreamComplete, bad metadata"));
mLoader->SheetComplete(this, NS_ERROR_SRI_CORRUPT);
return NS_OK;
}
}
SetReferrerPolicyFromHeader(aChannel);
// Enough to set the URIs on mSheet, since any sibling datas we have share
// the same mInner as mSheet and will thus get the same URI.
mSheet->SetURIs(channelURI, originalURI, channelURI);
return NS_OK_PARSE_SHEET;
}
Loader::IsAlternate Loader::IsAlternateSheet(const nsAString& aTitle,
bool aHasAlternateRel) {
// A sheet is alternate if it has a nonempty title that doesn't match the
// currently selected style set. But if there _is_ no currently selected
// style set, the sheet wasn't marked as an alternate explicitly, and aTitle
// is nonempty, we should select the style set corresponding to aTitle, since
// that's a preferred sheet.
if (aTitle.IsEmpty()) {
return IsAlternate::No;
}
if (mDocument) {
const nsString& currentSheetSet = mDocument->GetCurrentStyleSheetSet();
if (!aHasAlternateRel && currentSheetSet.IsEmpty()) {
// There's no preferred set yet, and we now have a sheet with a title.
// Make that be the preferred set.
// FIXME(emilio): This is kinda wild, can we do it somewhere else?
mDocument->SetPreferredStyleSheetSet(aTitle);
// We're definitely not an alternate. Also, beware that at this point
// currentSheetSet may dangle.
return IsAlternate::No;
}
if (aTitle.Equals(currentSheetSet)) {
return IsAlternate::No;
}
}
return IsAlternate::Yes;
}
void Loader::UpdateLoadingData(
URIPrincipalReferrerPolicyAndCORSModeHashKey* aOldKey,
SheetLoadData* aData) {
MOZ_ASSERT(mSheets, "Must have sheets!");
MOZ_ASSERT(aData->mIsLoading, "data must be loading");
DebugOnly<bool> removed = mSheets->mLoadingDatas.Remove(aOldKey);
MOZ_ASSERT(removed, "Can't find data to remove!!!");
URIPrincipalReferrerPolicyAndCORSModeHashKey newKey(aData);
mSheets->mLoadingDatas.Put(&newKey, aData);
}
nsresult Loader::CheckContentPolicy(nsIPrincipal* aLoadingPrincipal,
nsIPrincipal* aTriggeringPrincipal,
nsIURI* aTargetURI,
nsINode* aRequestingNode, bool aIsPreload) {
// When performing a system load (e.g. aUseSystemPrincipal = true)
// then aLoadingPrincipal == null; don't consult content policies.
if (!aLoadingPrincipal) {
return NS_OK;
}
nsContentPolicyType contentPolicyType =
aIsPreload ? nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD
: nsIContentPolicy::TYPE_INTERNAL_STYLESHEET;
nsCOMPtr<nsILoadInfo> secCheckLoadInfo = new net::LoadInfo(
aLoadingPrincipal, aTriggeringPrincipal, aRequestingNode,
nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK, contentPolicyType);
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
nsresult rv = NS_CheckContentLoadPolicy(
aTargetURI, secCheckLoadInfo, NS_LITERAL_CSTRING("text/css"), &shouldLoad,
nsContentUtils::GetContentPolicy());
if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
return NS_ERROR_CONTENT_BLOCKED;
}
return NS_OK;
}
/**
* CreateSheet() creates a CSSStyleSheet object for the given URI,
* if any. If there is no URI given, we just create a new style sheet
* object. Otherwise, we check for an existing style sheet object for
* that uri in various caches and clone it if we find it. Cloned
* sheets will have the title/media/enabled state of the sheet they
* are clones off; make sure to call PrepareSheet() on the result of
* CreateSheet().
*/
nsresult Loader::CreateSheet(nsIURI* aURI, nsIContent* aLinkingContent,
nsIPrincipal* aLoaderPrincipal,
css::SheetParsingMode aParsingMode,
CORSMode aCORSMode, ReferrerPolicy aReferrerPolicy,
const nsAString& aIntegrity, bool aSyncLoad,
StyleSheetState& aSheetState,
RefPtr<StyleSheet>* aSheet) {
LOG(("css::Loader::CreateSheet"));
MOZ_ASSERT(aSheet, "Null out param!");
if (!mSheets) {
mSheets = MakeUnique<Sheets>();
}
*aSheet = nullptr;
aSheetState = eSheetStateUnknown;
if (aURI) {
aSheetState = eSheetComplete;
RefPtr<StyleSheet> sheet;
// First, the XUL cache
#ifdef MOZ_XUL
if (IsChromeURI(aURI)) {
nsXULPrototypeCache* cache = nsXULPrototypeCache::GetInstance();
if (cache && cache->IsEnabled()) {
sheet = cache->GetStyleSheet(aURI);
LOG((" From XUL cache: %p", sheet.get()));
}
}
#endif
bool fromCompleteSheets = false;
if (!sheet) {
// Then our per-document complete sheets.
URIPrincipalReferrerPolicyAndCORSModeHashKey key(
aURI, aLoaderPrincipal, aCORSMode, aReferrerPolicy);
StyleSheet* completeSheet = nullptr;
mSheets->mCompleteSheets.Get(&key, &completeSheet);
sheet = completeSheet;
LOG((" From completed: %p", sheet.get()));
fromCompleteSheets = !!sheet;
}
if (sheet) {
// This sheet came from the XUL cache or our per-document hashtable; it
// better be a complete sheet.
NS_ASSERTION(sheet->IsComplete(),
"Sheet thinks it's not complete while we think it is");
// Make sure it hasn't been forced to have a unique inner;
// that is an indication that its rules have been exposed to
// CSSOM and so we can't use it.
//
// Similarly, if the sheet doesn't have the right parsing mode just bail.
if (sheet->HasForcedUniqueInner() ||
sheet->ParsingMode() != aParsingMode) {
LOG(
(" Not cloning completed sheet %p because it has a "
"forced unique inner or the wrong parsing mode",
sheet.get()));
sheet = nullptr;
fromCompleteSheets = false;
}
}
// Then loading sheets
if (!sheet && !aSyncLoad) {
aSheetState = eSheetLoading;
SheetLoadData* loadData = nullptr;
URIPrincipalReferrerPolicyAndCORSModeHashKey key(
aURI, aLoaderPrincipal, aCORSMode, aReferrerPolicy);
mSheets->mLoadingDatas.Get(&key, &loadData);
if (loadData) {
sheet = loadData->mSheet;
LOG((" From loading: %p", sheet.get()));
#ifdef DEBUG
bool debugEqual;
NS_ASSERTION((!aLoaderPrincipal && !loadData->mLoaderPrincipal) ||
(aLoaderPrincipal && loadData->mLoaderPrincipal &&
NS_SUCCEEDED(aLoaderPrincipal->Equals(
loadData->mLoaderPrincipal, &debugEqual)) &&
debugEqual),
"Principals should be the same");
#endif
}
// Then alternate sheets
if (!sheet) {
aSheetState = eSheetPending;
loadData = nullptr;
mSheets->mPendingDatas.Get(&key, &loadData);
if (loadData) {
sheet = loadData->mSheet;
LOG((" From pending: %p", sheet.get()));
#ifdef DEBUG
bool debugEqual;
NS_ASSERTION((!aLoaderPrincipal && !loadData->mLoaderPrincipal) ||
(aLoaderPrincipal && loadData->mLoaderPrincipal &&
NS_SUCCEEDED(aLoaderPrincipal->Equals(
loadData->mLoaderPrincipal, &debugEqual)) &&
debugEqual),
"Principals should be the same");
#endif
}
}
}
if (sheet) {
// The sheet we have now should be either incomplete or without
// a forced unique inner.
NS_ASSERTION(!sheet->HasForcedUniqueInner() || !sheet->IsComplete(),
"Unexpected complete sheet with forced unique inner");
NS_ASSERTION(sheet->IsComplete() || aSheetState != eSheetComplete,
"Sheet thinks it's not complete while we think it is");
RefPtr<StyleSheet> clonedSheet =
sheet->Clone(nullptr, nullptr, nullptr, nullptr);
*aSheet = std::move(clonedSheet);
if (*aSheet && fromCompleteSheets && !sheet->GetOwnerNode() &&