forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Loader.cpp
2370 lines (2036 loc) · 76.4 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: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: ft=cpp tw=78 sw=2 et ts=2
*
* 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/.
*
* This Original Code has been modified by IBM Corporation.
* Modifications made by IBM described herein are Copyright (c)
* International Business Machines Corporation, 2000. Modifications
* to Mozilla code or documentation identified per MPL Section 3.3
*
* Date Modified by Description of modification
* 04/20/2000 IBM Corp. OS/2 VisualAge build.
*/
/* loading of CSS style sheets using the network APIs */
#include "mozilla/Util.h"
#include "mozilla/css/Loader.h"
#include "nsIRunnable.h"
#include "nsIUnicharStreamLoader.h"
#include "nsSyncLoadService.h"
#include "nsCOMPtr.h"
#include "nsCOMArray.h"
#include "nsString.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsIDOMNode.h"
#include "nsIDOMDocument.h"
#include "nsIDOMWindow.h"
#include "nsHashtable.h"
#include "nsIURI.h"
#include "nsIServiceManager.h"
#include "nsNetUtil.h"
#include "nsContentUtils.h"
#include "nsCRT.h"
#include "nsIScriptSecurityManager.h"
#include "nsContentPolicyUtils.h"
#include "nsIHttpChannel.h"
#include "nsIScriptError.h"
#include "nsMimeTypes.h"
#include "nsIAtom.h"
#include "nsCSSStyleSheet.h"
#include "nsIStyleSheetLinkingElement.h"
#include "nsICSSLoaderObserver.h"
#include "nsCSSParser.h"
#include "mozilla/css/ImportRule.h"
#include "nsThreadUtils.h"
#include "nsGkAtoms.h"
#include "nsDocShellCID.h"
#include "nsIThreadInternal.h"
#ifdef MOZ_XUL
#include "nsXULPrototypeCache.h"
#endif
#include "nsIMediaList.h"
#include "nsIDOMStyleSheet.h"
#include "nsIDOMCSSStyleSheet.h"
#include "nsContentErrors.h"
#include "nsIChannelPolicy.h"
#include "nsIContentSecurityPolicy.h"
#include "mozilla/FunctionTimer.h"
/**
* 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) Checking whether the load is allowed: CheckLoadAllowed()
* 2) Creation of the actual style sheet objects: CreateSheet()
* 3) setting of the right media, title, enabled state, etc on the
* sheet: PrepareSheet()
* 4) Insertion of the sheet in the proper cascade order:
* InsertSheetInDoc() and InsertChildSheet()
* 5) Load of the sheet: LoadSheet()
* 6) Parsing of the sheet: ParseSheet()
* 7) 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.
*/
namespace mozilla {
namespace css {
/*********************************************
* Data needed to properly load a stylesheet *
*********************************************/
class SheetLoadData : public nsIRunnable,
public nsIUnicharStreamLoaderObserver,
public nsIThreadObserver
{
public:
virtual ~SheetLoadData(void);
// Data for loading a sheet linked from a document
SheetLoadData(Loader* aLoader,
const nsSubstring& aTitle,
nsIURI* aURI,
nsCSSStyleSheet* aSheet,
nsIStyleSheetLinkingElement* aOwningElement,
bool aIsAlternate,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal);
// Data for loading a sheet linked from an @import rule
SheetLoadData(Loader* aLoader,
nsIURI* aURI,
nsCSSStyleSheet* aSheet,
SheetLoadData* aParentData,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal);
// Data for loading a non-document sheet
SheetLoadData(Loader* aLoader,
nsIURI* aURI,
nsCSSStyleSheet* aSheet,
bool aSyncLoad,
bool aAllowUnsafeRules,
bool aUseSystemPrincipal,
const nsCString& aCharset,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal);
already_AddRefed<nsIURI> GetReferrerURI();
void ScheduleLoadEventIfNeeded(nsresult aStatus);
NS_DECL_ISUPPORTS
NS_DECL_NSIRUNNABLE
NS_DECL_NSITHREADOBSERVER
NS_DECL_NSIUNICHARSTREAMLOADEROBSERVER
// Hold a ref to the CSSLoader so we can call back to it to let it
// know the load finished
Loader* mLoader; // strong ref
// Title needed to pull datas out of the pending datas table when
// the preferred title is changed
nsString mTitle;
// Charset we decided to use for the sheet
nsCString mCharset;
// URI we're loading. Null for inline sheets
nsCOMPtr<nsIURI> mURI;
// Should be 1 for non-inline sheets.
PRUint32 mLineNumber;
// The sheet we're loading data for
nsRefPtr<nsCSSStyleSheet> mSheet;
// Linked list of datas for the same URI as us
SheetLoadData* mNext; // strong ref
// Load data for the sheet that @import-ed us if we were @import-ed
// during the parse
SheetLoadData* mParentData; // strong ref
// Number of sheets we @import-ed that are still loading
PRUint32 mPendingChildren;
// mSyncLoad is true when the load needs to be synchronous -- right
// now only for LoadSheetSync and children of sync loads.
bool mSyncLoad : 1;
// mIsNonDocumentSheet is true if the load was triggered by LoadSheetSync or
// LoadSheet or an @import from such a sheet. Non-document sheet loads can
// proceed even if we have no document.
bool mIsNonDocumentSheet : 1;
// mIsLoading is true from the moment we are placed in the loader's
// "loading datas" table (right after the async channel is opened)
// to the moment we are removed from said table (due to the load
// completing or being cancelled).
bool mIsLoading : 1;
// mIsCancelled is set to true when a sheet load is stopped by
// Stop() or StopLoadingSheet() (which was removed in Bug 556446).
// SheetLoadData::OnStreamComplete() checks this to avoid parsing
// sheets that have been cancelled and such.
bool mIsCancelled : 1;
// mMustNotify is true if the load data is being loaded async and
// the original function call that started the load has returned.
// This applies only to observer notifications; load/error events
// are fired for any SheetLoadData that has a non-null
// mOwningElement.
bool mMustNotify : 1;
// mWasAlternate is true if the sheet was an alternate when the load data was
// created.
bool mWasAlternate : 1;
// mAllowUnsafeRules is true if we should allow unsafe rules to be parsed
// in the loaded sheet.
bool mAllowUnsafeRules : 1;
// mUseSystemPrincipal is true if the system principal should be used for
// this sheet, no matter what the channel principal is. Only true for sync
// loads.
bool mUseSystemPrincipal : 1;
// If true, this SheetLoadData is being used as a way to handle
// async observer notification for an already-complete sheet.
bool mSheetAlreadyComplete : 1;
// This is the element that imported the sheet. Needed to get the
// charset set on it and to fire load/error events.
nsCOMPtr<nsIStyleSheetLinkingElement> mOwningElement;
// The observer that wishes to be notified of load completion
nsCOMPtr<nsICSSLoaderObserver> mObserver;
// The principal that identifies who started loading us.
nsCOMPtr<nsIPrincipal> mLoaderPrincipal;
// The charset to use if the transport and sheet don't indicate one.
// May be empty. Must be empty if mOwningElement is non-null.
nsCString mCharsetHint;
// The status our load ended up with; this determines whether we
// should fire error events or load events. This gets initialized
// by ScheduleLoadEventIfNeeded, and is only used after that has
// been called.
nsresult mStatus;
private:
void FireLoadEvent(nsIThreadInternal* aThread);
};
#ifdef MOZ_LOGGING
// #define FORCE_PR_LOG /* Allow logging in the release build */
#endif /* MOZ_LOGGING */
#include "prlog.h"
#ifdef PR_LOGGING
static PRLogModuleInfo *gLoaderLog = PR_NewLogModule("nsCSSLoader");
#endif /* PR_LOGGING */
#define LOG_FORCE(args) PR_LOG(gLoaderLog, PR_LOG_ALWAYS, args)
#define LOG_ERROR(args) PR_LOG(gLoaderLog, PR_LOG_ERROR, args)
#define LOG_WARN(args) PR_LOG(gLoaderLog, PR_LOG_WARNING, args)
#define LOG_DEBUG(args) PR_LOG(gLoaderLog, PR_LOG_DEBUG, args)
#define LOG(args) LOG_DEBUG(args)
#define LOG_FORCE_ENABLED() PR_LOG_TEST(gLoaderLog, PR_LOG_ALWAYS)
#define LOG_ERROR_ENABLED() PR_LOG_TEST(gLoaderLog, PR_LOG_ERROR)
#define LOG_WARN_ENABLED() PR_LOG_TEST(gLoaderLog, PR_LOG_WARNING)
#define LOG_DEBUG_ENABLED() PR_LOG_TEST(gLoaderLog, PR_LOG_DEBUG)
#define LOG_ENABLED() LOG_DEBUG_ENABLED()
#ifdef PR_LOGGING
#define LOG_URI(format, uri) \
PR_BEGIN_MACRO \
NS_ASSERTION(uri, "Logging null uri"); \
if (LOG_ENABLED()) { \
nsCAutoString _logURISpec; \
uri->GetSpec(_logURISpec); \
LOG((format, _logURISpec.get())); \
} \
PR_END_MACRO
#else // PR_LOGGING
#define LOG_URI(format, uri)
#endif // PR_LOGGING
// And some convenience strings...
#ifdef PR_LOGGING
static const char* const gStateStrings[] = {
"eSheetStateUnknown",
"eSheetNeedsParser",
"eSheetPending",
"eSheetLoading",
"eSheetComplete"
};
#endif
/********************************
* SheetLoadData implementation *
********************************/
NS_IMPL_ISUPPORTS3(SheetLoadData, nsIUnicharStreamLoaderObserver, nsIRunnable,
nsIThreadObserver)
SheetLoadData::SheetLoadData(Loader* aLoader,
const nsSubstring& aTitle,
nsIURI* aURI,
nsCSSStyleSheet* aSheet,
nsIStyleSheetLinkingElement* aOwningElement,
bool aIsAlternate,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal)
: mLoader(aLoader),
mTitle(aTitle),
mURI(aURI),
mLineNumber(1),
mSheet(aSheet),
mNext(nsnull),
mParentData(nsnull),
mPendingChildren(0),
mSyncLoad(false),
mIsNonDocumentSheet(false),
mIsLoading(false),
mIsCancelled(false),
mMustNotify(false),
mWasAlternate(aIsAlternate),
mAllowUnsafeRules(false),
mUseSystemPrincipal(false),
mSheetAlreadyComplete(false),
mOwningElement(aOwningElement),
mObserver(aObserver),
mLoaderPrincipal(aLoaderPrincipal)
{
NS_PRECONDITION(mLoader, "Must have a loader!");
NS_ADDREF(mLoader);
}
SheetLoadData::SheetLoadData(Loader* aLoader,
nsIURI* aURI,
nsCSSStyleSheet* aSheet,
SheetLoadData* aParentData,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal)
: mLoader(aLoader),
mURI(aURI),
mLineNumber(1),
mSheet(aSheet),
mNext(nsnull),
mParentData(aParentData),
mPendingChildren(0),
mSyncLoad(false),
mIsNonDocumentSheet(false),
mIsLoading(false),
mIsCancelled(false),
mMustNotify(false),
mWasAlternate(false),
mAllowUnsafeRules(false),
mUseSystemPrincipal(false),
mSheetAlreadyComplete(false),
mOwningElement(nsnull),
mObserver(aObserver),
mLoaderPrincipal(aLoaderPrincipal)
{
NS_PRECONDITION(mLoader, "Must have a loader!");
NS_ADDREF(mLoader);
if (mParentData) {
NS_ADDREF(mParentData);
mSyncLoad = mParentData->mSyncLoad;
mIsNonDocumentSheet = mParentData->mIsNonDocumentSheet;
mAllowUnsafeRules = mParentData->mAllowUnsafeRules;
mUseSystemPrincipal = mParentData->mUseSystemPrincipal;
++(mParentData->mPendingChildren);
}
NS_POSTCONDITION(!mUseSystemPrincipal || mSyncLoad,
"Shouldn't use system principal for async loads");
}
SheetLoadData::SheetLoadData(Loader* aLoader,
nsIURI* aURI,
nsCSSStyleSheet* aSheet,
bool aSyncLoad,
bool aAllowUnsafeRules,
bool aUseSystemPrincipal,
const nsCString& aCharset,
nsICSSLoaderObserver* aObserver,
nsIPrincipal* aLoaderPrincipal)
: mLoader(aLoader),
mURI(aURI),
mLineNumber(1),
mSheet(aSheet),
mNext(nsnull),
mParentData(nsnull),
mPendingChildren(0),
mSyncLoad(aSyncLoad),
mIsNonDocumentSheet(true),
mIsLoading(false),
mIsCancelled(false),
mMustNotify(false),
mWasAlternate(false),
mAllowUnsafeRules(aAllowUnsafeRules),
mUseSystemPrincipal(aUseSystemPrincipal),
mSheetAlreadyComplete(false),
mOwningElement(nsnull),
mObserver(aObserver),
mLoaderPrincipal(aLoaderPrincipal),
mCharsetHint(aCharset)
{
NS_PRECONDITION(mLoader, "Must have a loader!");
NS_ADDREF(mLoader);
NS_POSTCONDITION(!mUseSystemPrincipal || mSyncLoad,
"Shouldn't use system principal for async loads");
}
SheetLoadData::~SheetLoadData()
{
NS_RELEASE(mLoader);
NS_IF_RELEASE(mParentData);
NS_IF_RELEASE(mNext);
}
NS_IMETHODIMP
SheetLoadData::Run()
{
mLoader->HandleLoadEvent(this);
return NS_OK;
}
NS_IMETHODIMP
SheetLoadData::OnDispatchedEvent(nsIThreadInternal* aThread)
{
return NS_OK;
}
NS_IMETHODIMP
SheetLoadData::OnProcessNextEvent(nsIThreadInternal* aThread,
bool aMayWait,
PRUint32 aRecursionDepth)
{
// 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,
PRUint32 aRecursionDepth)
{
// 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!
nsRefPtr<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,
NS_SUCCEEDED(mStatus) ?
NS_LITERAL_STRING("load") :
NS_LITERAL_STRING("error"),
false, false);
// And unblock onload
if (mLoader->mDocument) {
mLoader->mDocument->UnblockOnload(true);
}
}
void
SheetLoadData::ScheduleLoadEventIfNeeded(nsresult aStatus)
{
if (!mOwningElement) {
return;
}
mStatus = aStatus;
nsCOMPtr<nsIThread> thread = do_GetMainThread();
nsCOMPtr<nsIThreadInternal> internalThread = do_QueryInterface(thread);
if (NS_SUCCEEDED(internalThread->AddObserver(this))) {
// Make sure to block onload here
if (mLoader->mDocument) {
mLoader->mDocument->BlockOnload();
}
}
}
/*************************
* Loader Implementation *
*************************/
Loader::Loader(void)
: mDocument(nsnull)
, mDatasToNotifyOn(0)
, mCompatMode(eCompatibility_FullStandards)
, mEnabled(true)
#ifdef DEBUG
, mSyncCallback(false)
#endif
{
}
Loader::Loader(nsIDocument* aDocument)
: mDocument(aDocument)
, mDatasToNotifyOn(0)
, mCompatMode(eCompatibility_FullStandards)
, mEnabled(true)
#ifdef DEBUG
, mSyncCallback(false)
#endif
{
// We can just use the preferred set, since there are no sheets in the
// document yet (if there are, how did they get there? _we_ load the sheets!)
// and hence the selected set makes no sense at this time.
nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(mDocument);
if (domDoc) {
domDoc->GetPreferredStyleSheetSet(mPreferredSheet);
}
}
Loader::~Loader()
{
NS_ASSERTION((!mLoadingDatas.IsInitialized()) || mLoadingDatas.Count() == 0,
"How did we get destroyed when there are loading data?");
NS_ASSERTION((!mPendingDatas.IsInitialized()) || 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.
}
NS_IMPL_ADDREF(Loader)
NS_IMPL_RELEASE(Loader)
void
Loader::DropDocumentReference(void)
{
mDocument = nsnull;
// 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 (mPendingDatas.IsInitialized()) {
StartAlternateLoads();
}
}
static PLDHashOperator
CollectNonAlternates(URIAndPrincipalHashKey *aKey,
SheetLoadData* &aData,
void* aClosure)
{
NS_PRECONDITION(aData, "Must have a data");
NS_PRECONDITION(aClosure, "Must have an array");
// Note that we don't want to affect what the selected style set is,
// so use true for aHasAlternateRel.
if (aData->mLoader->IsAlternate(aData->mTitle, true)) {
return PL_DHASH_NEXT;
}
static_cast<Loader::LoadDataArray*>(aClosure)->AppendElement(aData);
return PL_DHASH_REMOVE;
}
nsresult
Loader::SetPreferredSheet(const nsAString& aTitle)
{
#ifdef DEBUG
nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(mDocument);
if (doc) {
nsAutoString currentPreferred;
doc->GetLastStyleSheetSet(currentPreferred);
if (DOMStringIsNull(currentPreferred)) {
doc->GetPreferredStyleSheetSet(currentPreferred);
}
NS_ASSERTION(currentPreferred.Equals(aTitle),
"Unexpected argument to SetPreferredSheet");
}
#endif
mPreferredSheet = aTitle;
// start any pending alternates that aren't alternates anymore
if (mPendingDatas.IsInitialized()) {
LoadDataArray arr(mPendingDatas.Count());
mPendingDatas.Enumerate(CollectNonAlternates, &arr);
mDatasToNotifyOn += arr.Length();
for (PRUint32 i = 0; i < arr.Length(); ++i) {
--mDatasToNotifyOn;
LoadSheet(arr[i], eSheetNeedsParser);
}
}
return NS_OK;
}
static const char kCharsetSym[] = "@charset \"";
static nsresult GetCharsetFromData(const unsigned char* aStyleSheetData,
PRUint32 aDataLength,
nsACString& aCharset)
{
aCharset.Truncate();
if (aDataLength <= sizeof(kCharsetSym) - 1)
return NS_ERROR_NOT_AVAILABLE;
PRUint32 step = 1;
PRUint32 pos = 0;
bool bigEndian = false;
// Determine the encoding type. If we have a BOM, set aCharset to the
// charset listed for that BOM in http://www.w3.org/TR/REC-xml#sec-guessing;
// that way even if we don't have a valid @charset rule we can use the BOM to
// get a reasonable charset. If we do have an @charset rule, the string from
// that will override this fallback setting of aCharset.
if (*aStyleSheetData == 0x40 && *(aStyleSheetData+1) == 0x63 /* '@c' */ ) {
// 1-byte ASCII-based encoding (ISO-8859-*, UTF-8, etc), no BOM
step = 1;
pos = 0;
}
else if (nsContentUtils::CheckForBOM(aStyleSheetData,
aDataLength, aCharset, &bigEndian)) {
if (aCharset.Equals("UTF-8")) {
step = 1;
pos = 3;
}
else if (aCharset.Equals("UTF-16")) {
step = 2;
pos = bigEndian ? 3 : 2;
}
}
else if (aStyleSheetData[0] == 0x00 &&
aStyleSheetData[1] == 0x40 &&
aStyleSheetData[2] == 0x00 &&
aStyleSheetData[3] == 0x63) {
// 2-byte big-endian encoding, no BOM
step = 2;
pos = 1;
}
else if (aStyleSheetData[0] == 0x40 &&
aStyleSheetData[1] == 0x00 &&
aStyleSheetData[2] == 0x63 &&
aStyleSheetData[3] == 0x00) {
// 2-byte little-endian encoding, no BOM
step = 2;
pos = 0;
}
else {
// no clue what this is
return NS_ERROR_UNEXPECTED;
}
PRUint32 index = 0;
while (pos < aDataLength && index < sizeof(kCharsetSym) - 1) {
if (aStyleSheetData[pos] != kCharsetSym[index]) {
// If we have a guess as to the charset based on the BOM, then
// we can just return NS_OK even if there is no valid @charset
// rule.
return aCharset.IsEmpty() ? NS_ERROR_NOT_AVAILABLE : NS_OK;
}
++index;
pos += step;
}
nsCAutoString charset;
while (pos < aDataLength) {
if (aStyleSheetData[pos] == '"') {
break;
}
// casting to avoid ambiguities
charset.Append(char(aStyleSheetData[pos]));
pos += step;
}
// Check for the ending ';'
pos += step;
if (pos >= aDataLength || aStyleSheetData[pos] != ';') {
return aCharset.IsEmpty() ? NS_ERROR_NOT_AVAILABLE : NS_OK;
}
aCharset = charset;
return NS_OK;
}
NS_IMETHODIMP
SheetLoadData::OnDetermineCharset(nsIUnicharStreamLoader* aLoader,
nsISupports* aContext,
nsACString const& aSegment,
nsACString& aCharset)
{
NS_PRECONDITION(!mOwningElement || mCharsetHint.IsEmpty(),
"Can't have element _and_ charset hint");
LOG_URI("SheetLoadData::OnDetermineCharset for '%s'", mURI);
nsCOMPtr<nsIChannel> channel;
nsresult result = aLoader->GetChannel(getter_AddRefs(channel));
if (NS_FAILED(result))
channel = nsnull;
aCharset.Truncate();
/*
* First determine the charset (if one is indicated)
* 1) Check nsIChannel::contentCharset
* 2) Check @charset rules in the data
* 3) Check "charset" attribute of the <LINK> or <?xml-stylesheet?>
*
* If all these fail to give us a charset, fall back on our default
* (parent sheet charset, document charset or ISO-8859-1 in that order)
*/
if (channel) {
channel->GetContentCharset(aCharset);
}
result = NS_ERROR_NOT_AVAILABLE;
#ifdef PR_LOGGING
if (! aCharset.IsEmpty()) {
LOG((" Setting from HTTP to: %s", PromiseFlatCString(aCharset).get()));
}
#endif
if (aCharset.IsEmpty()) {
// We have no charset
// Try @charset rule and BOM
result = GetCharsetFromData((const unsigned char*)aSegment.BeginReading(),
aSegment.Length(), aCharset);
#ifdef PR_LOGGING
if (NS_SUCCEEDED(result)) {
LOG((" Setting from @charset rule or BOM: %s",
PromiseFlatCString(aCharset).get()));
}
#endif
}
if (aCharset.IsEmpty()) {
// Now try the charset on the <link> or processing instruction
// that loaded us
if (mOwningElement) {
nsAutoString elementCharset;
mOwningElement->GetCharset(elementCharset);
LossyCopyUTF16toASCII(elementCharset, aCharset);
#ifdef PR_LOGGING
if (! aCharset.IsEmpty()) {
LOG((" Setting from property on element: %s",
PromiseFlatCString(aCharset).get()));
}
#endif
} else {
// If mCharsetHint is empty, that's ok; aCharset is known empty here
aCharset = mCharsetHint;
}
}
if (aCharset.IsEmpty() && mParentData) {
aCharset = mParentData->mCharset;
#ifdef PR_LOGGING
if (! aCharset.IsEmpty()) {
LOG((" Setting from parent sheet: %s",
PromiseFlatCString(aCharset).get()));
}
#endif
}
if (aCharset.IsEmpty() && mLoader->mDocument) {
// no useful data on charset. Try the document charset.
aCharset = mLoader->mDocument->GetDocumentCharacterSet();
#ifdef PR_LOGGING
LOG((" Set from document: %s", PromiseFlatCString(aCharset).get()));
#endif
}
if (aCharset.IsEmpty()) {
NS_WARNING("Unable to determine charset for sheet, using ISO-8859-1!");
#ifdef PR_LOGGING
LOG_WARN((" Falling back to ISO-8859-1"));
#endif
aCharset.AssignLiteral("ISO-8859-1");
}
mCharset = aCharset;
return NS_OK;
}
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();
}
/*
* 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.
*/
NS_IMETHODIMP
SheetLoadData::OnStreamComplete(nsIUnicharStreamLoader* aLoader,
nsISupports* aContext,
nsresult aStatus,
const nsAString& aBuffer)
{
LOG(("SheetLoadData::OnStreamComplete"));
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%x", aStatus));
mLoader->SheetComplete(this, aStatus);
return NS_OK;
}
nsCOMPtr<nsIChannel> channel;
nsresult result = aLoader->GetChannel(getter_AddRefs(channel));
if (NS_FAILED(result)) {
LOG_WARN((" No channel from loader"));
mLoader->SheetComplete(this, result);
return NS_OK;
}
nsCOMPtr<nsIURI> originalURI;
channel->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(channel, 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();
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->GetChannelPrincipal(channel, getter_AddRefs(principal));
}
}
if (NS_FAILED(result)) {
LOG_WARN((" Couldn't get principal"));
mLoader->SheetComplete(this, result);
return NS_OK;
}
mSheet->SetPrincipal(principal);
// If it's an HTTP channel, we want to make sure this is not an
// error document we got.
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
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;
}
}
nsCAutoString contentType;
if (channel) {
channel->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;
PRUint32 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;
}
nsCAutoString spec;
channelURI->GetSpec(spec);
const nsAFlatString& specUTF16 = NS_ConvertUTF8toUTF16(spec);
const nsAFlatString& ctypeUTF16 = NS_ConvertASCIItoUTF16(contentType);
const PRUnichar *strings[] = { specUTF16.get(), ctypeUTF16.get() };
nsCOMPtr<nsIURI> referrer = GetReferrerURI();
nsContentUtils::ReportToConsole(errorFlag,
"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;
}
}
// 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);
bool completed;
result = mLoader->ParseSheet(aBuffer, this, completed);
NS_ASSERTION(completed || !mSyncLoad, "sync load did not complete");
return result;
}
#ifdef MOZ_XUL
static bool IsChromeURI(nsIURI* aURI)
{
NS_ASSERTION(aURI, "Have to pass in a URI");
bool isChrome = false;
aURI->SchemeIs("chrome", &isChrome);
return isChrome;
}
#endif
bool
Loader::IsAlternate(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 false;
}
if (!aHasAlternateRel && mDocument && mPreferredSheet.IsEmpty()) {
// There's no preferred set yet, and we now have a sheet with a title.
// Make that be the preferred set.
mDocument->SetHeaderData(nsGkAtoms::headerDefaultStyle, aTitle);
// We're definitely not an alternate
return false;
}
return !aTitle.Equals(mPreferredSheet);
}
/**
* CheckLoadAllowed will return success if the load is allowed,
* failure otherwise.
*