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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
|
/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
/* vim: set sw=2 ts=8 et tw=80 ft=cpp : */
/* 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/. */
#include "mozilla/dom/WindowGlobalParent.h"
#include <algorithm>
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/ContentBlockingAllowList.h"
#include "mozilla/dom/InProcessParent.h"
#include "mozilla/dom/BrowserBridgeParent.h"
#include "mozilla/dom/BrowsingContextGroup.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/ClientIPCTypes.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/BrowserHost.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/IdentityCredential.h"
#include "mozilla/dom/MediaController.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/ChromeUtils.h"
#include "mozilla/dom/ipc/IdType.h"
#include "mozilla/dom/ipc/StructuredCloneData.h"
#include "mozilla/Components.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/ServoCSSParser.h"
#include "mozilla/ServoStyleSet.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Variant.h"
#include "nsContentUtils.h"
#include "nsDocShell.h"
#include "nsDocShellLoadState.h"
#include "nsError.h"
#include "nsFrameLoader.h"
#include "nsFrameLoaderOwner.h"
#include "nsGlobalWindowInner.h"
#include "nsQueryObject.h"
#include "nsNetUtil.h"
#include "nsSandboxFlags.h"
#include "nsSerializationHelper.h"
#include "nsIBrowser.h"
#include "nsIEffectiveTLDService.h"
#include "nsIHttpsOnlyModePermission.h"
#include "nsIPromptCollection.h"
#include "nsITimer.h"
#include "nsITransportSecurityInfo.h"
#include "nsISharePicker.h"
#include "nsIURIMutator.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/DOMExceptionBinding.h"
#include "mozilla/dom/JSActorService.h"
#include "mozilla/dom/JSWindowActorBinding.h"
#include "mozilla/dom/JSWindowActorParent.h"
#include "SessionStoreFunctions.h"
#include "nsIXPConnect.h"
#include "nsImportModule.h"
#include "nsIXULRuntime.h"
#include "mozilla/dom/PBackgroundSessionStorageCache.h"
using namespace mozilla::ipc;
using namespace mozilla::dom::ipc;
extern mozilla::LazyLogModule gSHIPBFCacheLog;
extern mozilla::LazyLogModule gUseCountersLog;
namespace mozilla::dom {
WindowGlobalParent::WindowGlobalParent(
CanonicalBrowsingContext* aBrowsingContext, uint64_t aInnerWindowId,
uint64_t aOuterWindowId, FieldValues&& aInit)
: WindowContext(aBrowsingContext, aInnerWindowId, aOuterWindowId,
std::move(aInit)),
mIsInitialDocument(false),
mSandboxFlags(0),
mDocumentHasLoaded(false),
mDocumentHasUserInteracted(false),
mBlockAllMixedContent(false),
mUpgradeInsecureRequests(false) {
MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess(), "Parent process only");
}
already_AddRefed<WindowGlobalParent> WindowGlobalParent::CreateDisconnected(
const WindowGlobalInit& aInit) {
RefPtr<CanonicalBrowsingContext> browsingContext =
CanonicalBrowsingContext::Get(aInit.context().mBrowsingContextId);
if (NS_WARN_IF(!browsingContext)) {
return nullptr;
}
RefPtr<WindowGlobalParent> wgp =
GetByInnerWindowId(aInit.context().mInnerWindowId);
MOZ_RELEASE_ASSERT(!wgp, "Creating duplicate WindowGlobalParent");
FieldValues fields(aInit.context().mFields);
wgp =
new WindowGlobalParent(browsingContext, aInit.context().mInnerWindowId,
aInit.context().mOuterWindowId, std::move(fields));
wgp->mDocumentPrincipal = aInit.principal();
wgp->mDocumentURI = aInit.documentURI();
wgp->mIsInitialDocument = aInit.isInitialDocument();
wgp->mBlockAllMixedContent = aInit.blockAllMixedContent();
wgp->mUpgradeInsecureRequests = aInit.upgradeInsecureRequests();
wgp->mSandboxFlags = aInit.sandboxFlags();
wgp->mHttpsOnlyStatus = aInit.httpsOnlyStatus();
wgp->mSecurityInfo = aInit.securityInfo();
net::CookieJarSettings::Deserialize(aInit.cookieJarSettings(),
getter_AddRefs(wgp->mCookieJarSettings));
MOZ_RELEASE_ASSERT(wgp->mDocumentPrincipal, "Must have a valid principal");
nsresult rv = wgp->SetDocumentStoragePrincipal(aInit.storagePrincipal());
MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv),
"Must succeed in setting storage principal");
return wgp.forget();
}
void WindowGlobalParent::Init() {
MOZ_ASSERT(Manager(), "Should have a manager!");
// Invoke our base class' `Init` method. This will register us in
// `gWindowContexts`.
WindowContext::Init();
// Determine which content process the window global is coming from.
dom::ContentParentId processId(0);
ContentParent* cp = nullptr;
if (!IsInProcess()) {
cp = static_cast<ContentParent*>(Manager()->Manager());
processId = cp->ChildID();
// Ensure the content process has permissions for this principal.
cp->TransmitPermissionsForPrincipal(mDocumentPrincipal);
}
MOZ_DIAGNOSTIC_ASSERT(
!BrowsingContext()->GetParent() ||
BrowsingContext()->GetEmbedderInnerWindowId(),
"When creating a non-root WindowGlobalParent, the WindowGlobalParent "
"for our embedder should've already been created.");
// Ensure we have a document URI
if (!mDocumentURI) {
NS_NewURI(getter_AddRefs(mDocumentURI), "about:blank");
}
// NOTE: `cp` may be nullptr, but that's OK, we need to tell every other
// process in our group in that case.
IPCInitializer ipcinit = GetIPCInitializer();
Group()->EachOtherParent(cp, [&](ContentParent* otherContent) {
Unused << otherContent->SendCreateWindowContext(ipcinit);
});
if (!BrowsingContext()->IsDiscarded()) {
MOZ_ALWAYS_SUCCEEDS(
BrowsingContext()->SetCurrentInnerWindowId(InnerWindowId()));
Unused << SendSetContainerFeaturePolicy(
BrowsingContext()->GetContainerFeaturePolicy());
}
if (BrowsingContext()->IsTopContent()) {
// For top level sandboxed documents we need to create a new principal
// from URI + OriginAttributes, since the document principal will be a
// NullPrincipal. See Bug 1654546.
if (mSandboxFlags & SANDBOXED_ORIGIN) {
ContentBlockingAllowList::RecomputePrincipal(
mDocumentURI, mDocumentPrincipal->OriginAttributesRef(),
getter_AddRefs(mDocContentBlockingAllowListPrincipal));
} else {
ContentBlockingAllowList::ComputePrincipal(
mDocumentPrincipal,
getter_AddRefs(mDocContentBlockingAllowListPrincipal));
}
}
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
if (obs) {
obs->NotifyObservers(ToSupports(this), "window-global-created", nullptr);
}
if (!BrowsingContext()->IsDiscarded() && ShouldTrackSiteOriginTelemetry()) {
mOriginCounter.emplace();
mOriginCounter->UpdateSiteOriginsFrom(this, /* aIncrease = */ true);
}
}
void WindowGlobalParent::OriginCounter::UpdateSiteOriginsFrom(
WindowGlobalParent* aParent, bool aIncrease) {
MOZ_RELEASE_ASSERT(aParent);
if (aParent->DocumentPrincipal()->GetIsContentPrincipal()) {
nsAutoCString origin;
aParent->DocumentPrincipal()->GetSiteOrigin(origin);
if (aIncrease) {
int32_t& count = mOriginMap.LookupOrInsert(origin);
count += 1;
mMaxOrigins = std::max(mMaxOrigins, mOriginMap.Count());
} else if (auto entry = mOriginMap.Lookup(origin)) {
entry.Data() -= 1;
if (entry.Data() == 0) {
entry.Remove();
}
}
}
}
void WindowGlobalParent::OriginCounter::Accumulate() {
mozilla::Telemetry::Accumulate(
mozilla::Telemetry::HistogramID::
FX_NUMBER_OF_UNIQUE_SITE_ORIGINS_PER_DOCUMENT,
mMaxOrigins);
mMaxOrigins = 0;
mOriginMap.Clear();
}
/* static */
already_AddRefed<WindowGlobalParent> WindowGlobalParent::GetByInnerWindowId(
uint64_t aInnerWindowId) {
if (!XRE_IsParentProcess()) {
return nullptr;
}
return WindowContext::GetById(aInnerWindowId).downcast<WindowGlobalParent>();
}
already_AddRefed<WindowGlobalChild> WindowGlobalParent::GetChildActor() {
if (!CanSend()) {
return nullptr;
}
IProtocol* otherSide = InProcessParent::ChildActorFor(this);
return do_AddRef(static_cast<WindowGlobalChild*>(otherSide));
}
BrowserParent* WindowGlobalParent::GetBrowserParent() {
if (IsInProcess() || !CanSend()) {
return nullptr;
}
return static_cast<BrowserParent*>(Manager());
}
ContentParent* WindowGlobalParent::GetContentParent() {
if (IsInProcess() || !CanSend()) {
return nullptr;
}
return static_cast<ContentParent*>(Manager()->Manager());
}
already_AddRefed<nsFrameLoader> WindowGlobalParent::GetRootFrameLoader() {
dom::BrowsingContext* top = BrowsingContext()->Top();
RefPtr<nsFrameLoaderOwner> frameLoaderOwner =
do_QueryObject(top->GetEmbedderElement());
if (frameLoaderOwner) {
return frameLoaderOwner->GetFrameLoader();
}
return nullptr;
}
uint64_t WindowGlobalParent::ContentParentId() {
RefPtr<BrowserParent> browserParent = GetBrowserParent();
return browserParent ? browserParent->Manager()->ChildID() : 0;
}
int32_t WindowGlobalParent::OsPid() {
RefPtr<BrowserParent> browserParent = GetBrowserParent();
return browserParent ? browserParent->Manager()->Pid() : -1;
}
// A WindowGlobalPaernt is the root in its process if it has no parent, or its
// embedder is in a different process.
bool WindowGlobalParent::IsProcessRoot() {
if (!BrowsingContext()->GetParent()) {
return true;
}
RefPtr<WindowGlobalParent> embedder =
BrowsingContext()->GetEmbedderWindowGlobal();
if (NS_WARN_IF(!embedder)) {
return false;
}
return ContentParentId() != embedder->ContentParentId();
}
uint32_t WindowGlobalParent::ContentBlockingEvents() {
return GetContentBlockingLog()->GetContentBlockingEventsInLog();
}
void WindowGlobalParent::GetContentBlockingLog(nsAString& aLog) {
NS_ConvertUTF8toUTF16 log(GetContentBlockingLog()->Stringify());
aLog.Assign(std::move(log));
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvLoadURI(
const MaybeDiscarded<dom::BrowsingContext>& aTargetBC,
nsDocShellLoadState* aLoadState, bool aSetNavigating) {
if (aTargetBC.IsNullOrDiscarded()) {
MOZ_LOG(
BrowsingContext::GetLog(), LogLevel::Debug,
("ParentIPC: Trying to send a message with dead or detached context"));
return IPC_OK();
}
if (net::SchemeIsJavascript(aLoadState->URI())) {
return IPC_FAIL(this, "Illegal cross-process javascript: load attempt");
}
RefPtr<CanonicalBrowsingContext> targetBC = aTargetBC.get_canonical();
// FIXME: For cross-process loads, we should double check CanAccess() for the
// source browsing context in the parent process.
if (targetBC->Group() != BrowsingContext()->Group()) {
return IPC_FAIL(this, "Illegal cross-group BrowsingContext load");
}
// FIXME: We should really initiate the load in the parent before bouncing
// back down to the child.
targetBC->LoadURI(aLoadState, aSetNavigating);
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvInternalLoad(
nsDocShellLoadState* aLoadState) {
if (!aLoadState->Target().IsEmpty() ||
aLoadState->TargetBrowsingContext().IsNull()) {
return IPC_FAIL(this, "must already be retargeted");
}
if (aLoadState->TargetBrowsingContext().IsDiscarded()) {
MOZ_LOG(
BrowsingContext::GetLog(), LogLevel::Debug,
("ParentIPC: Trying to send a message with dead or detached context"));
return IPC_OK();
}
if (net::SchemeIsJavascript(aLoadState->URI())) {
return IPC_FAIL(this, "Illegal cross-process javascript: load attempt");
}
RefPtr<CanonicalBrowsingContext> targetBC =
aLoadState->TargetBrowsingContext().get_canonical();
// FIXME: For cross-process loads, we should double check CanAccess() for the
// source browsing context in the parent process.
if (targetBC->Group() != BrowsingContext()->Group()) {
return IPC_FAIL(this, "Illegal cross-group BrowsingContext load");
}
// FIXME: We should really initiate the load in the parent before bouncing
// back down to the child.
targetBC->InternalLoad(aLoadState);
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvUpdateDocumentURI(nsIURI* aURI) {
// XXX(nika): Assert that the URI change was one which makes sense (either
// about:blank -> a real URI, or a legal push/popstate URI change?)
mDocumentURI = aURI;
return IPC_OK();
}
nsresult WindowGlobalParent::SetDocumentStoragePrincipal(
nsIPrincipal* aNewDocumentStoragePrincipal) {
if (mDocumentPrincipal->Equals(aNewDocumentStoragePrincipal)) {
mDocumentStoragePrincipal = mDocumentPrincipal;
return NS_OK;
}
// Compare originNoSuffix to ensure it's equal.
nsCString noSuffix;
nsresult rv = mDocumentPrincipal->GetOriginNoSuffix(noSuffix);
if (NS_FAILED(rv)) {
return rv;
}
nsCString storageNoSuffix;
rv = aNewDocumentStoragePrincipal->GetOriginNoSuffix(storageNoSuffix);
if (NS_FAILED(rv)) {
return rv;
}
if (noSuffix != storageNoSuffix) {
return NS_ERROR_FAILURE;
}
if (!mDocumentPrincipal->OriginAttributesRef().EqualsIgnoringPartitionKey(
aNewDocumentStoragePrincipal->OriginAttributesRef())) {
return NS_ERROR_FAILURE;
}
mDocumentStoragePrincipal = aNewDocumentStoragePrincipal;
return NS_OK;
}
IPCResult WindowGlobalParent::RecvUpdateDocumentPrincipal(
nsIPrincipal* aNewDocumentPrincipal,
nsIPrincipal* aNewDocumentStoragePrincipal) {
if (!mDocumentPrincipal->Equals(aNewDocumentPrincipal)) {
return IPC_FAIL(this,
"Trying to reuse WindowGlobalParent but the principal of "
"the new document does not match the old one");
}
mDocumentPrincipal = aNewDocumentPrincipal;
if (NS_FAILED(SetDocumentStoragePrincipal(aNewDocumentStoragePrincipal))) {
return IPC_FAIL(this,
"Trying to reuse WindowGlobalParent but the principal of "
"the new document does not match the storage principal");
}
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvUpdateDocumentTitle(
const nsString& aTitle) {
if (mDocumentTitle.isSome() && mDocumentTitle.value() == aTitle) {
return IPC_OK();
}
mDocumentTitle = Some(aTitle);
// Send a pagetitlechanged event only for changes to the title
// for top-level frames.
if (!BrowsingContext()->IsTop()) {
return IPC_OK();
}
// Notify media controller in order to update its default metadata.
if (BrowsingContext()->HasCreatedMediaController()) {
BrowsingContext()->GetMediaController()->NotifyPageTitleChanged();
}
Element* frameElement = BrowsingContext()->GetEmbedderElement();
if (!frameElement) {
return IPC_OK();
}
AsyncEventDispatcher::RunDOMEventWhenSafe(
*frameElement, u"pagetitlechanged"_ns, CanBubble::eYes,
ChromeOnlyDispatch::eYes);
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvUpdateHttpsOnlyStatus(
uint32_t aHttpsOnlyStatus) {
mHttpsOnlyStatus = aHttpsOnlyStatus;
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvUpdateDocumentHasLoaded(
bool aDocumentHasLoaded) {
mDocumentHasLoaded = aDocumentHasLoaded;
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvUpdateDocumentHasUserInteracted(
bool aDocumentHasUserInteracted) {
mDocumentHasUserInteracted = aDocumentHasUserInteracted;
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvUpdateSandboxFlags(uint32_t aSandboxFlags) {
mSandboxFlags = aSandboxFlags;
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvUpdateDocumentCspSettings(
bool aBlockAllMixedContent, bool aUpgradeInsecureRequests) {
mBlockAllMixedContent = aBlockAllMixedContent;
mUpgradeInsecureRequests = aUpgradeInsecureRequests;
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvSetClientInfo(
const IPCClientInfo& aIPCClientInfo) {
mClientInfo = Some(ClientInfo(aIPCClientInfo));
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvDestroy() {
// Make a copy so that we can avoid potential iterator invalidation when
// calling the user-provided Destroy() methods.
JSActorWillDestroy();
if (CanSend()) {
RefPtr<BrowserParent> browserParent = GetBrowserParent();
if (!browserParent || !browserParent->IsDestroyed()) {
Unused << Send__delete__(this);
}
}
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvRawMessage(
const JSActorMessageMeta& aMeta, const Maybe<ClonedMessageData>& aData,
const Maybe<ClonedMessageData>& aStack) {
Maybe<StructuredCloneData> data;
if (aData) {
data.emplace();
data->BorrowFromClonedMessageData(*aData);
}
Maybe<StructuredCloneData> stack;
if (aStack) {
stack.emplace();
stack->BorrowFromClonedMessageData(*aStack);
}
ReceiveRawMessage(aMeta, std::move(data), std::move(stack));
return IPC_OK();
}
const nsACString& WindowGlobalParent::GetRemoteType() {
if (RefPtr<BrowserParent> browserParent = GetBrowserParent()) {
return browserParent->Manager()->GetRemoteType();
}
return NOT_REMOTE_TYPE;
}
void WindowGlobalParent::NotifyContentBlockingEvent(
uint32_t aEvent, nsIRequest* aRequest, bool aBlocked,
const nsACString& aTrackingOrigin,
const nsTArray<nsCString>& aTrackingFullHashes,
const Maybe<ContentBlockingNotifier::StorageAccessPermissionGrantedReason>&
aReason) {
MOZ_ASSERT(NS_IsMainThread());
DebugOnly<bool> isCookiesBlocked =
aEvent == nsIWebProgressListener::STATE_COOKIES_BLOCKED_TRACKER ||
aEvent == nsIWebProgressListener::STATE_COOKIES_BLOCKED_SOCIALTRACKER ||
(aEvent == nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN &&
StaticPrefs::network_cookie_rejectForeignWithExceptions_enabled());
MOZ_ASSERT_IF(aBlocked, aReason.isNothing());
MOZ_ASSERT_IF(!isCookiesBlocked, aReason.isNothing());
MOZ_ASSERT_IF(isCookiesBlocked && !aBlocked, aReason.isSome());
MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
// TODO: temporarily remove this until we find the root case of Bug 1609144
// MOZ_DIAGNOSTIC_ASSERT_IF(XRE_IsE10sParentProcess(), !IsInProcess());
// Return early if this WindowGlobalParent is in process.
if (IsInProcess()) {
return;
}
Maybe<uint32_t> event = GetContentBlockingLog()->RecordLogParent(
aTrackingOrigin, aEvent, aBlocked, aReason, aTrackingFullHashes);
// Notify the OnContentBlockingEvent if necessary.
if (event) {
if (auto* webProgress = GetBrowsingContext()->GetWebProgress()) {
webProgress->OnContentBlockingEvent(webProgress, aRequest, event.value());
}
}
}
already_AddRefed<JSWindowActorParent> WindowGlobalParent::GetActor(
JSContext* aCx, const nsACString& aName, ErrorResult& aRv) {
return JSActorManager::GetActor(aCx, aName, aRv)
.downcast<JSWindowActorParent>();
}
already_AddRefed<JSWindowActorParent> WindowGlobalParent::GetExistingActor(
const nsACString& aName) {
return JSActorManager::GetExistingActor(aName)
.downcast<JSWindowActorParent>();
}
already_AddRefed<JSActor> WindowGlobalParent::InitJSActor(
JS::Handle<JSObject*> aMaybeActor, const nsACString& aName,
ErrorResult& aRv) {
RefPtr<JSWindowActorParent> actor;
if (aMaybeActor.get()) {
aRv = UNWRAP_OBJECT(JSWindowActorParent, aMaybeActor.get(), actor);
if (aRv.Failed()) {
return nullptr;
}
} else {
actor = new JSWindowActorParent();
}
MOZ_RELEASE_ASSERT(!actor->GetManager(),
"mManager was already initialized once!");
actor->Init(aName, this);
return actor.forget();
}
bool WindowGlobalParent::IsCurrentGlobal() {
if (mozilla::SessionHistoryInParent() && BrowsingContext() &&
BrowsingContext()->IsInBFCache()) {
return false;
}
return CanSend() && BrowsingContext()->GetCurrentWindowGlobal() == this;
}
namespace {
class ShareHandler final : public PromiseNativeHandler {
public:
explicit ShareHandler(
mozilla::dom::WindowGlobalParent::ShareResolver&& aResolver)
: mResolver(std::move(aResolver)) {}
NS_DECL_ISUPPORTS
public:
virtual void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) override {
mResolver(NS_OK);
}
virtual void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) override {
if (NS_WARN_IF(!aValue.isObject())) {
mResolver(NS_ERROR_FAILURE);
return;
}
// nsresult is stored as Exception internally in Promise
JS::Rooted<JSObject*> obj(aCx, &aValue.toObject());
RefPtr<DOMException> unwrapped;
nsresult rv = UNWRAP_OBJECT(DOMException, &obj, unwrapped);
if (NS_WARN_IF(NS_FAILED(rv))) {
mResolver(NS_ERROR_FAILURE);
return;
}
mResolver(unwrapped->GetResult());
}
private:
~ShareHandler() = default;
mozilla::dom::WindowGlobalParent::ShareResolver mResolver;
};
NS_IMPL_ISUPPORTS0(ShareHandler)
} // namespace
mozilla::ipc::IPCResult WindowGlobalParent::RecvGetContentBlockingEvents(
WindowGlobalParent::GetContentBlockingEventsResolver&& aResolver) {
uint32_t events = GetContentBlockingLog()->GetContentBlockingEventsInLog();
aResolver(events);
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvUpdateCookieJarSettings(
const CookieJarSettingsArgs& aCookieJarSettingsArgs) {
net::CookieJarSettings::Deserialize(aCookieJarSettingsArgs,
getter_AddRefs(mCookieJarSettings));
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvUpdateDocumentSecurityInfo(
nsITransportSecurityInfo* aSecurityInfo) {
mSecurityInfo = aSecurityInfo;
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvShare(
IPCWebShareData&& aData, WindowGlobalParent::ShareResolver&& aResolver) {
// Widget Layer handoff...
nsCOMPtr<nsISharePicker> sharePicker =
do_GetService("@mozilla.org/sharepicker;1");
if (!sharePicker) {
aResolver(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return IPC_OK();
}
// Initialize the ShareWidget
RefPtr<BrowserParent> parent = GetBrowserParent();
nsCOMPtr<mozIDOMWindowProxy> openerWindow;
if (parent) {
openerWindow = parent->GetParentWindowOuter();
if (!openerWindow) {
aResolver(NS_ERROR_FAILURE);
return IPC_OK();
}
}
sharePicker->Init(openerWindow);
// And finally share the data...
RefPtr<Promise> promise;
nsresult rv = sharePicker->Share(aData.title(), aData.text(), aData.url(),
getter_AddRefs(promise));
if (NS_FAILED(rv)) {
aResolver(rv);
return IPC_OK();
}
// Handler finally awaits response...
RefPtr<ShareHandler> handler = new ShareHandler(std::move(aResolver));
promise->AppendNativeHandler(handler);
return IPC_OK();
}
namespace {
class CheckPermitUnloadRequest final : public PromiseNativeHandler,
public nsITimerCallback {
public:
CheckPermitUnloadRequest(WindowGlobalParent* aWGP, bool aHasInProcessBlocker,
nsIContentViewer::PermitUnloadAction aAction,
std::function<void(bool)>&& aResolver)
: mResolver(std::move(aResolver)),
mWGP(aWGP),
mAction(aAction),
mFoundBlocker(aHasInProcessBlocker) {}
void Run(ContentParent* aIgnoreProcess = nullptr, uint32_t aTimeout = 0) {
MOZ_ASSERT(mState == State::UNINITIALIZED);
mState = State::WAITING;
RefPtr<CheckPermitUnloadRequest> self(this);
AutoTArray<ContentParent*, 8> seen;
if (aIgnoreProcess) {
seen.AppendElement(aIgnoreProcess);
}
BrowsingContext* bc = mWGP->GetBrowsingContext();
bc->PreOrderWalk([&](dom::BrowsingContext* aBC) {
if (WindowGlobalParent* wgp =
aBC->Canonical()->GetCurrentWindowGlobal()) {
ContentParent* cp = wgp->GetContentParent();
if (wgp->HasBeforeUnload() && !seen.ContainsSorted(cp)) {
seen.InsertElementSorted(cp);
mPendingRequests++;
auto resolve = [self](bool blockNavigation) {
if (blockNavigation) {
self->mFoundBlocker = true;
}
self->ResolveRequest();
};
if (cp) {
cp->SendDispatchBeforeUnloadToSubtree(
bc, resolve, [self](auto) { self->ResolveRequest(); });
} else {
ContentChild::DispatchBeforeUnloadToSubtree(bc, resolve);
}
}
}
});
if (mPendingRequests && aTimeout) {
Unused << NS_NewTimerWithCallback(getter_AddRefs(mTimer), this, aTimeout,
nsITimer::TYPE_ONE_SHOT);
}
CheckDoneWaiting();
}
void ResolveRequest() {
mPendingRequests--;
CheckDoneWaiting();
}
NS_IMETHODIMP Notify(nsITimer* aTimer) override {
MOZ_ASSERT(aTimer == mTimer);
if (mState == State::WAITING) {
mState = State::TIMED_OUT;
CheckDoneWaiting();
}
return NS_OK;
}
void CheckDoneWaiting() {
// If we've found a blocker, we prompt immediately without waiting for
// further responses. The user's response applies to the entire navigation
// attempt, regardless of how many "beforeunload" listeners we call.
if (mState != State::TIMED_OUT &&
(mState != State::WAITING || (mPendingRequests && !mFoundBlocker))) {
return;
}
mState = State::PROMPTING;
// Clearing our reference to the timer will automatically cancel it if it's
// still running.
mTimer = nullptr;
if (!mFoundBlocker) {
SendReply(true);
return;
}
auto action = mAction;
if (StaticPrefs::dom_disable_beforeunload()) {
action = nsIContentViewer::eDontPromptAndUnload;
}
if (action != nsIContentViewer::ePrompt) {
SendReply(action == nsIContentViewer::eDontPromptAndUnload);
return;
}
// Handle any failure in prompting by aborting the navigation. See comment
// in nsContentViewer::PermitUnload for reasoning.
auto cleanup = MakeScopeExit([&]() { SendReply(false); });
if (nsCOMPtr<nsIPromptCollection> prompt =
do_GetService("@mozilla.org/embedcomp/prompt-collection;1")) {
RefPtr<Promise> promise;
prompt->AsyncBeforeUnloadCheck(mWGP->GetBrowsingContext(),
getter_AddRefs(promise));
if (!promise) {
return;
}
promise->AppendNativeHandler(this);
cleanup.release();
}
}
void SendReply(bool aAllow) {
MOZ_ASSERT(mState != State::REPLIED);
mResolver(aAllow);
mState = State::REPLIED;
}
void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) override {
MOZ_ASSERT(mState == State::PROMPTING);
SendReply(JS::ToBoolean(aValue));
}
void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) override {
MOZ_ASSERT(mState == State::PROMPTING);
SendReply(false);
}
NS_DECL_ISUPPORTS
private:
~CheckPermitUnloadRequest() {
// We may get here without having sent a reply if the promise we're waiting
// on is destroyed without being resolved or rejected.
if (mState != State::REPLIED) {
SendReply(false);
}
}
enum class State : uint8_t {
UNINITIALIZED,
WAITING,
TIMED_OUT,
PROMPTING,
REPLIED,
};
std::function<void(bool)> mResolver;
RefPtr<WindowGlobalParent> mWGP;
nsCOMPtr<nsITimer> mTimer;
uint32_t mPendingRequests = 0;
nsIContentViewer::PermitUnloadAction mAction;
State mState = State::UNINITIALIZED;
bool mFoundBlocker = false;
};
NS_IMPL_ISUPPORTS(CheckPermitUnloadRequest, nsITimerCallback)
} // namespace
mozilla::ipc::IPCResult WindowGlobalParent::RecvCheckPermitUnload(
bool aHasInProcessBlocker, XPCOMPermitUnloadAction aAction,
CheckPermitUnloadResolver&& aResolver) {
if (!IsCurrentGlobal()) {
aResolver(false);
return IPC_OK();
}
auto request = MakeRefPtr<CheckPermitUnloadRequest>(
this, aHasInProcessBlocker, aAction, std::move(aResolver));
request->Run(/* aIgnoreProcess */ GetContentParent());
return IPC_OK();
}
already_AddRefed<Promise> WindowGlobalParent::PermitUnload(
PermitUnloadAction aAction, uint32_t aTimeout, mozilla::ErrorResult& aRv) {
nsIGlobalObject* global = GetParentObject();
RefPtr<Promise> promise = Promise::Create(global, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
auto request = MakeRefPtr<CheckPermitUnloadRequest>(
this, /* aHasInProcessBlocker */ false,
nsIContentViewer::PermitUnloadAction(aAction),
[promise](bool aAllow) { promise->MaybeResolve(aAllow); });
request->Run(/* aIgnoreProcess */ nullptr, aTimeout);
return promise.forget();
}
void WindowGlobalParent::PermitUnload(std::function<void(bool)>&& aResolver) {
RefPtr<CheckPermitUnloadRequest> request = new CheckPermitUnloadRequest(
this, /* aHasInProcessBlocker */ false,
nsIContentViewer::PermitUnloadAction::ePrompt, std::move(aResolver));
request->Run();
}
already_AddRefed<mozilla::dom::Promise> WindowGlobalParent::DrawSnapshot(
const DOMRect* aRect, double aScale, const nsACString& aBackgroundColor,
bool aResetScrollPosition, mozilla::ErrorResult& aRv) {
nsIGlobalObject* global = GetParentObject();
RefPtr<Promise> promise = Promise::Create(global, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
nscolor color;
if (NS_WARN_IF(!ServoCSSParser::ComputeColor(nullptr, NS_RGB(0, 0, 0),
aBackgroundColor, &color,
nullptr, nullptr))) {
aRv = NS_ERROR_FAILURE;
return nullptr;
}
gfx::CrossProcessPaintFlags flags =
gfx::CrossProcessPaintFlags::UseHighQualityScaling;
if (!aRect) {
// If no explicit Rect was passed, we want the currently visible viewport.
flags |= gfx::CrossProcessPaintFlags::DrawView;
} else if (aResetScrollPosition) {
flags |= gfx::CrossProcessPaintFlags::ResetScrollPosition;
}
if (!gfx::CrossProcessPaint::Start(this, aRect, (float)aScale, color, flags,
promise)) {
aRv = NS_ERROR_FAILURE;
return nullptr;
}
return promise.forget();
}
void WindowGlobalParent::DrawSnapshotInternal(gfx::CrossProcessPaint* aPaint,
const Maybe<IntRect>& aRect,
float aScale,
nscolor aBackgroundColor,
uint32_t aFlags) {
auto promise = SendDrawSnapshot(aRect, aScale, aBackgroundColor, aFlags);
RefPtr<gfx::CrossProcessPaint> paint(aPaint);
RefPtr<WindowGlobalParent> wgp(this);
promise->Then(
GetMainThreadSerialEventTarget(), __func__,
[paint, wgp](PaintFragment&& aFragment) {
paint->ReceiveFragment(wgp, std::move(aFragment));
},
[paint, wgp](ResponseRejectReason&& aReason) {
paint->LostFragment(wgp);
});
}
/**
* Accumulated page use counter data for a given top-level content document.
*/
struct PageUseCounters {
// The number of page use counter data messages we are still waiting for.
uint32_t mWaiting = 0;
// Whether we have received any page use counter data.
bool mReceivedAny = false;
// The accumulated page use counters.
UseCounters mUseCounters;
};
mozilla::ipc::IPCResult WindowGlobalParent::RecvExpectPageUseCounters(
const MaybeDiscarded<WindowContext>& aTop) {
if (aTop.IsNull()) {
return IPC_FAIL(this, "aTop must not be null");
}
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
("Expect page use counters: WindowContext %" PRIu64 " -> %" PRIu64,
InnerWindowId(), aTop.ContextId()));
// We've been called to indicate that the document in our window intends
// to send use counter data to accumulate towards the top-level document's
// page use counters. This causes us to wait for this window to go away
// (in WindowGlobalParent::ActorDestroy) before reporting the page use
// counters via Telemetry.
RefPtr<WindowGlobalParent> page =
static_cast<WindowGlobalParent*>(aTop.GetMaybeDiscarded());
if (!page || page->mSentPageUseCounters) {
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
(" > too late, won't report page use counters for this straggler"));
return IPC_OK();
}
if (mPageUseCountersWindow) {
if (mPageUseCountersWindow != page) {
return IPC_FAIL(this,
"ExpectPageUseCounters called on the same "
"WindowContext with a different aTop value");
}
// We can get called with the same aTop value more than once, e.g. for
// initial about:blank documents and then subsequent "real" documents loaded
// into the same window. We must note each source window only once.
return IPC_OK();
}
// Note that the top-level document must wait for one more window's use
// counters before reporting via Telemetry.
mPageUseCountersWindow = page;
if (!page->mPageUseCounters) {
page->mPageUseCounters = MakeUnique<PageUseCounters>();
}
++page->mPageUseCounters->mWaiting;
MOZ_LOG(
gUseCountersLog, LogLevel::Debug,
(" > top-level now waiting on %d\n", page->mPageUseCounters->mWaiting));
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvAccumulatePageUseCounters(
const UseCounters& aUseCounters) {
// We've been called to accumulate use counter data into the page use counters
// for the document in mPageUseCountersWindow.
MOZ_LOG(
gUseCountersLog, LogLevel::Debug,
("Accumulate page use counters: WindowContext %" PRIu64 " -> %" PRIu64,
InnerWindowId(),
mPageUseCountersWindow ? mPageUseCountersWindow->InnerWindowId() : 0));
if (!mPageUseCountersWindow || mPageUseCountersWindow->mSentPageUseCounters) {
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
(" > too late, won't report page use counters for this straggler"));
return IPC_OK();
}
MOZ_ASSERT(mPageUseCountersWindow->mPageUseCounters);
MOZ_ASSERT(mPageUseCountersWindow->mPageUseCounters->mWaiting > 0);
mPageUseCountersWindow->mPageUseCounters->mUseCounters |= aUseCounters;
mPageUseCountersWindow->mPageUseCounters->mReceivedAny = true;
return IPC_OK();
}
// This is called on the top-level WindowGlobal, i.e. the one that is
// accumulating the page use counters, not the (potentially descendant) window
// that has finished providing use counter data.
void WindowGlobalParent::FinishAccumulatingPageUseCounters() {
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
("Stop expecting page use counters: -> WindowContext %" PRIu64,
InnerWindowId()));
if (!mPageUseCounters) {
MOZ_ASSERT_UNREACHABLE("Not expecting page use counter data");
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
(" > not expecting page use counter data"));
return;
}
MOZ_ASSERT(mPageUseCounters->mWaiting > 0);
--mPageUseCounters->mWaiting;
if (mPageUseCounters->mWaiting > 0) {
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
(" > now waiting on %d", mPageUseCounters->mWaiting));
return;
}
if (mPageUseCounters->mReceivedAny) {
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
(" > reporting [%s]",
nsContentUtils::TruncatedURLForDisplay(mDocumentURI).get()));
Maybe<nsCString> urlForLogging;
const bool dumpCounters = StaticPrefs::dom_use_counters_dump_page();
if (dumpCounters) {
urlForLogging.emplace(
nsContentUtils::TruncatedURLForDisplay(mDocumentURI));
}
Telemetry::Accumulate(Telemetry::TOP_LEVEL_CONTENT_DOCUMENTS_DESTROYED, 1);
for (int32_t c = 0; c < eUseCounter_Count; ++c) {
auto uc = static_cast<UseCounter>(c);
if (!mPageUseCounters->mUseCounters[uc]) {
continue;
}
auto id = static_cast<Telemetry::HistogramID>(
Telemetry::HistogramFirstUseCounter + uc * 2 + 1);
if (dumpCounters) {
printf_stderr("USE_COUNTER_PAGE: %s - %s\n",
Telemetry::GetHistogramName(id), urlForLogging->get());
}
Telemetry::Accumulate(id, 1);
}
} else {
MOZ_LOG(gUseCountersLog, LogLevel::Debug,
(" > no page use counter data was received"));
}
mSentPageUseCounters = true;
mPageUseCounters = nullptr;
}
Element* WindowGlobalParent::GetRootOwnerElement() {
WindowGlobalParent* top = TopWindowContext();
if (!top) {
return nullptr;
}
if (IsInProcess()) {
return top->BrowsingContext()->GetEmbedderElement();
}
if (BrowserParent* parent = top->GetBrowserParent()) {
return parent->GetOwnerElement();
}
return nullptr;
}
void WindowGlobalParent::NotifySessionStoreUpdatesComplete(Element* aEmbedder) {
if (!aEmbedder) {
aEmbedder = GetRootOwnerElement();
}
if (aEmbedder) {
if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
obs->NotifyWhenScriptSafe(ToSupports(aEmbedder),
"browser-shutdown-tabstate-updated", nullptr);
}
}
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvRequestRestoreTabContent() {
CanonicalBrowsingContext* bc = BrowsingContext();
if (bc && bc->AncestorsAreCurrent()) {
bc->Top()->RequestRestoreTabContent(this);
}
return IPC_OK();
}
nsCString BFCacheStatusToString(uint32_t aFlags) {
if (aFlags == 0) {
return "0"_ns;
}
nsCString flags;
#define ADD_BFCACHESTATUS_TO_STRING(_flag) \
if (aFlags & BFCacheStatus::_flag) { \
if (!flags.IsEmpty()) { \
flags.Append('|'); \
} \
flags.AppendLiteral(#_flag); \
aFlags &= ~BFCacheStatus::_flag; \
}
ADD_BFCACHESTATUS_TO_STRING(NOT_ALLOWED);
ADD_BFCACHESTATUS_TO_STRING(EVENT_HANDLING_SUPPRESSED);
ADD_BFCACHESTATUS_TO_STRING(SUSPENDED);
ADD_BFCACHESTATUS_TO_STRING(UNLOAD_LISTENER);
ADD_BFCACHESTATUS_TO_STRING(REQUEST);
ADD_BFCACHESTATUS_TO_STRING(ACTIVE_GET_USER_MEDIA);
ADD_BFCACHESTATUS_TO_STRING(ACTIVE_PEER_CONNECTION);
ADD_BFCACHESTATUS_TO_STRING(CONTAINS_EME_CONTENT);
ADD_BFCACHESTATUS_TO_STRING(CONTAINS_MSE_CONTENT);
ADD_BFCACHESTATUS_TO_STRING(HAS_ACTIVE_SPEECH_SYNTHESIS);
ADD_BFCACHESTATUS_TO_STRING(HAS_USED_VR);
ADD_BFCACHESTATUS_TO_STRING(CONTAINS_REMOTE_SUBFRAMES);
ADD_BFCACHESTATUS_TO_STRING(NOT_ONLY_TOPLEVEL_IN_BCG);
ADD_BFCACHESTATUS_TO_STRING(BEFOREUNLOAD_LISTENER);
ADD_BFCACHESTATUS_TO_STRING(ACTIVE_LOCK);
#undef ADD_BFCACHESTATUS_TO_STRING
MOZ_ASSERT(aFlags == 0,
"Missing stringification for enum value in BFCacheStatus.");
return flags;
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvUpdateBFCacheStatus(
const uint32_t& aOnFlags, const uint32_t& aOffFlags) {
if (MOZ_UNLIKELY(MOZ_LOG_TEST(gSHIPBFCacheLog, LogLevel::Debug))) {
nsAutoCString uri("[no uri]");
if (mDocumentURI) {
uri = mDocumentURI->GetSpecOrDefault();
}
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug,
("Setting BFCache flags for %s +(%s) -(%s)", uri.get(),
BFCacheStatusToString(aOnFlags).get(),
BFCacheStatusToString(aOffFlags).get()));
}
mBFCacheStatus |= aOnFlags;
mBFCacheStatus &= ~aOffFlags;
return IPC_OK();
}
mozilla::ipc::IPCResult
WindowGlobalParent::RecvUpdateActivePeerConnectionStatus(bool aIsAdded) {
if (aIsAdded) {
RecvUpdateBFCacheStatus(BFCacheStatus::ACTIVE_PEER_CONNECTION, 0);
} else {
RecvUpdateBFCacheStatus(0, BFCacheStatus::ACTIVE_PEER_CONNECTION);
}
if (WindowGlobalParent* top = TopWindowContext()) {
CheckedUint32 newValue(top->mNumOfProcessesWithActivePeerConnections);
if (aIsAdded) {
++newValue;
} else {
--newValue;
}
if (!newValue.isValid()) {
return IPC_FAIL(this,
"mNumOfProcessesWithActivePeerConnections overflowed");
}
top->mNumOfProcessesWithActivePeerConnections = newValue.value();
Unused << top->SetHasActivePeerConnections(newValue.value() > 0);
}
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvSetSingleChannelId(
const Maybe<uint64_t>& aSingleChannelId) {
mSingleChannelId = aSingleChannelId;
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvSetDocumentDomain(
nsIURI* aDomain) {
if (mSandboxFlags & SANDBOXED_DOMAIN) {
// We're sandboxed; disallow setting domain
return IPC_FAIL(this, "Sandbox disallows domain setting.");
}
// Might need to do a featurepolicy check here, like we currently do in the
// child process?
nsCOMPtr<nsIURI> uri;
mDocumentPrincipal->GetDomain(getter_AddRefs(uri));
if (!uri) {
uri = mDocumentPrincipal->GetURI();
if (!uri) {
return IPC_OK();
}
}
if (!aDomain || !Document::IsValidDomain(uri, aDomain)) {
// Error: illegal domain
return IPC_FAIL(
this, "Setting domain that's not a suffix of existing domain value.");
}
if (Group()->IsPotentiallyCrossOriginIsolated()) {
return IPC_FAIL(this, "Setting domain in a cross-origin isolated BC.");
}
mDocumentPrincipal->SetDomain(aDomain);
return IPC_OK();
}
mozilla::ipc::IPCResult WindowGlobalParent::RecvReloadWithHttpsOnlyException() {
nsresult rv;
nsCOMPtr<nsIURI> currentUri = BrowsingContext()->Top()->GetCurrentURI();
bool isViewSource = currentUri->SchemeIs("view-source");
nsCOMPtr<nsINestedURI> nestedURI = do_QueryInterface(currentUri);
nsCOMPtr<nsIURI> innerURI;
if (isViewSource) {
nestedURI->GetInnerURI(getter_AddRefs(innerURI));
} else {
innerURI = currentUri;
}
if (!innerURI->SchemeIs("https") && !innerURI->SchemeIs("http")) {
return IPC_FAIL(this, "HTTPS-only mode: Illegal state");
}
// If the error page is within an iFrame, we create an exception for whatever
// scheme the top-level site is currently on, because the user wants to
// unbreak the iFrame and not the top-level page. When the error page shows up
// on a top-level request, then we replace the scheme with http, because the
// user wants to unbreak the whole page.
nsCOMPtr<nsIURI> newURI;
if (!BrowsingContext()->IsTop()) {
newURI = innerURI;
} else {
Unused << NS_MutateURI(innerURI).SetScheme("http"_ns).Finalize(
getter_AddRefs(newURI));
}
OriginAttributes originAttributes =
TopWindowContext()->DocumentPrincipal()->OriginAttributesRef();
originAttributes.SetFirstPartyDomain(true, newURI);
nsCOMPtr<nsIPermissionManager> permMgr =
components::PermissionManager::Service();
if (!permMgr) {
return IPC_FAIL(
this, "HTTPS-only mode: Failed to get Permission Manager service");
}
nsCOMPtr<nsIPrincipal> principal =
BasePrincipal::CreateContentPrincipal(newURI, originAttributes);
rv = permMgr->AddFromPrincipal(
principal, "https-only-load-insecure"_ns,
nsIHttpsOnlyModePermission::LOAD_INSECURE_ALLOW_SESSION,
nsIPermissionManager::EXPIRE_SESSION, 0);
if (NS_FAILED(rv)) {
return IPC_FAIL(
this, "HTTPS-only mode: Failed to add permission to the principal");
}
nsCOMPtr<nsIURI> insecureURI = newURI;
if (isViewSource) {
nsAutoCString spec;
MOZ_ALWAYS_SUCCEEDS(newURI->GetSpec(spec));
if (NS_FAILED(
NS_NewURI(getter_AddRefs(insecureURI), "view-source:"_ns + spec))) {
return IPC_FAIL(
this, "HTTPS-only mode: Failed to re-construct view-source URI");
}
}
RefPtr<nsDocShellLoadState> loadState = new nsDocShellLoadState(insecureURI);
loadState->SetTriggeringPrincipal(nsContentUtils::GetSystemPrincipal());
loadState->SetLoadType(LOAD_NORMAL_REPLACE);
RefPtr<CanonicalBrowsingContext> topBC = BrowsingContext()->Top();
topBC->LoadURI(loadState, /* setNavigating */ true);
return IPC_OK();
}
IPCResult WindowGlobalParent::RecvDiscoverIdentityCredentialFromExternalSource(
const IdentityCredentialRequestOptions& aOptions,
const DiscoverIdentityCredentialFromExternalSourceResolver& aResolver) {
IdentityCredential::DiscoverFromExternalSourceInMainProcess(
DocumentPrincipal(), this->BrowsingContext(), aOptions)
->Then(
GetCurrentSerialEventTarget(), __func__,
[aResolver](const IPCIdentityCredential& aResult) {
return aResolver(Some(aResult));
},
[aResolver](nsresult aErr) { aResolver(Nothing()); });
return IPC_OK();
}
void WindowGlobalParent::ActorDestroy(ActorDestroyReason aWhy) {
if (GetBrowsingContext()->IsTopContent()) {
Telemetry::Accumulate(Telemetry::ORB_DID_EVER_BLOCK_RESPONSE,
mShouldReportHasBlockedOpaqueResponse);
}
if (mPageUseCountersWindow) {
mPageUseCountersWindow->FinishAccumulatingPageUseCounters();
mPageUseCountersWindow = nullptr;
}
if (GetBrowsingContext()->IsTopContent() &&
!mDocumentPrincipal->SchemeIs("about")) {
// Record the page load
uint32_t pageLoaded = 1;
Accumulate(Telemetry::MIXED_CONTENT_UNBLOCK_COUNTER, pageLoaded);
// Record the mixed content status of the docshell in Telemetry
enum {
NO_MIXED_CONTENT = 0, // There is no Mixed Content on the page
MIXED_DISPLAY_CONTENT =
1, // The page attempted to load Mixed Display Content
MIXED_ACTIVE_CONTENT =
2, // The page attempted to load Mixed Active Content
MIXED_DISPLAY_AND_ACTIVE_CONTENT = 3 // The page attempted to load Mixed
// Display & Mixed Active Content
};
bool hasMixedDisplay =
mSecurityState &
(nsIWebProgressListener::STATE_LOADED_MIXED_DISPLAY_CONTENT |
nsIWebProgressListener::STATE_BLOCKED_MIXED_DISPLAY_CONTENT);
bool hasMixedActive =
mSecurityState &
(nsIWebProgressListener::STATE_LOADED_MIXED_ACTIVE_CONTENT |
nsIWebProgressListener::STATE_BLOCKED_MIXED_ACTIVE_CONTENT);
uint32_t mixedContentLevel = NO_MIXED_CONTENT;
if (hasMixedDisplay && hasMixedActive) {
mixedContentLevel = MIXED_DISPLAY_AND_ACTIVE_CONTENT;
} else if (hasMixedActive) {
mixedContentLevel = MIXED_ACTIVE_CONTENT;
} else if (hasMixedDisplay) {
mixedContentLevel = MIXED_DISPLAY_CONTENT;
}
Accumulate(Telemetry::MIXED_CONTENT_PAGE_LOAD, mixedContentLevel);
if (GetDocTreeHadMedia()) {
ScalarAdd(Telemetry::ScalarID::MEDIA_ELEMENT_IN_PAGE_COUNT, 1);
}
}
ContentParent* cp = nullptr;
if (!IsInProcess()) {
cp = static_cast<ContentParent*>(Manager()->Manager());
}
Group()->EachOtherParent(cp, [&](ContentParent* otherContent) {
// Keep the WindowContext and our BrowsingContextGroup alive until other
// processes have acknowledged it has been discarded.
Group()->AddKeepAlive();
auto callback = [self = RefPtr{this}](auto) {
self->Group()->RemoveKeepAlive();
};
otherContent->SendDiscardWindowContext(InnerWindowId(), callback, callback);
});
// Note that our WindowContext has become discarded.
WindowContext::Discard();
// Report content blocking log when destroyed.
// There shouldn't have any content blocking log when a document is loaded in
// the parent process(See NotifyContentBlockingEvent), so we could skip
// reporting log when it is in-process.
if (!IsInProcess()) {
RefPtr<BrowserParent> browserParent =
static_cast<BrowserParent*>(Manager());
if (browserParent) {
nsCOMPtr<nsILoadContext> loadContext = browserParent->GetLoadContext();
if (loadContext && !loadContext->UsePrivateBrowsing() &&
BrowsingContext()->IsTopContent()) {
GetContentBlockingLog()->ReportLog(DocumentPrincipal());
if (mDocumentURI && (net::SchemeIsHTTP(mDocumentURI) ||
net::SchemeIsHTTPS(mDocumentURI))) {
GetContentBlockingLog()->ReportEmailTrackingLog(DocumentPrincipal());
}
}
}
}
// Destroy our JSWindowActors, and reject any pending queries.
JSActorDidDestroy();
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
if (obs) {
obs->NotifyObservers(ToSupports(this), "window-global-destroyed", nullptr);
}
if (mOriginCounter) {
mOriginCounter->Accumulate();
}
}
WindowGlobalParent::~WindowGlobalParent() = default;
JSObject* WindowGlobalParent::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return WindowGlobalParent_Binding::Wrap(aCx, this, aGivenProto);
}
nsIGlobalObject* WindowGlobalParent::GetParentObject() {
return xpc::NativeGlobal(xpc::PrivilegedJunkScope());
}
nsIDOMProcessParent* WindowGlobalParent::GetDomProcess() {
if (RefPtr<BrowserParent> browserParent = GetBrowserParent()) {
return browserParent->Manager();
}
return InProcessParent::Singleton();
}
void WindowGlobalParent::DidBecomeCurrentWindowGlobal(bool aCurrent) {
WindowGlobalParent* top = BrowsingContext()->GetTopWindowContext();
if (top && top->mOriginCounter) {
top->mOriginCounter->UpdateSiteOriginsFrom(this,
/* aIncrease = */ aCurrent);
}
if (!aCurrent && Fullscreen()) {
ExitTopChromeDocumentFullscreen();
}
}
bool WindowGlobalParent::ShouldTrackSiteOriginTelemetry() {
CanonicalBrowsingContext* bc = BrowsingContext();
if (!bc->IsTopContent()) {
return false;
}
RefPtr<BrowserParent> browserParent = GetBrowserParent();
if (!browserParent ||
!IsWebRemoteType(browserParent->Manager()->GetRemoteType())) {
return false;
}
return DocumentPrincipal()->GetIsContentPrincipal();
}
void WindowGlobalParent::AddSecurityState(uint32_t aStateFlags) {
MOZ_ASSERT(TopWindowContext() == this);
MOZ_ASSERT((aStateFlags &
(nsIWebProgressListener::STATE_LOADED_MIXED_DISPLAY_CONTENT |
nsIWebProgressListener::STATE_LOADED_MIXED_ACTIVE_CONTENT |
nsIWebProgressListener::STATE_BLOCKED_MIXED_DISPLAY_CONTENT |
nsIWebProgressListener::STATE_BLOCKED_MIXED_ACTIVE_CONTENT |
nsIWebProgressListener::STATE_HTTPS_ONLY_MODE_UPGRADED |
nsIWebProgressListener::STATE_HTTPS_ONLY_MODE_UPGRADE_FAILED)) ==
aStateFlags,
"Invalid flags specified!");
if ((mSecurityState & aStateFlags) == aStateFlags) {
return;
}
mSecurityState |= aStateFlags;
if (GetBrowsingContext()->GetCurrentWindowGlobal() == this) {
GetBrowsingContext()->UpdateSecurityState();
}
}
bool WindowGlobalParent::HasActivePeerConnections() {
MOZ_ASSERT(TopWindowContext() == this,
"mNumOfProcessesWithActivePeerConnections is set only "
"in the top window context");
return mNumOfProcessesWithActivePeerConnections > 0;
}
void WindowGlobalParent::ExitTopChromeDocumentFullscreen() {
RefPtr<CanonicalBrowsingContext> chromeTop =
BrowsingContext()->TopCrossChromeBoundary();
if (Document* chromeDoc = chromeTop->GetDocument()) {
Document::ClearPendingFullscreenRequests(chromeDoc);
if (chromeDoc->Fullscreen()) {
// This only clears the DOM fullscreen, will not exit from browser UI
// fullscreen mode.
Document::AsyncExitFullscreen(chromeDoc);
}
}
}
void WindowGlobalParent::SetShouldReportHasBlockedOpaqueResponse(
nsContentPolicyType aContentPolicy) {
// It's always okay to block TYPE_BEACON, TYPE_PING and TYPE_CSP_REPORT in
// the parent process because content processes can do nothing to their
// responses. Hence excluding them from the telemetry as blocking
// them have no webcompat concerns.
if (aContentPolicy != nsIContentPolicy::TYPE_BEACON &&
aContentPolicy != nsIContentPolicy::TYPE_PING &&
aContentPolicy != nsIContentPolicy::TYPE_CSP_REPORT) {
if (IsTop()) {
mShouldReportHasBlockedOpaqueResponse = true;
}
}
}
NS_IMPL_CYCLE_COLLECTION_INHERITED(WindowGlobalParent, WindowContext,
mPageUseCountersWindow)
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(WindowGlobalParent,
WindowContext)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(WindowGlobalParent)
NS_INTERFACE_MAP_END_INHERITING(WindowContext)
NS_IMPL_ADDREF_INHERITED(WindowGlobalParent, WindowContext)
NS_IMPL_RELEASE_INHERITED(WindowGlobalParent, WindowContext)
} // namespace mozilla::dom
|