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
|
/* 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 "js/Array.h" // JS::GetArrayLength, JS::IsArrayObject
#include "js/JSON.h"
#include "jsapi.h"
#include "mozilla/PresShell.h"
#include "mozilla/dom/AutocompleteInfoBinding.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/HTMLSelectElement.h"
#include "mozilla/dom/HTMLTextAreaElement.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/SessionStorageManager.h"
#include "mozilla/dom/SessionStoreUtils.h"
#include "mozilla/dom/txIXPathContext.h"
#include "mozilla/dom/WindowProxyHolder.h"
#include "mozilla/dom/XPathResult.h"
#include "mozilla/dom/XPathEvaluator.h"
#include "mozilla/dom/XPathExpression.h"
#include "mozilla/UniquePtr.h"
#include "nsCharSeparatedTokenizer.h"
#include "nsContentList.h"
#include "nsContentUtils.h"
#include "nsFocusManager.h"
#include "nsGlobalWindowOuter.h"
#include "nsIDocShell.h"
#include "nsIFormControl.h"
#include "nsIScrollableFrame.h"
#include "nsPresContext.h"
#include "nsPrintfCString.h"
using namespace mozilla;
using namespace mozilla::dom;
namespace {
class DynamicFrameEventFilter final : public nsIDOMEventListener {
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(DynamicFrameEventFilter)
explicit DynamicFrameEventFilter(EventListener* aListener)
: mListener(aListener) {}
NS_IMETHODIMP HandleEvent(Event* aEvent) override {
if (mListener && TargetInNonDynamicDocShell(aEvent)) {
mListener->HandleEvent(*aEvent);
}
return NS_OK;
}
private:
~DynamicFrameEventFilter() = default;
bool TargetInNonDynamicDocShell(Event* aEvent) {
EventTarget* target = aEvent->GetTarget();
if (!target) {
return false;
}
nsPIDOMWindowOuter* outer = target->GetOwnerGlobalForBindingsInternal();
if (!outer || !outer->GetDocShell()) {
return false;
}
RefPtr<BrowsingContext> context = outer->GetBrowsingContext();
return context && !context->CreatedDynamically();
}
RefPtr<EventListener> mListener;
};
NS_IMPL_CYCLE_COLLECTION(DynamicFrameEventFilter, mListener)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DynamicFrameEventFilter)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(DynamicFrameEventFilter)
NS_IMPL_CYCLE_COLLECTING_RELEASE(DynamicFrameEventFilter)
} // anonymous namespace
/* static */
void SessionStoreUtils::ForEachNonDynamicChildFrame(
const GlobalObject& aGlobal, WindowProxyHolder& aWindow,
SessionStoreUtilsFrameCallback& aCallback, ErrorResult& aRv) {
if (!aWindow.get()) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
nsCOMPtr<nsIDocShell> docShell = aWindow.get()->GetDocShell();
if (!docShell) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
int32_t length;
aRv = docShell->GetInProcessChildCount(&length);
if (aRv.Failed()) {
return;
}
for (int32_t i = 0; i < length; ++i) {
nsCOMPtr<nsIDocShellTreeItem> item;
docShell->GetInProcessChildAt(i, getter_AddRefs(item));
if (!item) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
RefPtr<BrowsingContext> context = item->GetBrowsingContext();
if (!context) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
if (context->CreatedDynamically()) {
continue;
}
nsCOMPtr<nsIDocShell> childDocShell(do_QueryInterface(item));
if (!childDocShell) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
int32_t childOffset = childDocShell->GetChildOffset();
aCallback.Call(WindowProxyHolder(context.forget()), childOffset);
}
}
/* static */
already_AddRefed<nsISupports>
SessionStoreUtils::AddDynamicFrameFilteredListener(
const GlobalObject& aGlobal, EventTarget& aTarget, const nsAString& aType,
JS::Handle<JS::Value> aListener, bool aUseCapture, bool aMozSystemGroup,
ErrorResult& aRv) {
if (NS_WARN_IF(!aListener.isObject())) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return nullptr;
}
JSContext* cx = aGlobal.Context();
JS::Rooted<JSObject*> obj(cx, &aListener.toObject());
JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
RefPtr<EventListener> listener =
new EventListener(cx, obj, global, GetIncumbentGlobal());
nsCOMPtr<nsIDOMEventListener> filter(new DynamicFrameEventFilter(listener));
if (aMozSystemGroup) {
aRv = aTarget.AddSystemEventListener(aType, filter, aUseCapture);
} else {
aRv = aTarget.AddEventListener(aType, filter, aUseCapture);
}
if (aRv.Failed()) {
return nullptr;
}
return filter.forget();
}
/* static */
void SessionStoreUtils::RemoveDynamicFrameFilteredListener(
const GlobalObject& global, EventTarget& aTarget, const nsAString& aType,
nsISupports* aListener, bool aUseCapture, bool aMozSystemGroup,
ErrorResult& aRv) {
nsCOMPtr<nsIDOMEventListener> listener = do_QueryInterface(aListener);
if (!listener) {
aRv.Throw(NS_ERROR_NO_INTERFACE);
return;
}
if (aMozSystemGroup) {
aTarget.RemoveSystemEventListener(aType, listener, aUseCapture);
} else {
aTarget.RemoveEventListener(aType, listener, aUseCapture);
}
}
/* static */
void SessionStoreUtils::CollectDocShellCapabilities(const GlobalObject& aGlobal,
nsIDocShell* aDocShell,
nsCString& aRetVal) {
bool allow;
#define TRY_ALLOWPROP(y) \
PR_BEGIN_MACRO \
aDocShell->GetAllow##y(&allow); \
if (!allow) { \
if (!aRetVal.IsEmpty()) { \
aRetVal.Append(','); \
} \
aRetVal.Append(#y); \
} \
PR_END_MACRO
TRY_ALLOWPROP(Plugins);
// Bug 1328013 : Don't collect "AllowJavascript" property
// TRY_ALLOWPROP(Javascript);
TRY_ALLOWPROP(MetaRedirects);
TRY_ALLOWPROP(Subframes);
TRY_ALLOWPROP(Images);
TRY_ALLOWPROP(Media);
TRY_ALLOWPROP(DNSPrefetch);
TRY_ALLOWPROP(WindowControl);
TRY_ALLOWPROP(Auth);
TRY_ALLOWPROP(ContentRetargeting);
TRY_ALLOWPROP(ContentRetargetingOnChildren);
#undef TRY_ALLOWPROP
}
/* static */
void SessionStoreUtils::RestoreDocShellCapabilities(
const GlobalObject& aGlobal, nsIDocShell* aDocShell,
const nsCString& aDisallowCapabilities) {
aDocShell->SetAllowPlugins(true);
aDocShell->SetAllowJavascript(true);
aDocShell->SetAllowMetaRedirects(true);
aDocShell->SetAllowSubframes(true);
aDocShell->SetAllowImages(true);
aDocShell->SetAllowMedia(true);
aDocShell->SetAllowDNSPrefetch(true);
aDocShell->SetAllowWindowControl(true);
aDocShell->SetAllowContentRetargeting(true);
aDocShell->SetAllowContentRetargetingOnChildren(true);
for (const nsACString& token :
nsCCharSeparatedTokenizer(aDisallowCapabilities, ',').ToRange()) {
if (token.EqualsLiteral("Plugins")) {
aDocShell->SetAllowPlugins(false);
} else if (token.EqualsLiteral("Javascript")) {
aDocShell->SetAllowJavascript(false);
} else if (token.EqualsLiteral("MetaRedirects")) {
aDocShell->SetAllowMetaRedirects(false);
} else if (token.EqualsLiteral("Subframes")) {
aDocShell->SetAllowSubframes(false);
} else if (token.EqualsLiteral("Images")) {
aDocShell->SetAllowImages(false);
} else if (token.EqualsLiteral("Media")) {
aDocShell->SetAllowMedia(false);
} else if (token.EqualsLiteral("DNSPrefetch")) {
aDocShell->SetAllowDNSPrefetch(false);
} else if (token.EqualsLiteral("WindowControl")) {
aDocShell->SetAllowWindowControl(false);
} else if (token.EqualsLiteral("ContentRetargeting")) {
bool allow;
aDocShell->GetAllowContentRetargetingOnChildren(&allow);
aDocShell->SetAllowContentRetargeting(
false); // will also set AllowContentRetargetingOnChildren
aDocShell->SetAllowContentRetargetingOnChildren(
allow); // restore the allowProp to original
} else if (token.EqualsLiteral("ContentRetargetingOnChildren")) {
aDocShell->SetAllowContentRetargetingOnChildren(false);
}
}
}
static void CollectCurrentScrollPosition(JSContext* aCx, Document& aDocument,
Nullable<CollectedData>& aRetVal) {
PresShell* presShell = aDocument.GetPresShell();
if (!presShell) {
return;
}
nsPoint scrollPos = presShell->GetVisualViewportOffset();
int scrollX = nsPresContext::AppUnitsToIntCSSPixels(scrollPos.x);
int scrollY = nsPresContext::AppUnitsToIntCSSPixels(scrollPos.y);
if ((scrollX != 0) || (scrollY != 0)) {
aRetVal.SetValue().mScroll.Construct() =
nsPrintfCString("%d,%d", scrollX, scrollY);
}
}
/* static */
void SessionStoreUtils::RestoreScrollPosition(const GlobalObject& aGlobal,
nsGlobalWindowInner& aWindow,
const CollectedData& aData) {
if (!aData.mScroll.WasPassed()) {
return;
}
nsCCharSeparatedTokenizer tokenizer(aData.mScroll.Value(), ',');
nsAutoCString token(tokenizer.nextToken());
int pos_X = atoi(token.get());
token = tokenizer.nextToken();
int pos_Y = atoi(token.get());
aWindow.ScrollTo(pos_X, pos_Y);
if (nsCOMPtr<Document> doc = aWindow.GetExtantDoc()) {
if (nsPresContext* presContext = doc->GetPresContext()) {
if (presContext->IsRootContentDocument()) {
// Use eMainThread so this takes precedence over session history
// (ScrollFrameHelper::ScrollToRestoredPosition()).
presContext->PresShell()->ScrollToVisual(
CSSPoint::ToAppUnits(CSSPoint(pos_X, pos_Y)),
layers::FrameMetrics::eMainThread, ScrollMode::Instant);
}
}
}
}
// Implements the Luhn checksum algorithm as described at
// http://wikipedia.org/wiki/Luhn_algorithm
// Number digit lengths vary with network, but should fall within 12-19 range.
// [2] More details at https://en.wikipedia.org/wiki/Payment_card_number
static bool IsValidCCNumber(nsAString& aValue) {
uint32_t total = 0;
uint32_t numLength = 0;
uint32_t strLen = aValue.Length();
for (uint32_t i = 0; i < strLen; ++i) {
uint32_t idx = strLen - i - 1;
// ignore whitespace and dashes)
char16_t chr = aValue[idx];
if (IsSpaceCharacter(chr) || chr == '-') {
continue;
}
// If our number is too long, note that fact
++numLength;
if (numLength > 19) {
return false;
}
// Try to parse the character as a base-10 integer.
nsresult rv = NS_OK;
uint32_t val = Substring(aValue, idx, 1).ToInteger(&rv, 10);
if (NS_FAILED(rv)) {
return false;
}
if (i % 2 == 1) {
val *= 2;
if (val > 9) {
val -= 9;
}
}
total += val;
}
return numLength >= 12 && total % 10 == 0;
}
// Limit the number of XPath expressions for performance reasons. See bug
// 477564.
static const uint16_t kMaxTraversedXPaths = 100;
// A helper function to append a element into mId or mXpath of CollectedData
static Record<nsString, OwningStringOrBooleanOrObject>::EntryType*
AppendEntryToCollectedData(nsINode* aNode, const nsAString& aId,
uint16_t& aGeneratedCount,
Nullable<CollectedData>& aRetVal) {
Record<nsString, OwningStringOrBooleanOrObject>::EntryType* entry;
if (!aId.IsEmpty()) {
if (!aRetVal.SetValue().mId.WasPassed()) {
aRetVal.SetValue().mId.Construct();
}
auto& recordEntries = aRetVal.SetValue().mId.Value().Entries();
entry = recordEntries.AppendElement();
entry->mKey = aId;
} else {
if (!aRetVal.SetValue().mXpath.WasPassed()) {
aRetVal.SetValue().mXpath.Construct();
}
auto& recordEntries = aRetVal.SetValue().mXpath.Value().Entries();
entry = recordEntries.AppendElement();
nsAutoString xpath;
aNode->GenerateXPath(xpath);
aGeneratedCount++;
entry->mKey = xpath;
}
return entry;
}
// A helper function to append a element into aXPathVals or aIdVals
static void AppendEntryToCollectedData(
nsINode* aNode, const nsAString& aId, CollectedInputDataValue& aEntry,
uint16_t& aNumXPath, uint16_t& aNumId,
nsTArray<CollectedInputDataValue>& aXPathVals,
nsTArray<CollectedInputDataValue>& aIdVals) {
if (!aId.IsEmpty()) {
aEntry.id = aId;
aIdVals.AppendElement(aEntry);
aNumId++;
} else {
nsAutoString xpath;
aNode->GenerateXPath(xpath);
aEntry.id = xpath;
aXPathVals.AppendElement(aEntry);
aNumXPath++;
}
}
/* for bool value */
static void AppendValueToCollectedData(nsINode* aNode, const nsAString& aId,
const bool& aValue,
uint16_t& aGeneratedCount,
JSContext* aCx,
Nullable<CollectedData>& aRetVal) {
Record<nsString, OwningStringOrBooleanOrObject>::EntryType* entry =
AppendEntryToCollectedData(aNode, aId, aGeneratedCount, aRetVal);
entry->mValue.SetAsBoolean() = aValue;
}
/* for bool value */
static void AppendValueToCollectedData(
nsINode* aNode, const nsAString& aId, const bool& aValue,
uint16_t& aNumXPath, uint16_t& aNumId,
nsTArray<CollectedInputDataValue>& aXPathVals,
nsTArray<CollectedInputDataValue>& aIdVals) {
CollectedInputDataValue entry;
entry.type = u"bool"_ns;
entry.value = AsVariant(aValue);
AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals,
aIdVals);
}
/* for nsString value */
static void AppendValueToCollectedData(nsINode* aNode, const nsAString& aId,
const nsString& aValue,
uint16_t& aGeneratedCount,
Nullable<CollectedData>& aRetVal) {
Record<nsString, OwningStringOrBooleanOrObject>::EntryType* entry =
AppendEntryToCollectedData(aNode, aId, aGeneratedCount, aRetVal);
entry->mValue.SetAsString() = aValue;
}
/* for nsString value */
static void AppendValueToCollectedData(
nsINode* aNode, const nsAString& aId, const nsString& aValue,
uint16_t& aNumXPath, uint16_t& aNumId,
nsTArray<CollectedInputDataValue>& aXPathVals,
nsTArray<CollectedInputDataValue>& aIdVals) {
CollectedInputDataValue entry;
entry.type = u"string"_ns;
entry.value = AsVariant(aValue);
AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals,
aIdVals);
}
/* for single select value */
static void AppendValueToCollectedData(
nsINode* aNode, const nsAString& aId,
const CollectedNonMultipleSelectValue& aValue, uint16_t& aGeneratedCount,
JSContext* aCx, Nullable<CollectedData>& aRetVal) {
JS::Rooted<JS::Value> jsval(aCx);
if (!ToJSValue(aCx, aValue, &jsval)) {
JS_ClearPendingException(aCx);
return;
}
Record<nsString, OwningStringOrBooleanOrObject>::EntryType* entry =
AppendEntryToCollectedData(aNode, aId, aGeneratedCount, aRetVal);
entry->mValue.SetAsObject() = &jsval.toObject();
}
/* for single select value */
static void AppendValueToCollectedData(
nsINode* aNode, const nsAString& aId,
const CollectedNonMultipleSelectValue& aValue, uint16_t& aNumXPath,
uint16_t& aNumId, nsTArray<CollectedInputDataValue>& aXPathVals,
nsTArray<CollectedInputDataValue>& aIdVals) {
CollectedInputDataValue entry;
entry.type = u"singleSelect"_ns;
entry.value = AsVariant(aValue);
AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals,
aIdVals);
}
/* special handing for input element with string type */
static void AppendValueToCollectedData(Document& aDocument, nsINode* aNode,
const nsAString& aId,
const nsString& aValue,
uint16_t& aGeneratedCount,
JSContext* aCx,
Nullable<CollectedData>& aRetVal) {
if (!aId.IsEmpty()) {
// We want to avoid saving data for about:sessionrestore as a string.
// Since it's stored in the form as stringified JSON, stringifying
// further causes an explosion of escape characters. cf. bug 467409
if (aId.EqualsLiteral("sessionData")) {
nsAutoCString url;
Unused << aDocument.GetDocumentURI()->GetSpecIgnoringRef(url);
if (url.EqualsLiteral("about:sessionrestore") ||
url.EqualsLiteral("about:welcomeback")) {
JS::Rooted<JS::Value> jsval(aCx);
if (JS_ParseJSON(aCx, aValue.get(), aValue.Length(), &jsval) &&
jsval.isObject()) {
Record<nsString, OwningStringOrBooleanOrObject>::EntryType* entry =
AppendEntryToCollectedData(aNode, aId, aGeneratedCount, aRetVal);
entry->mValue.SetAsObject() = &jsval.toObject();
} else {
JS_ClearPendingException(aCx);
}
return;
}
}
}
AppendValueToCollectedData(aNode, aId, aValue, aGeneratedCount, aRetVal);
}
static void AppendValueToCollectedData(
Document& aDocument, nsINode* aNode, const nsAString& aId,
const nsString& aValue, uint16_t& aNumXPath, uint16_t& aNumId,
nsTArray<CollectedInputDataValue>& aXPathVals,
nsTArray<CollectedInputDataValue>& aIdVals) {
CollectedInputDataValue entry;
entry.type = u"string"_ns;
entry.value = AsVariant(aValue);
AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals,
aIdVals);
}
/* for nsTArray<nsString>: file and multipleSelect */
static void AppendValueToCollectedData(nsINode* aNode, const nsAString& aId,
const nsAString& aValueType,
nsTArray<nsString>& aValue,
uint16_t& aGeneratedCount,
JSContext* aCx,
Nullable<CollectedData>& aRetVal) {
JS::Rooted<JS::Value> jsval(aCx);
if (aValueType.EqualsLiteral("file")) {
CollectedFileListValue val;
val.mType = aValueType;
val.mFileList = std::move(aValue);
if (!ToJSValue(aCx, val, &jsval)) {
JS_ClearPendingException(aCx);
return;
}
} else {
if (!ToJSValue(aCx, aValue, &jsval)) {
JS_ClearPendingException(aCx);
return;
}
}
Record<nsString, OwningStringOrBooleanOrObject>::EntryType* entry =
AppendEntryToCollectedData(aNode, aId, aGeneratedCount, aRetVal);
entry->mValue.SetAsObject() = &jsval.toObject();
}
/* for nsTArray<nsString>: file and multipleSelect */
static void AppendValueToCollectedData(
nsINode* aNode, const nsAString& aId, const nsAString& aValueType,
const nsTArray<nsString>& aValue, uint16_t& aNumXPath, uint16_t& aNumId,
nsTArray<CollectedInputDataValue>& aXPathVals,
nsTArray<CollectedInputDataValue>& aIdVals) {
CollectedInputDataValue entry;
entry.type = aValueType;
entry.value = AsVariant(CopyableTArray(aValue.Clone()));
AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals,
aIdVals);
}
/* static */
template <typename... ArgsT>
void SessionStoreUtils::CollectFromTextAreaElement(Document& aDocument,
uint16_t& aGeneratedCount,
ArgsT&&... args) {
RefPtr<nsContentList> textlist =
NS_GetContentList(&aDocument, kNameSpaceID_XHTML, u"textarea"_ns);
uint32_t length = textlist->Length(true);
for (uint32_t i = 0; i < length; ++i) {
MOZ_ASSERT(textlist->Item(i), "null item in node list!");
HTMLTextAreaElement* textArea =
HTMLTextAreaElement::FromNodeOrNull(textlist->Item(i));
if (!textArea) {
continue;
}
DOMString autocomplete;
textArea->GetAutocomplete(autocomplete);
if (autocomplete.AsAString().EqualsLiteral("off")) {
continue;
}
nsAutoString id;
textArea->GetId(id);
if (id.IsEmpty() && (aGeneratedCount > kMaxTraversedXPaths)) {
continue;
}
nsString value;
textArea->GetValue(value);
// In order to reduce XPath generation (which is slow), we only save data
// for form fields that have been changed. (cf. bug 537289)
if (textArea->AttrValueIs(kNameSpaceID_None, nsGkAtoms::value, value,
eCaseMatters)) {
continue;
}
AppendValueToCollectedData(textArea, id, value, aGeneratedCount,
std::forward<ArgsT>(args)...);
}
}
/* static */
template <typename... ArgsT>
void SessionStoreUtils::CollectFromInputElement(Document& aDocument,
uint16_t& aGeneratedCount,
ArgsT&&... args) {
RefPtr<nsContentList> inputlist =
NS_GetContentList(&aDocument, kNameSpaceID_XHTML, u"input"_ns);
uint32_t length = inputlist->Length(true);
for (uint32_t i = 0; i < length; ++i) {
MOZ_ASSERT(inputlist->Item(i), "null item in node list!");
nsCOMPtr<nsIFormControl> formControl =
do_QueryInterface(inputlist->Item(i));
if (formControl) {
uint8_t controlType = formControl->ControlType();
if (controlType == NS_FORM_INPUT_PASSWORD ||
controlType == NS_FORM_INPUT_HIDDEN ||
controlType == NS_FORM_INPUT_BUTTON ||
controlType == NS_FORM_INPUT_IMAGE ||
controlType == NS_FORM_INPUT_SUBMIT ||
controlType == NS_FORM_INPUT_RESET) {
continue;
}
}
RefPtr<HTMLInputElement> input =
HTMLInputElement::FromNodeOrNull(inputlist->Item(i));
if (!input || !nsContentUtils::IsAutocompleteEnabled(input)) {
continue;
}
nsAutoString id;
input->GetId(id);
if (id.IsEmpty() && (aGeneratedCount > kMaxTraversedXPaths)) {
continue;
}
Nullable<AutocompleteInfo> aInfo;
input->GetAutocompleteInfo(aInfo);
if (!aInfo.IsNull() && !aInfo.Value().mCanAutomaticallyPersist) {
continue;
}
if (input->ControlType() == NS_FORM_INPUT_CHECKBOX ||
input->ControlType() == NS_FORM_INPUT_RADIO) {
bool checked = input->Checked();
if (checked == input->DefaultChecked()) {
continue;
}
AppendValueToCollectedData(input, id, checked, aGeneratedCount,
std::forward<ArgsT>(args)...);
} else if (input->ControlType() == NS_FORM_INPUT_FILE) {
IgnoredErrorResult rv;
nsTArray<nsString> result;
input->MozGetFileNameArray(result, rv);
if (rv.Failed() || result.Length() == 0) {
continue;
}
AppendValueToCollectedData(input, id, u"file"_ns, result, aGeneratedCount,
std::forward<ArgsT>(args)...);
} else {
nsString value;
input->GetValue(value, CallerType::System);
// In order to reduce XPath generation (which is slow), we only save data
// for form fields that have been changed. (cf. bug 537289)
// Also, don't want to collect credit card number.
if (value.IsEmpty() || IsValidCCNumber(value) ||
input->HasBeenTypePassword() ||
input->AttrValueIs(kNameSpaceID_None, nsGkAtoms::value, value,
eCaseMatters)) {
continue;
}
AppendValueToCollectedData(aDocument, input, id, value, aGeneratedCount,
std::forward<ArgsT>(args)...);
}
}
}
/* static */
template <typename... ArgsT>
void SessionStoreUtils::CollectFromSelectElement(Document& aDocument,
uint16_t& aGeneratedCount,
ArgsT&&... args) {
RefPtr<nsContentList> selectlist =
NS_GetContentList(&aDocument, kNameSpaceID_XHTML, u"select"_ns);
uint32_t length = selectlist->Length(true);
for (uint32_t i = 0; i < length; ++i) {
MOZ_ASSERT(selectlist->Item(i), "null item in node list!");
RefPtr<HTMLSelectElement> select =
HTMLSelectElement::FromNodeOrNull(selectlist->Item(i));
if (!select) {
continue;
}
nsAutoString id;
select->GetId(id);
if (id.IsEmpty() && (aGeneratedCount > kMaxTraversedXPaths)) {
continue;
}
AutocompleteInfo aInfo;
select->GetAutocompleteInfo(aInfo);
if (!aInfo.mCanAutomaticallyPersist) {
continue;
}
nsAutoCString value;
if (!select->Multiple()) {
// <select>s without the multiple attribute are hard to determine the
// default value, so assume we don't have the default.
DOMString selectVal;
select->GetValue(selectVal);
CollectedNonMultipleSelectValue val;
val.mSelectedIndex = select->SelectedIndex();
val.mValue = selectVal.AsAString();
AppendValueToCollectedData(select, id, val, aGeneratedCount,
std::forward<ArgsT>(args)...);
} else {
// <select>s with the multiple attribute are easier to determine the
// default value since each <option> has a defaultSelected property
HTMLOptionsCollection* options = select->GetOptions();
if (!options) {
continue;
}
bool hasDefaultValue = true;
nsTArray<nsString> selectslist;
uint32_t numOptions = options->Length();
for (uint32_t idx = 0; idx < numOptions; idx++) {
HTMLOptionElement* option = options->ItemAsOption(idx);
bool selected = option->Selected();
if (!selected) {
continue;
}
option->GetValue(*selectslist.AppendElement());
hasDefaultValue =
hasDefaultValue && (selected == option->DefaultSelected());
}
// In order to reduce XPath generation (which is slow), we only save data
// for form fields that have been changed. (cf. bug 537289)
if (hasDefaultValue) {
continue;
}
AppendValueToCollectedData(select, id, u"multipleSelect"_ns, selectslist,
aGeneratedCount, std::forward<ArgsT>(args)...);
}
}
}
static void CollectCurrentFormData(JSContext* aCx, Document& aDocument,
Nullable<CollectedData>& aRetVal) {
uint16_t generatedCount = 0;
/* textarea element */
SessionStoreUtils::CollectFromTextAreaElement(aDocument, generatedCount,
aRetVal);
/* input element */
SessionStoreUtils::CollectFromInputElement(aDocument, generatedCount, aCx,
aRetVal);
/* select element */
SessionStoreUtils::CollectFromSelectElement(aDocument, generatedCount, aCx,
aRetVal);
Element* bodyElement = aDocument.GetBody();
if (aDocument.HasFlag(NODE_IS_EDITABLE) && bodyElement) {
bodyElement->GetInnerHTML(aRetVal.SetValue().mInnerHTML.Construct(),
IgnoreErrors());
}
if (aRetVal.IsNull()) {
return;
}
// Store the frame's current URL with its form data so that we can compare
// it when restoring data to not inject form data into the wrong document.
nsIURI* uri = aDocument.GetDocumentURI();
if (uri) {
uri->GetSpecIgnoringRef(aRetVal.SetValue().mUrl.Construct());
}
}
MOZ_CAN_RUN_SCRIPT
static void SetElementAsString(Element* aElement, const nsAString& aValue) {
IgnoredErrorResult rv;
HTMLTextAreaElement* textArea = HTMLTextAreaElement::FromNode(aElement);
if (textArea) {
textArea->SetValue(aValue, rv);
if (!rv.Failed()) {
nsContentUtils::DispatchInputEvent(aElement);
}
return;
}
HTMLInputElement* input = HTMLInputElement::FromNode(aElement);
if (input) {
input->SetValue(aValue, CallerType::NonSystem, rv);
if (!rv.Failed()) {
nsContentUtils::DispatchInputEvent(aElement);
return;
}
}
input = HTMLInputElement::FromNodeOrNull(
nsFocusManager::GetRedirectedFocus(aElement));
if (input) {
input->SetValue(aValue, CallerType::NonSystem, rv);
if (!rv.Failed()) {
nsContentUtils::DispatchInputEvent(aElement);
}
}
}
MOZ_CAN_RUN_SCRIPT
static void SetElementAsBool(Element* aElement, bool aValue) {
HTMLInputElement* input = HTMLInputElement::FromNode(aElement);
if (input) {
bool checked = input->Checked();
if (aValue != checked) {
input->SetChecked(aValue);
nsContentUtils::DispatchInputEvent(aElement);
}
}
}
MOZ_CAN_RUN_SCRIPT
static void SetElementAsFiles(HTMLInputElement* aElement,
const CollectedFileListValue& aValue) {
nsTArray<nsString> fileList;
IgnoredErrorResult rv;
aElement->MozSetFileNameArray(aValue.mFileList, rv);
if (rv.Failed()) {
return;
}
nsContentUtils::DispatchInputEvent(aElement);
}
MOZ_CAN_RUN_SCRIPT
static void SetElementAsSelect(HTMLSelectElement* aElement,
const CollectedNonMultipleSelectValue& aValue) {
HTMLOptionsCollection* options = aElement->GetOptions();
if (!options) {
return;
}
int32_t selectIdx = options->SelectedIndex();
if (selectIdx >= 0) {
nsAutoString selectOptionVal;
options->ItemAsOption(selectIdx)->GetValue(selectOptionVal);
if (aValue.mValue.Equals(selectOptionVal)) {
return;
}
}
uint32_t numOptions = options->Length();
for (uint32_t idx = 0; idx < numOptions; idx++) {
HTMLOptionElement* option = options->ItemAsOption(idx);
nsAutoString optionValue;
option->GetValue(optionValue);
if (aValue.mValue.Equals(optionValue)) {
aElement->SetSelectedIndex(idx);
nsContentUtils::DispatchInputEvent(aElement);
}
}
}
MOZ_CAN_RUN_SCRIPT
static void SetElementAsMultiSelect(HTMLSelectElement* aElement,
const nsTArray<nsString>& aValueArray) {
bool fireEvent = false;
HTMLOptionsCollection* options = aElement->GetOptions();
if (!options) {
return;
}
uint32_t numOptions = options->Length();
for (uint32_t idx = 0; idx < numOptions; idx++) {
HTMLOptionElement* option = options->ItemAsOption(idx);
nsAutoString optionValue;
option->GetValue(optionValue);
for (uint32_t i = 0, l = aValueArray.Length(); i < l; ++i) {
if (optionValue.Equals(aValueArray[i])) {
option->SetSelected(true);
if (!option->DefaultSelected()) {
fireEvent = true;
}
}
}
}
if (fireEvent) {
nsContentUtils::DispatchInputEvent(aElement);
}
}
MOZ_CAN_RUN_SCRIPT
static void SetElementAsObject(JSContext* aCx, Element* aElement,
JS::Handle<JS::Value> aObject) {
RefPtr<HTMLInputElement> input = HTMLInputElement::FromNode(aElement);
if (input) {
if (input->ControlType() == NS_FORM_INPUT_FILE) {
CollectedFileListValue value;
if (value.Init(aCx, aObject)) {
SetElementAsFiles(input, value);
} else {
JS_ClearPendingException(aCx);
}
}
return;
}
RefPtr<HTMLSelectElement> select = HTMLSelectElement::FromNode(aElement);
if (select) {
// For Single Select Element
if (!select->Multiple()) {
CollectedNonMultipleSelectValue value;
if (value.Init(aCx, aObject)) {
SetElementAsSelect(select, value);
} else {
JS_ClearPendingException(aCx);
}
return;
}
// For Multiple Selects Element
bool isArray = false;
JS::IsArrayObject(aCx, aObject, &isArray);
if (!isArray) {
return;
}
JS::Rooted<JSObject*> arrayObj(aCx, &aObject.toObject());
uint32_t arrayLength = 0;
if (!JS::GetArrayLength(aCx, arrayObj, &arrayLength)) {
JS_ClearPendingException(aCx);
return;
}
nsTArray<nsString> array(arrayLength);
for (uint32_t arrayIdx = 0; arrayIdx < arrayLength; arrayIdx++) {
JS::Rooted<JS::Value> element(aCx);
if (!JS_GetElement(aCx, arrayObj, arrayIdx, &element)) {
JS_ClearPendingException(aCx);
return;
}
if (!element.isString()) {
return;
}
nsAutoJSString value;
if (!value.init(aCx, element)) {
JS_ClearPendingException(aCx);
return;
}
array.AppendElement(value);
}
SetElementAsMultiSelect(select, array);
}
}
MOZ_CAN_RUN_SCRIPT
static void SetRestoreData(JSContext* aCx, Element* aElement,
JS::MutableHandle<JS::Value> aObject) {
nsAutoString data;
if (nsContentUtils::StringifyJSON(aCx, aObject, data)) {
SetElementAsString(aElement, data);
} else {
JS_ClearPendingException(aCx);
}
}
MOZ_CAN_RUN_SCRIPT
static void SetInnerHTML(Document& aDocument, const CollectedData& aData) {
RefPtr<Element> bodyElement = aDocument.GetBody();
if (aDocument.HasFlag(NODE_IS_EDITABLE) && bodyElement) {
IgnoredErrorResult rv;
bodyElement->SetInnerHTML(aData.mInnerHTML.Value(),
aDocument.NodePrincipal(), rv);
if (!rv.Failed()) {
nsContentUtils::DispatchInputEvent(bodyElement);
}
}
}
class FormDataParseContext : public txIParseContext {
public:
explicit FormDataParseContext(bool aCaseInsensitive)
: mIsCaseInsensitive(aCaseInsensitive) {}
nsresult resolveNamespacePrefix(nsAtom* aPrefix, int32_t& aID) override {
if (aPrefix == nsGkAtoms::xul) {
aID = kNameSpaceID_XUL;
} else {
MOZ_ASSERT(nsDependentAtomString(aPrefix).EqualsLiteral("xhtml"));
aID = kNameSpaceID_XHTML;
}
return NS_OK;
}
nsresult resolveFunctionCall(nsAtom* aName, int32_t aID,
FunctionCall** aFunction) override {
return NS_ERROR_XPATH_UNKNOWN_FUNCTION;
}
bool caseInsensitiveNameTests() override { return mIsCaseInsensitive; }
void SetErrorOffset(uint32_t aOffset) override {}
private:
bool mIsCaseInsensitive;
};
static Element* FindNodeByXPath(JSContext* aCx, Document& aDocument,
const nsAString& aExpression) {
FormDataParseContext parsingContext(aDocument.IsHTMLDocument());
IgnoredErrorResult rv;
UniquePtr<XPathExpression> expression(
aDocument.XPathEvaluator()->CreateExpression(aExpression, &parsingContext,
&aDocument, rv));
if (rv.Failed()) {
return nullptr;
}
RefPtr<XPathResult> result = expression->Evaluate(
aCx, aDocument, XPathResult::FIRST_ORDERED_NODE_TYPE, nullptr, rv);
if (rv.Failed()) {
return nullptr;
}
return Element::FromNodeOrNull(result->GetSingleNodeValue(rv));
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY
/* static */
bool SessionStoreUtils::RestoreFormData(const GlobalObject& aGlobal,
Document& aDocument,
const CollectedData& aData) {
if (!aData.mUrl.WasPassed()) {
return true;
}
// Don't restore any data for the given frame if the URL
// stored in the form data doesn't match its current URL.
nsAutoCString url;
Unused << aDocument.GetDocumentURI()->GetSpecIgnoringRef(url);
if (!aData.mUrl.Value().Equals(url)) {
return false;
}
if (aData.mInnerHTML.WasPassed()) {
SetInnerHTML(aDocument, aData);
}
if (aData.mId.WasPassed()) {
for (auto& entry : aData.mId.Value().Entries()) {
RefPtr<Element> node = aDocument.GetElementById(entry.mKey);
if (node == nullptr) {
continue;
}
if (entry.mValue.IsString()) {
SetElementAsString(node, entry.mValue.GetAsString());
} else if (entry.mValue.IsBoolean()) {
SetElementAsBool(node, entry.mValue.GetAsBoolean());
} else {
// For about:{sessionrestore,welcomeback} we saved the field as JSON to
// avoid nested instances causing humongous sessionstore.js files.
// cf. bug 467409
JSContext* cx = aGlobal.Context();
if (entry.mKey.EqualsLiteral("sessionData")) {
nsAutoCString url;
Unused << aDocument.GetDocumentURI()->GetSpecIgnoringRef(url);
if (url.EqualsLiteral("about:sessionrestore") ||
url.EqualsLiteral("about:welcomeback")) {
JS::Rooted<JS::Value> object(
cx, JS::ObjectValue(*entry.mValue.GetAsObject()));
SetRestoreData(cx, node, &object);
continue;
}
}
JS::Rooted<JS::Value> object(
cx, JS::ObjectValue(*entry.mValue.GetAsObject()));
SetElementAsObject(cx, node, object);
}
}
}
if (aData.mXpath.WasPassed()) {
for (auto& entry : aData.mXpath.Value().Entries()) {
RefPtr<Element> node =
FindNodeByXPath(aGlobal.Context(), aDocument, entry.mKey);
if (node == nullptr) {
continue;
}
if (entry.mValue.IsString()) {
SetElementAsString(node, entry.mValue.GetAsString());
} else if (entry.mValue.IsBoolean()) {
SetElementAsBool(node, entry.mValue.GetAsBoolean());
} else {
JS::Rooted<JS::Value> object(
aGlobal.Context(), JS::ObjectValue(*entry.mValue.GetAsObject()));
SetElementAsObject(aGlobal.Context(), node, object);
}
}
}
return true;
}
/* Read entries in the session storage data contained in a tab's history. */
static void ReadAllEntriesFromStorage(nsPIDOMWindowOuter* aWindow,
nsTArray<nsCString>& aOrigins,
nsTArray<nsString>& aKeys,
nsTArray<nsString>& aValues) {
BrowsingContext* const browsingContext = aWindow->GetBrowsingContext();
if (!browsingContext) {
return;
}
Document* doc = aWindow->GetDoc();
if (!doc) {
return;
}
nsCOMPtr<nsIPrincipal> principal = doc->NodePrincipal();
if (!principal) {
return;
}
nsCOMPtr<nsIPrincipal> storagePrincipal = doc->EffectiveStoragePrincipal();
if (!storagePrincipal) {
return;
}
nsAutoCString origin;
nsresult rv = storagePrincipal->GetOrigin(origin);
if (NS_FAILED(rv) || aOrigins.Contains(origin)) {
// Don't read a host twice.
return;
}
/* Completed checking for recursion and is about to read storage*/
const RefPtr<SessionStorageManager> storageManager =
browsingContext->GetSessionStorageManager();
if (!storageManager) {
return;
}
RefPtr<Storage> storage;
storageManager->GetStorage(aWindow->GetCurrentInnerWindow(), principal,
storagePrincipal, false, getter_AddRefs(storage));
if (!storage) {
return;
}
mozilla::IgnoredErrorResult result;
uint32_t len = storage->GetLength(*principal, result);
if (result.Failed() || len == 0) {
return;
}
int64_t storageUsage = storage->GetOriginQuotaUsage();
if (storageUsage > StaticPrefs::browser_sessionstore_dom_storage_limit()) {
return;
}
for (uint32_t i = 0; i < len; i++) {
nsString key, value;
mozilla::IgnoredErrorResult res;
storage->Key(i, key, *principal, res);
if (res.Failed()) {
continue;
}
storage->GetItem(key, value, *principal, res);
if (res.Failed()) {
continue;
}
aKeys.AppendElement(key);
aValues.AppendElement(value);
aOrigins.AppendElement(origin);
}
}
/* Collect Collect session storage from current frame and all child frame */
/* static */
void SessionStoreUtils::CollectedSessionStorage(
BrowsingContext* aBrowsingContext, nsTArray<nsCString>& aOrigins,
nsTArray<nsString>& aKeys, nsTArray<nsString>& aValues) {
/* Collect session store from current frame */
nsPIDOMWindowOuter* window = aBrowsingContext->GetDOMWindow();
if (!window) {
return;
}
ReadAllEntriesFromStorage(window, aOrigins, aKeys, aValues);
/* Collect session storage from all child frame */
if (!window->GetDocShell()) {
return;
}
// This is not going to work for fission. Bug 1572084 for tracking it.
for (BrowsingContext* child : aBrowsingContext->Children()) {
if (!child->CreatedDynamically()) {
SessionStoreUtils::CollectedSessionStorage(child, aOrigins, aKeys,
aValues);
}
}
}
/* static */
void SessionStoreUtils::RestoreSessionStorage(
const GlobalObject& aGlobal, nsIDocShell* aDocShell,
const Record<nsString, Record<nsString, nsString>>& aData) {
for (auto& entry : aData.Entries()) {
// NOTE: In capture() we record the full origin for the URI which the
// sessionStorage is being captured for. As of bug 1235657 this code
// stopped parsing any origins which have originattributes correctly, as
// it decided to use the origin attributes from the docshell, and try to
// interpret the origin as a URI. Since bug 1353844 this code now correctly
// parses the full origin, and then discards the origin attributes, to
// make the behavior line up with the original intentions in bug 1235657
// while preserving the ability to read all session storage from
// previous versions. In the future, if this behavior is desired, we may
// want to use the spec instead of the origin as the key, and avoid
// transmitting origin attribute information which we then discard when
// restoring.
//
// If changing this logic, make sure to also change the principal
// computation logic in SessionStore::_sendRestoreHistory.
// OriginAttributes are always after a '^' character
int32_t pos = entry.mKey.RFindChar('^');
nsCOMPtr<nsIPrincipal> principal = BasePrincipal::CreateContentPrincipal(
NS_ConvertUTF16toUTF8(Substring(entry.mKey, 0, pos)));
BrowsingContext* const browsingContext =
nsDocShell::Cast(aDocShell)->GetBrowsingContext();
if (!browsingContext) {
return;
}
nsCOMPtr<nsIPrincipal> storagePrincipal =
BasePrincipal::CreateContentPrincipal(
NS_ConvertUTF16toUTF8(entry.mKey));
const RefPtr<SessionStorageManager> storageManager =
browsingContext->GetSessionStorageManager();
if (!storageManager) {
return;
}
RefPtr<Storage> storage;
// There is no need to pass documentURI, it's only used to fill documentURI
// property of domstorage event, which in this case has no consumer.
// Prevention of events in case of missing documentURI will be solved in a
// followup bug to bug 600307.
// Null window because the current window doesn't match the principal yet
// and loads about:blank.
storageManager->CreateStorage(nullptr, principal, storagePrincipal, u""_ns,
false, getter_AddRefs(storage));
if (!storage) {
continue;
}
for (auto& InnerEntry : entry.mValue.Entries()) {
IgnoredErrorResult result;
storage->SetItem(InnerEntry.mKey, InnerEntry.mValue, *principal, result);
if (result.Failed()) {
NS_WARNING("storage set item failed!");
}
}
}
}
typedef void (*CollectorFunc)(JSContext* aCx, Document& aDocument,
Nullable<CollectedData>& aRetVal);
/**
* A function that will recursively call |CollectorFunc| to collect data for all
* non-dynamic frames in the current frame/docShell tree.
*/
static void CollectFrameTreeData(JSContext* aCx,
BrowsingContext* aBrowsingContext,
Nullable<CollectedData>& aRetVal,
CollectorFunc aFunc) {
if (aBrowsingContext->CreatedDynamically()) {
return;
}
nsPIDOMWindowOuter* window = aBrowsingContext->GetDOMWindow();
if (!window || !window->GetDocShell()) {
return;
}
Document* document = window->GetDoc();
if (!document) {
return;
}
/* Collect data from current frame */
aFunc(aCx, *document, aRetVal);
/* Collect data from all child frame */
nsTArray<JSObject*> childrenData;
SequenceRooter<JSObject*> rooter(aCx, &childrenData);
uint32_t trailingNullCounter = 0;
// This is not going to work for fission. Bug 1572084 for tracking it.
for (auto& child : aBrowsingContext->Children()) {
NullableRootedDictionary<CollectedData> data(aCx);
CollectFrameTreeData(aCx, child, data, aFunc);
if (data.IsNull()) {
childrenData.AppendElement(nullptr);
trailingNullCounter++;
continue;
}
JS::Rooted<JS::Value> jsval(aCx);
if (!ToJSValue(aCx, data.SetValue(), &jsval)) {
JS_ClearPendingException(aCx);
continue;
}
childrenData.AppendElement(&jsval.toObject());
trailingNullCounter = 0;
}
if (trailingNullCounter != childrenData.Length()) {
childrenData.TruncateLength(childrenData.Length() - trailingNullCounter);
aRetVal.SetValue().mChildren.Construct() = std::move(childrenData);
}
}
/* static */ void SessionStoreUtils::CollectScrollPosition(
const GlobalObject& aGlobal, WindowProxyHolder& aWindow,
Nullable<CollectedData>& aRetVal) {
CollectFrameTreeData(aGlobal.Context(), aWindow.get(), aRetVal,
CollectCurrentScrollPosition);
}
/* static */ void SessionStoreUtils::CollectFormData(
const GlobalObject& aGlobal, WindowProxyHolder& aWindow,
Nullable<CollectedData>& aRetVal) {
CollectFrameTreeData(aGlobal.Context(), aWindow.get(), aRetVal,
CollectCurrentFormData);
}
/* static */ void SessionStoreUtils::ComposeInputData(
const nsTArray<CollectedInputDataValue>& aData, InputElementData& ret) {
nsTArray<int> selectedIndex, valueIdx;
nsTArray<nsString> id, selectVal, strVal, type;
nsTArray<bool> boolVal;
for (const CollectedInputDataValue& data : aData) {
id.AppendElement(data.id);
type.AppendElement(data.type);
if (data.value.is<mozilla::dom::CollectedNonMultipleSelectValue>()) {
valueIdx.AppendElement(selectVal.Length());
selectedIndex.AppendElement(
data.value.as<mozilla::dom::CollectedNonMultipleSelectValue>()
.mSelectedIndex);
selectVal.AppendElement(
data.value.as<mozilla::dom::CollectedNonMultipleSelectValue>()
.mValue);
} else if (data.value.is<CopyableTArray<nsString>>()) {
// The first valueIdx is "index of the first string value"
valueIdx.AppendElement(strVal.Length());
strVal.AppendElements(data.value.as<CopyableTArray<nsString>>());
// The second valueIdx is "index of the last string value" + 1
id.AppendElement(data.id);
type.AppendElement(data.type);
valueIdx.AppendElement(strVal.Length());
} else if (data.value.is<nsString>()) {
valueIdx.AppendElement(strVal.Length());
strVal.AppendElement(data.value.as<nsString>());
} else if (data.type.EqualsLiteral("bool")) {
valueIdx.AppendElement(boolVal.Length());
boolVal.AppendElement(data.value.as<bool>());
}
}
if (selectedIndex.Length() != 0) {
ret.mSelectedIndex.Construct(std::move(selectedIndex));
}
if (valueIdx.Length() != 0) {
ret.mValueIdx.Construct(std::move(valueIdx));
}
if (id.Length() != 0) {
ret.mId.Construct(std::move(id));
}
if (selectVal.Length() != 0) {
ret.mSelectVal.Construct(std::move(selectVal));
}
if (strVal.Length() != 0) {
ret.mStrVal.Construct(std::move(strVal));
}
if (type.Length() != 0) {
ret.mType.Construct(std::move(type));
}
if (boolVal.Length() != 0) {
ret.mBoolVal.Construct(std::move(boolVal));
}
}
|