summaryrefslogtreecommitdiffstats
path: root/dom/webbrowserpersist/nsWebBrowserPersist.cpp
blob: 2a83a166cfc6ca959dd7d9f2a7971d8c54f2cd8b (plain)
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
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/ArrayUtils.h"
#include "mozilla/TextUtils.h"

#include "nspr.h"

#include "nsIFileStreams.h"  // New Necko file streams
#include <algorithm>

#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsIClassOfService.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsILoadContext.h"
#include "nsIPrivateBrowsingChannel.h"
#include "nsComponentManagerUtils.h"
#include "nsIStorageStream.h"
#include "nsISeekableStream.h"
#include "nsIHttpChannel.h"
#include "nsIEncodedChannel.h"
#include "nsIUploadChannel.h"
#include "nsICacheInfoChannel.h"
#include "nsIFileChannel.h"
#include "nsEscape.h"
#include "nsUnicharUtils.h"
#include "nsIStringEnumerator.h"
#include "nsContentCID.h"
#include "nsStreamUtils.h"

#include "nsCExternalHandlerService.h"

#include "nsIURL.h"
#include "nsIFileURL.h"
#include "nsIWebProgressListener.h"
#include "nsIAuthPrompt.h"
#include "nsIPrompt.h"
#include "nsIFormControl.h"
#include "nsIThreadRetargetableRequest.h"
#include "nsContentUtils.h"

#include "nsIStringBundle.h"
#include "nsIProtocolHandler.h"

#include "nsWebBrowserPersist.h"
#include "WebBrowserPersistLocalDocument.h"

#include "nsIContent.h"
#include "nsIMIMEInfo.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/HTMLSharedElement.h"
#include "mozilla/net/CookieJarSettings.h"
#include "mozilla/Mutex.h"
#include "mozilla/Printf.h"
#include "ReferrerInfo.h"
#include "nsIURIMutator.h"
#include "mozilla/WebBrowserPersistDocumentParent.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/PContentParent.h"
#include "mozilla/dom/BrowserParent.h"
#include "nsIDocumentEncoder.h"

using namespace mozilla;
using namespace mozilla::dom;

// Buffer file writes in 32kb chunks
#define BUFFERED_OUTPUT_SIZE (1024 * 32)

struct nsWebBrowserPersist::WalkData {
  nsCOMPtr<nsIWebBrowserPersistDocument> mDocument;
  nsCOMPtr<nsIURI> mFile;
  nsCOMPtr<nsIURI> mDataPath;
};

// Information about a DOM document
struct nsWebBrowserPersist::DocData {
  nsCOMPtr<nsIURI> mBaseURI;
  nsCOMPtr<nsIWebBrowserPersistDocument> mDocument;
  nsCOMPtr<nsIURI> mFile;
  nsCString mCharset;
};

// Information about a URI
struct nsWebBrowserPersist::URIData {
  bool mNeedsPersisting;
  bool mSaved;
  bool mIsSubFrame;
  bool mDataPathIsRelative;
  bool mNeedsFixup;
  nsString mFilename;
  nsString mSubFrameExt;
  nsCOMPtr<nsIURI> mFile;
  nsCOMPtr<nsIURI> mDataPath;
  nsCOMPtr<nsIURI> mRelativeDocumentURI;
  nsCOMPtr<nsIPrincipal> mTriggeringPrincipal;
  nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
  nsContentPolicyType mContentPolicyType;
  nsCString mRelativePathToData;
  nsCString mCharset;

  nsresult GetLocalURI(nsIURI* targetBaseURI, nsCString& aSpecOut);
};

// Information about the output stream
// Note that this data structure (and the map that nsWebBrowserPersist keeps,
// where these are values) is used from two threads: the main thread,
// and the background task thread.
// The background thread only writes to mStream (from OnDataAvailable), and
// this access is guarded using mStreamMutex. It reads the mFile member, which
// is only written to on the main thread when the object is constructed and
// from OnStartRequest (if mCalcFileExt), both guaranteed to happen before
// OnDataAvailable is fired.
// The main thread gets OnStartRequest, OnStopRequest, and progress sink events,
// and accesses the other members.
struct nsWebBrowserPersist::OutputData {
  nsCOMPtr<nsIURI> mFile;
  nsCOMPtr<nsIURI> mOriginalLocation;
  nsCOMPtr<nsIOutputStream> mStream;
  Mutex mStreamMutex MOZ_UNANNOTATED;
  int64_t mSelfProgress;
  int64_t mSelfProgressMax;
  bool mCalcFileExt;

  OutputData(nsIURI* aFile, nsIURI* aOriginalLocation, bool aCalcFileExt)
      : mFile(aFile),
        mOriginalLocation(aOriginalLocation),
        mStreamMutex("nsWebBrowserPersist::OutputData::mStreamMutex"),
        mSelfProgress(0),
        mSelfProgressMax(10000),
        mCalcFileExt(aCalcFileExt) {}
  ~OutputData() {
    // Gaining this lock in the destructor is pretty icky. It should be OK
    // because the only other place we lock the mutex is in OnDataAvailable,
    // which will never itself cause the OutputData instance to be
    // destroyed.
    MutexAutoLock lock(mStreamMutex);
    if (mStream) {
      mStream->Close();
    }
  }
};

struct nsWebBrowserPersist::UploadData {
  nsCOMPtr<nsIURI> mFile;
  int64_t mSelfProgress;
  int64_t mSelfProgressMax;

  explicit UploadData(nsIURI* aFile)
      : mFile(aFile), mSelfProgress(0), mSelfProgressMax(10000) {}
};

struct nsWebBrowserPersist::CleanupData {
  nsCOMPtr<nsIFile> mFile;
  // Snapshot of what the file actually is at the time of creation so that if
  // it transmutes into something else later on it can be ignored. For example,
  // catch files that turn into dirs or vice versa.
  bool mIsDirectory;
};

class nsWebBrowserPersist::OnWalk final
    : public nsIWebBrowserPersistResourceVisitor {
 public:
  OnWalk(nsWebBrowserPersist* aParent, nsIURI* aFile, nsIFile* aDataPath)
      : mParent(aParent),
        mFile(aFile),
        mDataPath(aDataPath),
        mPendingDocuments(1),
        mStatus(NS_OK) {}

  NS_DECL_NSIWEBBROWSERPERSISTRESOURCEVISITOR
  NS_DECL_ISUPPORTS
 private:
  RefPtr<nsWebBrowserPersist> mParent;
  nsCOMPtr<nsIURI> mFile;
  nsCOMPtr<nsIFile> mDataPath;

  uint32_t mPendingDocuments;
  nsresult mStatus;

  virtual ~OnWalk() = default;
};

NS_IMPL_ISUPPORTS(nsWebBrowserPersist::OnWalk,
                  nsIWebBrowserPersistResourceVisitor)

class nsWebBrowserPersist::OnRemoteWalk final
    : public nsIWebBrowserPersistDocumentReceiver {
 public:
  OnRemoteWalk(nsIWebBrowserPersistResourceVisitor* aVisitor,
               nsIWebBrowserPersistDocument* aDocument)
      : mVisitor(aVisitor), mDocument(aDocument) {}

  NS_DECL_NSIWEBBROWSERPERSISTDOCUMENTRECEIVER
  NS_DECL_ISUPPORTS
 private:
  nsCOMPtr<nsIWebBrowserPersistResourceVisitor> mVisitor;
  nsCOMPtr<nsIWebBrowserPersistDocument> mDocument;

  virtual ~OnRemoteWalk() = default;
};

NS_IMPL_ISUPPORTS(nsWebBrowserPersist::OnRemoteWalk,
                  nsIWebBrowserPersistDocumentReceiver)

class nsWebBrowserPersist::OnWrite final
    : public nsIWebBrowserPersistWriteCompletion {
 public:
  OnWrite(nsWebBrowserPersist* aParent, nsIURI* aFile, nsIFile* aLocalFile)
      : mParent(aParent), mFile(aFile), mLocalFile(aLocalFile) {}

  NS_DECL_NSIWEBBROWSERPERSISTWRITECOMPLETION
  NS_DECL_ISUPPORTS
 private:
  RefPtr<nsWebBrowserPersist> mParent;
  nsCOMPtr<nsIURI> mFile;
  nsCOMPtr<nsIFile> mLocalFile;

  virtual ~OnWrite() = default;
};

NS_IMPL_ISUPPORTS(nsWebBrowserPersist::OnWrite,
                  nsIWebBrowserPersistWriteCompletion)

class nsWebBrowserPersist::FlatURIMap final
    : public nsIWebBrowserPersistURIMap {
 public:
  explicit FlatURIMap(const nsACString& aTargetBase)
      : mTargetBase(aTargetBase) {}

  void Add(const nsACString& aMapFrom, const nsACString& aMapTo) {
    mMapFrom.AppendElement(aMapFrom);
    mMapTo.AppendElement(aMapTo);
  }

  NS_DECL_NSIWEBBROWSERPERSISTURIMAP
  NS_DECL_ISUPPORTS

 private:
  nsTArray<nsCString> mMapFrom;
  nsTArray<nsCString> mMapTo;
  nsCString mTargetBase;

  virtual ~FlatURIMap() = default;
};

NS_IMPL_ISUPPORTS(nsWebBrowserPersist::FlatURIMap, nsIWebBrowserPersistURIMap)

NS_IMETHODIMP
nsWebBrowserPersist::FlatURIMap::GetNumMappedURIs(uint32_t* aNum) {
  MOZ_ASSERT(mMapFrom.Length() == mMapTo.Length());
  *aNum = mMapTo.Length();
  return NS_OK;
}

NS_IMETHODIMP
nsWebBrowserPersist::FlatURIMap::GetTargetBaseURI(nsACString& aTargetBase) {
  aTargetBase = mTargetBase;
  return NS_OK;
}

NS_IMETHODIMP
nsWebBrowserPersist::FlatURIMap::GetURIMapping(uint32_t aIndex,
                                               nsACString& aMapFrom,
                                               nsACString& aMapTo) {
  MOZ_ASSERT(mMapFrom.Length() == mMapTo.Length());
  if (aIndex >= mMapTo.Length()) {
    return NS_ERROR_INVALID_ARG;
  }
  aMapFrom = mMapFrom[aIndex];
  aMapTo = mMapTo[aIndex];
  return NS_OK;
}

// Maximum file length constant. The max file name length is
// volume / server dependent but it is difficult to obtain
// that information. Instead this constant is a reasonable value that
// modern systems should able to cope with.
const uint32_t kDefaultMaxFilenameLength = 64;

// Default flags for persistence
const uint32_t kDefaultPersistFlags =
    nsIWebBrowserPersist::PERSIST_FLAGS_NO_CONVERSION |
    nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES;

// String bundle where error messages come from
const char* kWebBrowserPersistStringBundle =
    "chrome://global/locale/nsWebBrowserPersist.properties";

nsWebBrowserPersist::nsWebBrowserPersist()
    : mCurrentDataPathIsRelative(false),
      mCurrentThingsToPersist(0),
      mOutputMapMutex("nsWebBrowserPersist::mOutputMapMutex"),
      mFirstAndOnlyUse(true),
      mSavingDocument(false),
      mCancel(false),
      mEndCalled(false),
      mCompleted(false),
      mStartSaving(false),
      mReplaceExisting(true),
      mSerializingOutput(false),
      mIsPrivate(false),
      mPersistFlags(kDefaultPersistFlags),
      mPersistResult(NS_OK),
      mTotalCurrentProgress(0),
      mTotalMaxProgress(0),
      mWrapColumn(72),
      mEncodingFlags(0) {}

nsWebBrowserPersist::~nsWebBrowserPersist() { Cleanup(); }

//*****************************************************************************
// nsWebBrowserPersist::nsISupports
//*****************************************************************************

NS_IMPL_ADDREF(nsWebBrowserPersist)
NS_IMPL_RELEASE(nsWebBrowserPersist)

NS_INTERFACE_MAP_BEGIN(nsWebBrowserPersist)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIWebBrowserPersist)
  NS_INTERFACE_MAP_ENTRY(nsIWebBrowserPersist)
  NS_INTERFACE_MAP_ENTRY(nsICancelable)
  NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
  NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
  NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableStreamListener)
  NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
  NS_INTERFACE_MAP_ENTRY(nsIProgressEventSink)
NS_INTERFACE_MAP_END

//*****************************************************************************
// nsWebBrowserPersist::nsIInterfaceRequestor
//*****************************************************************************

NS_IMETHODIMP nsWebBrowserPersist::GetInterface(const nsIID& aIID,
                                                void** aIFace) {
  NS_ENSURE_ARG_POINTER(aIFace);

  *aIFace = nullptr;

  nsresult rv = QueryInterface(aIID, aIFace);
  if (NS_SUCCEEDED(rv)) {
    return rv;
  }

  if (mProgressListener && (aIID.Equals(NS_GET_IID(nsIAuthPrompt)) ||
                            aIID.Equals(NS_GET_IID(nsIPrompt)))) {
    mProgressListener->QueryInterface(aIID, aIFace);
    if (*aIFace) return NS_OK;
  }

  nsCOMPtr<nsIInterfaceRequestor> req = do_QueryInterface(mProgressListener);
  if (req) {
    return req->GetInterface(aIID, aIFace);
  }

  return NS_ERROR_NO_INTERFACE;
}

//*****************************************************************************
// nsWebBrowserPersist::nsIWebBrowserPersist
//*****************************************************************************

NS_IMETHODIMP nsWebBrowserPersist::GetPersistFlags(uint32_t* aPersistFlags) {
  NS_ENSURE_ARG_POINTER(aPersistFlags);
  *aPersistFlags = mPersistFlags;
  return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::SetPersistFlags(uint32_t aPersistFlags) {
  mPersistFlags = aPersistFlags;
  mReplaceExisting = (mPersistFlags & PERSIST_FLAGS_REPLACE_EXISTING_FILES);
  mSerializingOutput = (mPersistFlags & PERSIST_FLAGS_SERIALIZE_OUTPUT);
  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::GetCurrentState(uint32_t* aCurrentState) {
  NS_ENSURE_ARG_POINTER(aCurrentState);
  if (mCompleted) {
    *aCurrentState = PERSIST_STATE_FINISHED;
  } else if (mFirstAndOnlyUse) {
    *aCurrentState = PERSIST_STATE_SAVING;
  } else {
    *aCurrentState = PERSIST_STATE_READY;
  }
  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::GetResult(nsresult* aResult) {
  NS_ENSURE_ARG_POINTER(aResult);
  *aResult = mPersistResult;
  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::GetProgressListener(
    nsIWebProgressListener** aProgressListener) {
  NS_ENSURE_ARG_POINTER(aProgressListener);
  *aProgressListener = mProgressListener;
  NS_IF_ADDREF(*aProgressListener);
  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::SetProgressListener(
    nsIWebProgressListener* aProgressListener) {
  mProgressListener = aProgressListener;
  mProgressListener2 = do_QueryInterface(aProgressListener);
  mEventSink = do_GetInterface(aProgressListener);
  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::SaveURI(
    nsIURI* aURI, nsIPrincipal* aPrincipal, uint32_t aCacheKey,
    nsIReferrerInfo* aReferrerInfo, nsICookieJarSettings* aCookieJarSettings,
    nsIInputStream* aPostData, const char* aExtraHeaders, nsISupports* aFile,
    nsContentPolicyType aContentPolicy, bool aIsPrivate) {
  NS_ENSURE_TRUE(mFirstAndOnlyUse, NS_ERROR_FAILURE);
  mFirstAndOnlyUse = false;  // Stop people from reusing this object!

  nsCOMPtr<nsIURI> fileAsURI;
  nsresult rv;
  rv = GetValidURIFromObject(aFile, getter_AddRefs(fileAsURI));
  NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);

  // SaveURIInternal doesn't like broken uris.
  mPersistFlags |= PERSIST_FLAGS_FAIL_ON_BROKEN_LINKS;
  rv = SaveURIInternal(aURI, aPrincipal, aContentPolicy, aCacheKey,
                       aReferrerInfo, aCookieJarSettings, aPostData,
                       aExtraHeaders, fileAsURI, false, aIsPrivate);
  return NS_FAILED(rv) ? rv : NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::SaveChannel(nsIChannel* aChannel,
                                               nsISupports* aFile) {
  NS_ENSURE_TRUE(mFirstAndOnlyUse, NS_ERROR_FAILURE);
  mFirstAndOnlyUse = false;  // Stop people from reusing this object!

  nsCOMPtr<nsIURI> fileAsURI;
  nsresult rv;
  rv = GetValidURIFromObject(aFile, getter_AddRefs(fileAsURI));
  NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);

  rv = aChannel->GetURI(getter_AddRefs(mURI));
  NS_ENSURE_SUCCESS(rv, rv);

  // SaveChannelInternal doesn't like broken uris.
  mPersistFlags |= PERSIST_FLAGS_FAIL_ON_BROKEN_LINKS;
  rv = SaveChannelInternal(aChannel, fileAsURI, false);
  return NS_FAILED(rv) ? rv : NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::SaveDocument(nsISupports* aDocument,
                                                nsISupports* aFile,
                                                nsISupports* aDataPath,
                                                const char* aOutputContentType,
                                                uint32_t aEncodingFlags,
                                                uint32_t aWrapColumn) {
  NS_ENSURE_TRUE(mFirstAndOnlyUse, NS_ERROR_FAILURE);
  mFirstAndOnlyUse = false;  // Stop people from reusing this object!

  // We need a STATE_IS_NETWORK start/stop pair to bracket the
  // notification callbacks.  For a whole document we generate those
  // here and in EndDownload(), but for the single-request methods
  // that's done in On{Start,Stop}Request instead.
  mSavingDocument = true;

  NS_ENSURE_ARG_POINTER(aDocument);
  NS_ENSURE_ARG_POINTER(aFile);

  nsCOMPtr<nsIURI> fileAsURI;
  nsCOMPtr<nsIURI> datapathAsURI;
  nsresult rv;

  rv = GetValidURIFromObject(aFile, getter_AddRefs(fileAsURI));
  NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);
  if (aDataPath) {
    rv = GetValidURIFromObject(aDataPath, getter_AddRefs(datapathAsURI));
    NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);
  }

  mWrapColumn = aWrapColumn;
  mEncodingFlags = aEncodingFlags;

  if (aOutputContentType) {
    mContentType.AssignASCII(aOutputContentType);
  }

  // State start notification
  if (mProgressListener) {
    mProgressListener->OnStateChange(
        nullptr, nullptr,
        nsIWebProgressListener::STATE_START |
            nsIWebProgressListener::STATE_IS_NETWORK,
        NS_OK);
  }

  nsCOMPtr<nsIWebBrowserPersistDocument> doc = do_QueryInterface(aDocument);
  if (!doc) {
    nsCOMPtr<Document> localDoc = do_QueryInterface(aDocument);
    if (localDoc) {
      doc = new mozilla::WebBrowserPersistLocalDocument(localDoc);
    } else {
      rv = NS_ERROR_NO_INTERFACE;
    }
  }

  bool closed = false;
  if (doc && NS_SUCCEEDED(doc->GetIsClosed(&closed)) && !closed) {
    rv = SaveDocumentInternal(doc, fileAsURI, datapathAsURI);
  }

  if (NS_FAILED(rv) || closed) {
    SendErrorStatusChange(true, rv, nullptr, mURI);
    EndDownload(rv);
  }
  return rv;
}

NS_IMETHODIMP nsWebBrowserPersist::Cancel(nsresult aReason) {
  // No point cancelling if we're already complete.
  if (mEndCalled) {
    return NS_OK;
  }
  mCancel = true;
  EndDownload(aReason);
  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::CancelSave() {
  return Cancel(NS_BINDING_ABORTED);
}

nsresult nsWebBrowserPersist::StartUpload(nsIStorageStream* storStream,
                                          nsIURI* aDestinationURI,
                                          const nsACString& aContentType) {
  // setup the upload channel if the destination is not local
  nsCOMPtr<nsIInputStream> inputstream;
  nsresult rv = storStream->NewInputStream(0, getter_AddRefs(inputstream));
  NS_ENSURE_TRUE(inputstream, NS_ERROR_FAILURE);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
  return StartUpload(inputstream, aDestinationURI, aContentType);
}

nsresult nsWebBrowserPersist::StartUpload(nsIInputStream* aInputStream,
                                          nsIURI* aDestinationURI,
                                          const nsACString& aContentType) {
  nsCOMPtr<nsIChannel> destChannel;
  CreateChannelFromURI(aDestinationURI, getter_AddRefs(destChannel));
  nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(destChannel));
  NS_ENSURE_TRUE(uploadChannel, NS_ERROR_FAILURE);

  // Set the upload stream
  // NOTE: ALL data must be available in "inputstream"
  nsresult rv = uploadChannel->SetUploadStream(aInputStream, aContentType, -1);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
  rv = destChannel->AsyncOpen(this);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // add this to the upload list
  nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(destChannel);
  mUploadList.InsertOrUpdate(keyPtr, MakeUnique<UploadData>(aDestinationURI));

  return NS_OK;
}

void nsWebBrowserPersist::SerializeNextFile() {
  nsresult rv = NS_OK;
  MOZ_ASSERT(mWalkStack.Length() == 0);

  // First, handle gathered URIs.
  // This is potentially O(n^2), when taking into account the
  // number of times this method is called.  If it becomes a
  // bottleneck, the count of not-yet-persisted URIs could be
  // maintained separately, and we can skip iterating mURIMap if there are none.

  // Persist each file in the uri map. The document(s)
  // will be saved after the last one of these is saved.
  for (const auto& entry : mURIMap) {
    URIData* data = entry.GetWeak();

    if (!data->mNeedsPersisting || data->mSaved) {
      continue;
    }

    // Create a URI from the key.
    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), entry.GetKey(), data->mCharset.get());
    if (NS_WARN_IF(NS_FAILED(rv))) {
      break;
    }

    // Make a URI to save the data to.
    nsCOMPtr<nsIURI> fileAsURI = data->mDataPath;
    rv = AppendPathToURI(fileAsURI, data->mFilename, fileAsURI);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      break;
    }

    rv = SaveURIInternal(uri, data->mTriggeringPrincipal,
                         data->mContentPolicyType, 0, nullptr,
                         data->mCookieJarSettings, nullptr, nullptr, fileAsURI,
                         true, mIsPrivate);
    // If SaveURIInternal fails, then it will have called EndDownload,
    // which means that |data| is no longer valid memory. We MUST bail.
    if (NS_WARN_IF(NS_FAILED(rv))) {
      break;
    }

    if (rv == NS_OK) {
      // URIData.mFile will be updated to point to the correct
      // URI object when it is fixed up with the right file extension
      // in OnStartRequest
      data->mFile = fileAsURI;
      data->mSaved = true;
    } else {
      data->mNeedsFixup = false;
    }

    if (mSerializingOutput) {
      break;
    }
  }

  // If there are downloads happening, wait until they're done; the
  // OnStopRequest handler will call this method again.
  if (mOutputMap.Count() > 0) {
    return;
  }

  // If serializing, also wait until last upload is done.
  if (mSerializingOutput && mUploadList.Count() > 0) {
    return;
  }

  // If there are also no more documents, then we're done.
  if (mDocList.Length() == 0) {
    // ...or not quite done, if there are still uploads.
    if (mUploadList.Count() > 0) {
      return;
    }
    // Finish and clean things up.  Defer this because the caller
    // may have been expecting to use the listeners that that
    // method will clear.
    NS_DispatchToCurrentThread(
        NewRunnableMethod("nsWebBrowserPersist::FinishDownload", this,
                          &nsWebBrowserPersist::FinishDownload));
    return;
  }

  // There are no URIs to save, so just save the next document.
  mStartSaving = true;
  mozilla::UniquePtr<DocData> docData(mDocList.ElementAt(0));
  mDocList.RemoveElementAt(0);  // O(n^2) but probably doesn't matter.
  MOZ_ASSERT(docData);
  if (!docData) {
    EndDownload(NS_ERROR_FAILURE);
    return;
  }

  mCurrentBaseURI = docData->mBaseURI;
  mCurrentCharset = docData->mCharset;
  mTargetBaseURI = docData->mFile;

  // Save the document, fixing it up with the new URIs as we do

  nsAutoCString targetBaseSpec;
  if (mTargetBaseURI) {
    rv = mTargetBaseURI->GetSpec(targetBaseSpec);
    if (NS_FAILED(rv)) {
      SendErrorStatusChange(true, rv, nullptr, nullptr);
      EndDownload(rv);
      return;
    }
  }

  // mFlatURIMap must be rebuilt each time through SerializeNextFile, as
  // mTargetBaseURI is used to create the relative URLs and will be different
  // with each serialized document.
  RefPtr<FlatURIMap> flatMap = new FlatURIMap(targetBaseSpec);
  for (const auto& uriEntry : mURIMap) {
    nsAutoCString mapTo;
    nsresult rv = uriEntry.GetWeak()->GetLocalURI(mTargetBaseURI, mapTo);
    if (NS_SUCCEEDED(rv) || !mapTo.IsVoid()) {
      flatMap->Add(uriEntry.GetKey(), mapTo);
    }
  }
  mFlatURIMap = std::move(flatMap);

  nsCOMPtr<nsIFile> localFile;
  GetLocalFileFromURI(docData->mFile, getter_AddRefs(localFile));
  if (localFile) {
    // if we're not replacing an existing file but the file
    // exists, something is wrong
    bool fileExists = false;
    rv = localFile->Exists(&fileExists);
    if (NS_SUCCEEDED(rv) && !mReplaceExisting && fileExists) {
      rv = NS_ERROR_FILE_ALREADY_EXISTS;
    }
    if (NS_FAILED(rv)) {
      SendErrorStatusChange(false, rv, nullptr, docData->mFile);
      EndDownload(rv);
      return;
    }
  }
  nsCOMPtr<nsIOutputStream> outputStream;
  rv = MakeOutputStream(docData->mFile, getter_AddRefs(outputStream));
  if (NS_SUCCEEDED(rv) && !outputStream) {
    rv = NS_ERROR_FAILURE;
  }
  if (NS_FAILED(rv)) {
    SendErrorStatusChange(false, rv, nullptr, docData->mFile);
    EndDownload(rv);
    return;
  }

  RefPtr<OnWrite> finish = new OnWrite(this, docData->mFile, localFile);
  rv = docData->mDocument->WriteContent(outputStream, mFlatURIMap,
                                        NS_ConvertUTF16toUTF8(mContentType),
                                        mEncodingFlags, mWrapColumn, finish);
  if (NS_FAILED(rv)) {
    SendErrorStatusChange(false, rv, nullptr, docData->mFile);
    EndDownload(rv);
  }
}

NS_IMETHODIMP
nsWebBrowserPersist::OnWrite::OnFinish(nsIWebBrowserPersistDocument* aDoc,
                                       nsIOutputStream* aStream,
                                       const nsACString& aContentType,
                                       nsresult aStatus) {
  nsresult rv = aStatus;

  if (NS_FAILED(rv)) {
    mParent->SendErrorStatusChange(false, rv, nullptr, mFile);
    mParent->EndDownload(rv);
    return NS_OK;
  }
  if (!mLocalFile) {
    nsCOMPtr<nsIStorageStream> storStream(do_QueryInterface(aStream));
    if (storStream) {
      aStream->Close();
      rv = mParent->StartUpload(storStream, mFile, aContentType);
      if (NS_FAILED(rv)) {
        mParent->SendErrorStatusChange(false, rv, nullptr, mFile);
        mParent->EndDownload(rv);
      }
      // Either we failed and we're done, or we're uploading and
      // the OnStopRequest callback is responsible for the next
      // SerializeNextFile().
      return NS_OK;
    }
  }
  NS_DispatchToCurrentThread(
      NewRunnableMethod("nsWebBrowserPersist::SerializeNextFile", mParent,
                        &nsWebBrowserPersist::SerializeNextFile));
  return NS_OK;
}

//*****************************************************************************
// nsWebBrowserPersist::nsIRequestObserver
//*****************************************************************************

NS_IMETHODIMP nsWebBrowserPersist::OnStartRequest(nsIRequest* request) {
  if (mProgressListener) {
    uint32_t stateFlags = nsIWebProgressListener::STATE_START |
                          nsIWebProgressListener::STATE_IS_REQUEST;
    if (!mSavingDocument) {
      stateFlags |= nsIWebProgressListener::STATE_IS_NETWORK;
    }
    mProgressListener->OnStateChange(nullptr, request, stateFlags, NS_OK);
  }

  nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
  NS_ENSURE_TRUE(channel, NS_ERROR_FAILURE);

  nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(request);
  OutputData* data = mOutputMap.Get(keyPtr);

  // NOTE: This code uses the channel as a hash key so it will not
  //       recognize redirected channels because the key is not the same.
  //       When that happens we remove and add the data entry to use the
  //       new channel as the hash key.
  if (!data) {
    UploadData* upData = mUploadList.Get(keyPtr);
    if (!upData) {
      // Redirect? Try and fixup the output table
      nsresult rv = FixRedirectedChannelEntry(channel);
      NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

      // Should be able to find the data after fixup unless redirects
      // are disabled.
      data = mOutputMap.Get(keyPtr);
      if (!data) {
        return NS_ERROR_FAILURE;
      }
    }
  }

  if (data && data->mFile) {
    nsCOMPtr<nsIThreadRetargetableRequest> r = do_QueryInterface(request);
    // Determine if we're uploading. Only use OMT onDataAvailable if not.
    nsCOMPtr<nsIFile> localFile;
    GetLocalFileFromURI(data->mFile, getter_AddRefs(localFile));
    if (r && localFile) {
      if (!mBackgroundQueue) {
        NS_CreateBackgroundTaskQueue("WebBrowserPersist",
                                     getter_AddRefs(mBackgroundQueue));
      }
      if (mBackgroundQueue) {
        r->RetargetDeliveryTo(mBackgroundQueue);
      }
    }

    // If PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION is set in mPersistFlags,
    // try to determine whether this channel needs to apply Content-Encoding
    // conversions.
    NS_ASSERTION(
        !((mPersistFlags & PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION) &&
          (mPersistFlags & PERSIST_FLAGS_NO_CONVERSION)),
        "Conflict in persist flags: both AUTODETECT and NO_CONVERSION set");
    if (mPersistFlags & PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION)
      SetApplyConversionIfNeeded(channel);

    if (data->mCalcFileExt &&
        !(mPersistFlags & PERSIST_FLAGS_DONT_CHANGE_FILENAMES)) {
      nsCOMPtr<nsIURI> uriWithExt;
      // this is the first point at which the server can tell us the mimetype
      nsresult rv = CalculateAndAppendFileExt(
          data->mFile, channel, data->mOriginalLocation, uriWithExt);
      if (NS_SUCCEEDED(rv)) {
        data->mFile = uriWithExt;
      }

      // now make filename conformant and unique
      nsCOMPtr<nsIURI> uniqueFilenameURI;
      rv = CalculateUniqueFilename(data->mFile, uniqueFilenameURI);
      if (NS_SUCCEEDED(rv)) {
        data->mFile = uniqueFilenameURI;
      }

      // The URIData entry is pointing to the old unfixed URI, so we need
      // to update it.
      nsCOMPtr<nsIURI> chanURI;
      rv = channel->GetOriginalURI(getter_AddRefs(chanURI));
      if (NS_SUCCEEDED(rv)) {
        nsAutoCString spec;
        chanURI->GetSpec(spec);
        URIData* uridata;
        if (mURIMap.Get(spec, &uridata)) {
          uridata->mFile = data->mFile;
        }
      }
    }

    // compare uris and bail before we add to output map if they are equal
    bool isEqual = false;
    if (NS_SUCCEEDED(data->mFile->Equals(data->mOriginalLocation, &isEqual)) &&
        isEqual) {
      {
        MutexAutoLock lock(mOutputMapMutex);
        // remove from output map
        mOutputMap.Remove(keyPtr);
      }

      // cancel; we don't need to know any more
      // stop request will get called
      request->Cancel(NS_BINDING_ABORTED);
    }
  }

  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::OnStopRequest(nsIRequest* request,
                                                 nsresult status) {
  nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(request);
  OutputData* data = mOutputMap.Get(keyPtr);
  if (data) {
    if (NS_SUCCEEDED(mPersistResult) && NS_FAILED(status)) {
      SendErrorStatusChange(true, status, request, data->mFile);
    }

    // If there is a stream ref and we weren't canceled,
    // close it away from the main thread.
    // We don't do this when there's an error/cancelation,
    // because our consumer may try to delete the file, which will error
    // if we're still holding on to it, so we have to close it pronto.
    {
      MutexAutoLock lock(data->mStreamMutex);
      if (data->mStream && NS_SUCCEEDED(status) && !mCancel) {
        if (!mBackgroundQueue) {
          nsresult rv = NS_CreateBackgroundTaskQueue(
              "WebBrowserPersist", getter_AddRefs(mBackgroundQueue));
          if (NS_FAILED(rv)) {
            return rv;
          }
        }
        // Now steal the stream ref and close it away from the main thread,
        // keeping the promise around so we don't finish before all files
        // are flushed and closed.
        mFileClosePromises.AppendElement(InvokeAsync(
            mBackgroundQueue, __func__, [stream = std::move(data->mStream)]() {
              nsresult rv = stream->Close();
              // We don't care if closing failed; we don't care in the
              // destructor either...
              return ClosePromise::CreateAndResolve(rv, __func__);
            }));
      }
    }
    MutexAutoLock lock(mOutputMapMutex);
    mOutputMap.Remove(keyPtr);
  } else {
    // if we didn't find the data in mOutputMap, try mUploadList
    UploadData* upData = mUploadList.Get(keyPtr);
    if (upData) {
      mUploadList.Remove(keyPtr);
    }
  }

  // Do more work.
  SerializeNextFile();

  if (mProgressListener) {
    uint32_t stateFlags = nsIWebProgressListener::STATE_STOP |
                          nsIWebProgressListener::STATE_IS_REQUEST;
    if (!mSavingDocument) {
      stateFlags |= nsIWebProgressListener::STATE_IS_NETWORK;
    }
    mProgressListener->OnStateChange(nullptr, request, stateFlags, status);
  }

  return NS_OK;
}

//*****************************************************************************
// nsWebBrowserPersist::nsIStreamListener
//*****************************************************************************

// Note: this is supposed to (but not guaranteed to) fire on a background
// thread when used to save to local disk (channels not using local files will
// use the main thread).
// (Read) Access to mOutputMap is guarded via mOutputMapMutex.
// Access to individual OutputData::mStream is guarded via its mStreamMutex.
// mCancel is atomic, as is mPersistFlags (accessed via MakeOutputStream).
// If you end up touching this method and needing other member access, bear
// this in mind.
NS_IMETHODIMP
nsWebBrowserPersist::OnDataAvailable(nsIRequest* request,
                                     nsIInputStream* aIStream, uint64_t aOffset,
                                     uint32_t aLength) {
  // MOZ_ASSERT(!NS_IsMainThread()); // no guarantees, but it's likely.

  bool cancel = mCancel;
  if (!cancel) {
    nsresult rv = NS_OK;
    uint32_t bytesRemaining = aLength;

    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
    NS_ENSURE_TRUE(channel, NS_ERROR_FAILURE);

    MutexAutoLock lock(mOutputMapMutex);
    nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(request);
    OutputData* data = mOutputMap.Get(keyPtr);
    if (!data) {
      // might be uploadData; consume necko's buffer and bail...
      uint32_t n;
      return aIStream->ReadSegments(NS_DiscardSegment, nullptr, aLength, &n);
    }

    bool readError = true;

    MutexAutoLock streamLock(data->mStreamMutex);
    // Make the output stream
    if (!data->mStream) {
      rv = MakeOutputStream(data->mFile, getter_AddRefs(data->mStream));
      if (NS_FAILED(rv)) {
        readError = false;
        cancel = true;
      }
    }

    // Read data from the input and write to the output
    char buffer[8192];
    uint32_t bytesRead;
    while (!cancel && bytesRemaining) {
      readError = true;
      rv = aIStream->Read(buffer,
                          std::min(uint32_t(sizeof(buffer)), bytesRemaining),
                          &bytesRead);
      if (NS_SUCCEEDED(rv)) {
        readError = false;
        // Write out the data until something goes wrong, or, it is
        // all written.  We loop because for some errors (e.g., disk
        // full), we get NS_OK with some bytes written, then an error.
        // So, we want to write again in that case to get the actual
        // error code.
        const char* bufPtr = buffer;  // Where to write from.
        while (NS_SUCCEEDED(rv) && bytesRead) {
          uint32_t bytesWritten = 0;
          rv = data->mStream->Write(bufPtr, bytesRead, &bytesWritten);
          if (NS_SUCCEEDED(rv)) {
            bytesRead -= bytesWritten;
            bufPtr += bytesWritten;
            bytesRemaining -= bytesWritten;
            // Force an error if (for some reason) we get NS_OK but
            // no bytes written.
            if (!bytesWritten) {
              rv = NS_ERROR_FAILURE;
              cancel = true;
            }
          } else {
            // Disaster - can't write out the bytes - disk full / permission?
            cancel = true;
          }
        }
      } else {
        // Disaster - can't read the bytes - broken link / file error?
        cancel = true;
      }
    }

    int64_t channelContentLength = -1;
    if (!cancel &&
        NS_SUCCEEDED(channel->GetContentLength(&channelContentLength))) {
      // if we get -1 at this point, we didn't get content-length header
      // assume that we got all of the data and push what we have;
      // that's the best we can do now
      if ((-1 == channelContentLength) ||
          ((channelContentLength - (aOffset + aLength)) == 0)) {
        NS_WARNING_ASSERTION(
            channelContentLength != -1,
            "nsWebBrowserPersist::OnDataAvailable() no content length "
            "header, pushing what we have");
        // we're done with this pass; see if we need to do upload
        nsAutoCString contentType;
        channel->GetContentType(contentType);
        // if we don't have the right type of output stream then it's a local
        // file
        nsCOMPtr<nsIStorageStream> storStream(do_QueryInterface(data->mStream));
        if (storStream) {
          data->mStream->Close();
          data->mStream =
              nullptr;  // null out stream so we don't close it later
          MOZ_ASSERT(NS_IsMainThread(),
                     "Uploads should be on the main thread.");
          rv = StartUpload(storStream, data->mFile, contentType);
          if (NS_FAILED(rv)) {
            readError = false;
            cancel = true;
          }
        }
      }
    }

    // Notify listener if an error occurred.
    if (cancel) {
      RefPtr<nsIRequest> req = readError ? request : nullptr;
      nsCOMPtr<nsIURI> file = data->mFile;
      RefPtr<Runnable> errorOnMainThread = NS_NewRunnableFunction(
          "nsWebBrowserPersist::SendErrorStatusChange",
          [self = RefPtr{this}, req, file, readError, rv]() {
            self->SendErrorStatusChange(readError, rv, req, file);
          });
      NS_DispatchToMainThread(errorOnMainThread);

      // And end the download on the main thread.
      nsCOMPtr<nsIRunnable> endOnMainThread = NewRunnableMethod<nsresult>(
          "nsWebBrowserPersist::EndDownload", this,
          &nsWebBrowserPersist::EndDownload, NS_BINDING_ABORTED);
      NS_DispatchToMainThread(endOnMainThread);
    }
  }

  return cancel ? NS_BINDING_ABORTED : NS_OK;
}

//*****************************************************************************
// nsWebBrowserPersist::nsIThreadRetargetableStreamListener
//*****************************************************************************

NS_IMETHODIMP nsWebBrowserPersist::CheckListenerChain() { return NS_OK; }

//*****************************************************************************
// nsWebBrowserPersist::nsIProgressEventSink
//*****************************************************************************

NS_IMETHODIMP nsWebBrowserPersist::OnProgress(nsIRequest* request,
                                              int64_t aProgress,
                                              int64_t aProgressMax) {
  if (!mProgressListener) {
    return NS_OK;
  }

  // Store the progress of this request
  nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(request);
  OutputData* data = mOutputMap.Get(keyPtr);
  if (data) {
    data->mSelfProgress = aProgress;
    data->mSelfProgressMax = aProgressMax;
  } else {
    UploadData* upData = mUploadList.Get(keyPtr);
    if (upData) {
      upData->mSelfProgress = aProgress;
      upData->mSelfProgressMax = aProgressMax;
    }
  }

  // Notify listener of total progress
  CalcTotalProgress();
  if (mProgressListener2) {
    mProgressListener2->OnProgressChange64(nullptr, request, aProgress,
                                           aProgressMax, mTotalCurrentProgress,
                                           mTotalMaxProgress);
  } else {
    // have to truncate 64-bit to 32bit
    mProgressListener->OnProgressChange(
        nullptr, request, uint64_t(aProgress), uint64_t(aProgressMax),
        mTotalCurrentProgress, mTotalMaxProgress);
  }

  // If our progress listener implements nsIProgressEventSink,
  // forward the notification
  if (mEventSink) {
    mEventSink->OnProgress(request, aProgress, aProgressMax);
  }

  return NS_OK;
}

NS_IMETHODIMP nsWebBrowserPersist::OnStatus(nsIRequest* request,
                                            nsresult status,
                                            const char16_t* statusArg) {
  if (mProgressListener) {
    // We need to filter out non-error error codes.
    // Is the only NS_SUCCEEDED value NS_OK?
    switch (status) {
      case NS_NET_STATUS_RESOLVING_HOST:
      case NS_NET_STATUS_RESOLVED_HOST:
      case NS_NET_STATUS_CONNECTING_TO:
      case NS_NET_STATUS_CONNECTED_TO:
      case NS_NET_STATUS_TLS_HANDSHAKE_STARTING:
      case NS_NET_STATUS_TLS_HANDSHAKE_ENDED:
      case NS_NET_STATUS_SENDING_TO:
      case NS_NET_STATUS_RECEIVING_FROM:
      case NS_NET_STATUS_WAITING_FOR:
      case NS_NET_STATUS_READING:
      case NS_NET_STATUS_WRITING:
        break;

      default:
        // Pass other notifications (for legitimate errors) along.
        mProgressListener->OnStatusChange(nullptr, request, status, statusArg);
        break;
    }
  }

  // If our progress listener implements nsIProgressEventSink,
  // forward the notification
  if (mEventSink) {
    mEventSink->OnStatus(request, status, statusArg);
  }

  return NS_OK;
}

//*****************************************************************************
// nsWebBrowserPersist private methods
//*****************************************************************************

// Convert error info into proper message text and send OnStatusChange
// notification to the web progress listener.
nsresult nsWebBrowserPersist::SendErrorStatusChange(bool aIsReadError,
                                                    nsresult aResult,
                                                    nsIRequest* aRequest,
                                                    nsIURI* aURI) {
  NS_ENSURE_ARG_POINTER(aURI);

  if (!mProgressListener) {
    // Do nothing
    return NS_OK;
  }

  // Get the file path or spec from the supplied URI
  nsCOMPtr<nsIFile> file;
  GetLocalFileFromURI(aURI, getter_AddRefs(file));
  AutoTArray<nsString, 1> strings;
  nsresult rv;
  if (file) {
    file->GetPath(*strings.AppendElement());
  } else {
    nsAutoCString fileurl;
    rv = aURI->GetSpec(fileurl);
    NS_ENSURE_SUCCESS(rv, rv);
    CopyUTF8toUTF16(fileurl, *strings.AppendElement());
  }

  const char* msgId;
  switch (aResult) {
    case NS_ERROR_FILE_NAME_TOO_LONG:
      // File name too long.
      msgId = "fileNameTooLongError";
      break;
    case NS_ERROR_FILE_ALREADY_EXISTS:
      // File exists with same name as directory.
      msgId = "fileAlreadyExistsError";
      break;
    case NS_ERROR_FILE_NO_DEVICE_SPACE:
      // Out of space on target volume.
      msgId = "diskFull";
      break;

    case NS_ERROR_FILE_READ_ONLY:
      // Attempt to write to read/only file.
      msgId = "readOnly";
      break;

    case NS_ERROR_FILE_ACCESS_DENIED:
      // Attempt to write without sufficient permissions.
      msgId = "accessError";
      break;

    default:
      // Generic read/write error message.
      if (aIsReadError)
        msgId = "readError";
      else
        msgId = "writeError";
      break;
  }
  // Get properties file bundle and extract status string.
  nsCOMPtr<nsIStringBundleService> s =
      do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
  NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && s, NS_ERROR_FAILURE);

  nsCOMPtr<nsIStringBundle> bundle;
  rv = s->CreateBundle(kWebBrowserPersistStringBundle, getter_AddRefs(bundle));
  NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && bundle, NS_ERROR_FAILURE);

  nsAutoString msgText;
  rv = bundle->FormatStringFromName(msgId, strings, msgText);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  mProgressListener->OnStatusChange(nullptr, aRequest, aResult, msgText.get());

  return NS_OK;
}

nsresult nsWebBrowserPersist::GetValidURIFromObject(nsISupports* aObject,
                                                    nsIURI** aURI) const {
  NS_ENSURE_ARG_POINTER(aObject);
  NS_ENSURE_ARG_POINTER(aURI);

  nsCOMPtr<nsIFile> objAsFile = do_QueryInterface(aObject);
  if (objAsFile) {
    return NS_NewFileURI(aURI, objAsFile);
  }
  nsCOMPtr<nsIURI> objAsURI = do_QueryInterface(aObject);
  if (objAsURI) {
    *aURI = objAsURI;
    NS_ADDREF(*aURI);
    return NS_OK;
  }

  return NS_ERROR_FAILURE;
}

/* static */
nsresult nsWebBrowserPersist::GetLocalFileFromURI(nsIURI* aURI,
                                                  nsIFile** aLocalFile) {
  nsresult rv;

  nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(aURI, &rv);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIFile> file;
  rv = fileURL->GetFile(getter_AddRefs(file));
  if (NS_FAILED(rv)) {
    return rv;
  }

  file.forget(aLocalFile);
  return NS_OK;
}

/* static */
nsresult nsWebBrowserPersist::AppendPathToURI(nsIURI* aURI,
                                              const nsAString& aPath,
                                              nsCOMPtr<nsIURI>& aOutURI) {
  NS_ENSURE_ARG_POINTER(aURI);

  nsAutoCString newPath;
  nsresult rv = aURI->GetPathQueryRef(newPath);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // Append a forward slash if necessary
  int32_t len = newPath.Length();
  if (len > 0 && newPath.CharAt(len - 1) != '/') {
    newPath.Append('/');
  }

  // Store the path back on the URI
  AppendUTF16toUTF8(aPath, newPath);

  return NS_MutateURI(aURI).SetPathQueryRef(newPath).Finalize(aOutURI);
}

nsresult nsWebBrowserPersist::SaveURIInternal(
    nsIURI* aURI, nsIPrincipal* aTriggeringPrincipal,
    nsContentPolicyType aContentPolicyType, uint32_t aCacheKey,
    nsIReferrerInfo* aReferrerInfo, nsICookieJarSettings* aCookieJarSettings,
    nsIInputStream* aPostData, const char* aExtraHeaders, nsIURI* aFile,
    bool aCalcFileExt, bool aIsPrivate) {
  NS_ENSURE_ARG_POINTER(aURI);
  NS_ENSURE_ARG_POINTER(aFile);
  NS_ENSURE_ARG_POINTER(aTriggeringPrincipal);

  nsresult rv = NS_OK;

  mURI = aURI;

  nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
  if (mPersistFlags & PERSIST_FLAGS_BYPASS_CACHE) {
    loadFlags |= nsIRequest::LOAD_BYPASS_CACHE;
  } else if (mPersistFlags & PERSIST_FLAGS_FROM_CACHE) {
    loadFlags |= nsIRequest::LOAD_FROM_CACHE;
  }

  // If there is no cookieJarSetting given, we need to create a new
  // cookieJarSettings for this download in order to send cookies based on the
  // current state of the prefs/permissions.
  nsCOMPtr<nsICookieJarSettings> cookieJarSettings = aCookieJarSettings;
  if (!cookieJarSettings) {
    // Although the variable is called 'triggering principal', it is used as the
    // loading principal in the download channel, so we treat it as a loading
    // principal also.
    bool shouldResistFingerprinting =
        nsContentUtils::ShouldResistFingerprinting_dangerous(
            aTriggeringPrincipal,
            "We are creating a new CookieJar Settings, so none exists "
            "currently. Although the variable is called 'triggering principal',"
            "it is used as the loading principal in the download channel, so we"
            "treat it as a loading principal also.");
    cookieJarSettings =
        aIsPrivate
            ? net::CookieJarSettings::Create(net::CookieJarSettings::ePrivate,
                                             shouldResistFingerprinting)
            : net::CookieJarSettings::Create(net::CookieJarSettings::eRegular,
                                             shouldResistFingerprinting);
  }

  // Open a channel to the URI
  nsCOMPtr<nsIChannel> inputChannel;
  rv = NS_NewChannel(getter_AddRefs(inputChannel), aURI, aTriggeringPrincipal,
                     nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
                     aContentPolicyType, cookieJarSettings,
                     nullptr,  // aPerformanceStorage
                     nullptr,  // aLoadGroup
                     static_cast<nsIInterfaceRequestor*>(this), loadFlags);

  nsCOMPtr<nsIPrivateBrowsingChannel> pbChannel =
      do_QueryInterface(inputChannel);
  if (pbChannel) {
    pbChannel->SetPrivate(aIsPrivate);
  }

  if (NS_FAILED(rv) || inputChannel == nullptr) {
    EndDownload(NS_ERROR_FAILURE);
    return NS_ERROR_FAILURE;
  }

  // Disable content conversion
  if (mPersistFlags & PERSIST_FLAGS_NO_CONVERSION) {
    nsCOMPtr<nsIEncodedChannel> encodedChannel(do_QueryInterface(inputChannel));
    if (encodedChannel) {
      encodedChannel->SetApplyConversion(false);
    }
  }

  nsCOMPtr<nsILoadInfo> loadInfo = inputChannel->LoadInfo();
  loadInfo->SetIsUserTriggeredSave(true);

  // Set the referrer, post data and headers if any
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(inputChannel));
  if (httpChannel) {
    if (aReferrerInfo) {
      DebugOnly<nsresult> success = httpChannel->SetReferrerInfo(aReferrerInfo);
      MOZ_ASSERT(NS_SUCCEEDED(success));
    }

    // Post data
    if (aPostData) {
      nsCOMPtr<nsISeekableStream> stream(do_QueryInterface(aPostData));
      if (stream) {
        // Rewind the postdata stream
        stream->Seek(nsISeekableStream::NS_SEEK_SET, 0);
        nsCOMPtr<nsIUploadChannel> uploadChannel(
            do_QueryInterface(httpChannel));
        NS_ASSERTION(uploadChannel, "http must support nsIUploadChannel");
        // Attach the postdata to the http channel
        uploadChannel->SetUploadStream(aPostData, ""_ns, -1);
      }
    }

    // Cache key
    nsCOMPtr<nsICacheInfoChannel> cacheChannel(do_QueryInterface(httpChannel));
    if (cacheChannel && aCacheKey != 0) {
      cacheChannel->SetCacheKey(aCacheKey);
    }

    // Headers
    if (aExtraHeaders) {
      nsAutoCString oneHeader;
      nsAutoCString headerName;
      nsAutoCString headerValue;
      int32_t crlf = 0;
      int32_t colon = 0;
      const char* kWhitespace = "\b\t\r\n ";
      nsAutoCString extraHeaders(aExtraHeaders);
      while (true) {
        crlf = extraHeaders.Find("\r\n");
        if (crlf == -1) break;
        extraHeaders.Mid(oneHeader, 0, crlf);
        extraHeaders.Cut(0, crlf + 2);
        colon = oneHeader.Find(":");
        if (colon == -1) break;  // Should have a colon
        oneHeader.Left(headerName, colon);
        colon++;
        oneHeader.Mid(headerValue, colon, oneHeader.Length() - colon);
        headerName.Trim(kWhitespace);
        headerValue.Trim(kWhitespace);
        // Add the header (merging if required)
        rv = httpChannel->SetRequestHeader(headerName, headerValue, true);
        if (NS_FAILED(rv)) {
          EndDownload(NS_ERROR_FAILURE);
          return NS_ERROR_FAILURE;
        }
      }
    }
  }
  return SaveChannelInternal(inputChannel, aFile, aCalcFileExt);
}

nsresult nsWebBrowserPersist::SaveChannelInternal(nsIChannel* aChannel,
                                                  nsIURI* aFile,
                                                  bool aCalcFileExt) {
  NS_ENSURE_ARG_POINTER(aChannel);
  NS_ENSURE_ARG_POINTER(aFile);

  // The default behaviour of SaveChannelInternal is to download the source
  // into a storage stream and upload that to the target. MakeOutputStream
  // special-cases a file target and creates a file output stream directly.
  // We want to special-case a file source and create a file input stream,
  // but we don't need to do this in the case of a file target.
  nsCOMPtr<nsIFileChannel> fc(do_QueryInterface(aChannel));
  nsCOMPtr<nsIFileURL> fu(do_QueryInterface(aFile));

  if (fc && !fu) {
    nsCOMPtr<nsIInputStream> fileInputStream, bufferedInputStream;
    nsresult rv = aChannel->Open(getter_AddRefs(fileInputStream));
    NS_ENSURE_SUCCESS(rv, rv);
    rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedInputStream),
                                   fileInputStream.forget(),
                                   BUFFERED_OUTPUT_SIZE);
    NS_ENSURE_SUCCESS(rv, rv);
    nsAutoCString contentType;
    aChannel->GetContentType(contentType);
    return StartUpload(bufferedInputStream, aFile, contentType);
  }

  // Mark save channel as throttleable.
  nsCOMPtr<nsIClassOfService> cos(do_QueryInterface(aChannel));
  if (cos) {
    cos->AddClassFlags(nsIClassOfService::Throttleable);
  }

  // Read from the input channel
  nsresult rv = aChannel->AsyncOpen(this);
  if (rv == NS_ERROR_NO_CONTENT) {
    // Assume this is a protocol such as mailto: which does not feed out
    // data and just ignore it.
    return NS_SUCCESS_DONT_FIXUP;
  }

  if (NS_FAILED(rv)) {
    // Opening failed, but do we care?
    if (mPersistFlags & PERSIST_FLAGS_FAIL_ON_BROKEN_LINKS) {
      SendErrorStatusChange(true, rv, aChannel, aFile);
      EndDownload(NS_ERROR_FAILURE);
      return NS_ERROR_FAILURE;
    }
    return NS_SUCCESS_DONT_FIXUP;
  }

  MutexAutoLock lock(mOutputMapMutex);
  // Add the output transport to the output map with the channel as the key
  nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(aChannel);
  mOutputMap.InsertOrUpdate(keyPtr,
                            MakeUnique<OutputData>(aFile, mURI, aCalcFileExt));

  return NS_OK;
}

nsresult nsWebBrowserPersist::GetExtensionForContentType(
    const char16_t* aContentType, char16_t** aExt) {
  NS_ENSURE_ARG_POINTER(aContentType);
  NS_ENSURE_ARG_POINTER(aExt);

  *aExt = nullptr;

  nsresult rv;
  if (!mMIMEService) {
    mMIMEService = do_GetService(NS_MIMESERVICE_CONTRACTID, &rv);
    NS_ENSURE_TRUE(mMIMEService, NS_ERROR_FAILURE);
  }

  nsAutoCString contentType;
  LossyCopyUTF16toASCII(MakeStringSpan(aContentType), contentType);
  nsAutoCString ext;
  rv = mMIMEService->GetPrimaryExtension(contentType, ""_ns, ext);
  if (NS_SUCCEEDED(rv)) {
    *aExt = UTF8ToNewUnicode(ext);
    NS_ENSURE_TRUE(*aExt, NS_ERROR_OUT_OF_MEMORY);
    return NS_OK;
  }

  return NS_ERROR_FAILURE;
}

nsresult nsWebBrowserPersist::SaveDocumentDeferred(
    mozilla::UniquePtr<WalkData>&& aData) {
  nsresult rv =
      SaveDocumentInternal(aData->mDocument, aData->mFile, aData->mDataPath);
  if (NS_FAILED(rv)) {
    SendErrorStatusChange(true, rv, nullptr, mURI);
    EndDownload(rv);
  }
  return rv;
}

nsresult nsWebBrowserPersist::SaveDocumentInternal(
    nsIWebBrowserPersistDocument* aDocument, nsIURI* aFile, nsIURI* aDataPath) {
  mURI = nullptr;
  NS_ENSURE_ARG_POINTER(aDocument);
  NS_ENSURE_ARG_POINTER(aFile);

  nsresult rv = aDocument->SetPersistFlags(mPersistFlags);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aDocument->GetIsPrivate(&mIsPrivate);
  NS_ENSURE_SUCCESS(rv, rv);

  // See if we can get the local file representation of this URI
  nsCOMPtr<nsIFile> localFile;
  rv = GetLocalFileFromURI(aFile, getter_AddRefs(localFile));

  nsCOMPtr<nsIFile> localDataPath;
  if (NS_SUCCEEDED(rv) && aDataPath) {
    // See if we can get the local file representation of this URI
    rv = GetLocalFileFromURI(aDataPath, getter_AddRefs(localDataPath));
    NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
  }

  // Persist the main document
  rv = aDocument->GetCharacterSet(mCurrentCharset);
  NS_ENSURE_SUCCESS(rv, rv);
  nsAutoCString uriSpec;
  rv = aDocument->GetDocumentURI(uriSpec);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = NS_NewURI(getter_AddRefs(mURI), uriSpec, mCurrentCharset.get());
  NS_ENSURE_SUCCESS(rv, rv);
  rv = aDocument->GetBaseURI(uriSpec);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = NS_NewURI(getter_AddRefs(mCurrentBaseURI), uriSpec,
                 mCurrentCharset.get());
  NS_ENSURE_SUCCESS(rv, rv);

  // Does the caller want to fixup the referenced URIs and save those too?
  if (aDataPath) {
    // Basic steps are these.
    //
    // 1. Iterate through the document (and subdocuments) building a list
    //    of unique URIs.
    // 2. For each URI create an OutputData entry and open a channel to save
    //    it. As each URI is saved, discover the mime type and fix up the
    //    local filename with the correct extension.
    // 3. Store the document in a list and wait for URI persistence to finish
    // 4. After URI persistence completes save the list of documents,
    //    fixing it up as it goes out to file.

    mCurrentDataPathIsRelative = false;
    mCurrentDataPath = aDataPath;
    mCurrentRelativePathToData = "";
    mCurrentThingsToPersist = 0;
    mTargetBaseURI = aFile;

    // Determine if the specified data path is relative to the
    // specified file, (e.g. c:\docs\htmldata is relative to
    // c:\docs\myfile.htm, but not to d:\foo\data.

    // Starting with the data dir work back through its parents
    // checking if one of them matches the base directory.

    if (localDataPath && localFile) {
      nsCOMPtr<nsIFile> baseDir;
      localFile->GetParent(getter_AddRefs(baseDir));

      nsAutoCString relativePathToData;
      nsCOMPtr<nsIFile> dataDirParent;
      dataDirParent = localDataPath;
      while (dataDirParent) {
        bool sameDir = false;
        dataDirParent->Equals(baseDir, &sameDir);
        if (sameDir) {
          mCurrentRelativePathToData = relativePathToData;
          mCurrentDataPathIsRelative = true;
          break;
        }

        nsAutoString dirName;
        dataDirParent->GetLeafName(dirName);

        nsAutoCString newRelativePathToData;
        newRelativePathToData =
            NS_ConvertUTF16toUTF8(dirName) + "/"_ns + relativePathToData;
        relativePathToData = newRelativePathToData;

        nsCOMPtr<nsIFile> newDataDirParent;
        rv = dataDirParent->GetParent(getter_AddRefs(newDataDirParent));
        dataDirParent = newDataDirParent;
      }
    } else {
      // generate a relative path if possible
      nsCOMPtr<nsIURL> pathToBaseURL(do_QueryInterface(aFile));
      if (pathToBaseURL) {
        nsAutoCString relativePath;  // nsACString
        if (NS_SUCCEEDED(
                pathToBaseURL->GetRelativeSpec(aDataPath, relativePath))) {
          mCurrentDataPathIsRelative = true;
          mCurrentRelativePathToData = relativePath;
        }
      }
    }

    // Store the document in a list so when URI persistence is done and the
    // filenames of saved URIs are known, the documents can be fixed up and
    // saved

    auto* docData = new DocData;
    docData->mBaseURI = mCurrentBaseURI;
    docData->mCharset = mCurrentCharset;
    docData->mDocument = aDocument;
    docData->mFile = aFile;
    mDocList.AppendElement(docData);

    // Walk the DOM gathering a list of externally referenced URIs in the uri
    // map
    nsCOMPtr<nsIWebBrowserPersistResourceVisitor> visit =
        new OnWalk(this, aFile, localDataPath);
    return aDocument->ReadResources(visit);
  } else {
    auto* docData = new DocData;
    docData->mBaseURI = mCurrentBaseURI;
    docData->mCharset = mCurrentCharset;
    docData->mDocument = aDocument;
    docData->mFile = aFile;
    mDocList.AppendElement(docData);

    // Not walking DOMs, so go directly to serialization.
    SerializeNextFile();
    return NS_OK;
  }
}

NS_IMETHODIMP
nsWebBrowserPersist::OnWalk::VisitResource(
    nsIWebBrowserPersistDocument* aDoc, const nsACString& aURI,
    nsContentPolicyType aContentPolicyType) {
  return mParent->StoreURI(aURI, aDoc, aContentPolicyType);
}

NS_IMETHODIMP
nsWebBrowserPersist::OnWalk::VisitDocument(
    nsIWebBrowserPersistDocument* aDoc, nsIWebBrowserPersistDocument* aSubDoc) {
  URIData* data = nullptr;
  nsAutoCString uriSpec;
  nsresult rv = aSubDoc->GetDocumentURI(uriSpec);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = mParent->StoreURI(uriSpec, aDoc, nsIContentPolicy::TYPE_SUBDOCUMENT,
                         false, &data);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!data) {
    // If the URI scheme isn't persistable, then don't persist.
    return NS_OK;
  }
  data->mIsSubFrame = true;
  return mParent->SaveSubframeContent(aSubDoc, aDoc, uriSpec, data);
}

NS_IMETHODIMP
nsWebBrowserPersist::OnWalk::VisitBrowsingContext(
    nsIWebBrowserPersistDocument* aDoc, BrowsingContext* aContext) {
  RefPtr<dom::CanonicalBrowsingContext> context = aContext->Canonical();

  if (NS_WARN_IF(!context->GetCurrentWindowGlobal())) {
    EndVisit(nullptr, NS_ERROR_FAILURE);
    return NS_ERROR_FAILURE;
  }

  UniquePtr<WebBrowserPersistDocumentParent> actor(
      new WebBrowserPersistDocumentParent());

  nsCOMPtr<nsIWebBrowserPersistDocumentReceiver> receiver =
      new OnRemoteWalk(this, aDoc);
  actor->SetOnReady(receiver);

  RefPtr<dom::BrowserParent> browserParent =
      context->GetCurrentWindowGlobal()->GetBrowserParent();

  bool ok =
      context->GetContentParent()->SendPWebBrowserPersistDocumentConstructor(
          actor.release(), browserParent, context);

  if (NS_WARN_IF(!ok)) {
    // (The actor will be destroyed on constructor failure.)
    EndVisit(nullptr, NS_ERROR_FAILURE);
    return NS_ERROR_FAILURE;
  }

  ++mPendingDocuments;

  return NS_OK;
}

NS_IMETHODIMP
nsWebBrowserPersist::OnWalk::EndVisit(nsIWebBrowserPersistDocument* aDoc,
                                      nsresult aStatus) {
  if (NS_FAILED(mStatus)) {
    return mStatus;
  }

  if (NS_FAILED(aStatus)) {
    mStatus = aStatus;
    mParent->SendErrorStatusChange(true, aStatus, nullptr, mFile);
    mParent->EndDownload(aStatus);
    return aStatus;
  }

  if (--mPendingDocuments) {
    // We're not done yet, wait for more.
    return NS_OK;
  }

  mParent->FinishSaveDocumentInternal(mFile, mDataPath);
  return NS_OK;
}

NS_IMETHODIMP
nsWebBrowserPersist::OnRemoteWalk::OnDocumentReady(
    nsIWebBrowserPersistDocument* aSubDocument) {
  mVisitor->VisitDocument(mDocument, aSubDocument);
  mVisitor->EndVisit(mDocument, NS_OK);
  return NS_OK;
}

NS_IMETHODIMP
nsWebBrowserPersist::OnRemoteWalk::OnError(nsresult aFailure) {
  mVisitor->EndVisit(nullptr, aFailure);
  return NS_OK;
}

void nsWebBrowserPersist::FinishSaveDocumentInternal(nsIURI* aFile,
                                                     nsIFile* aDataPath) {
  // If there are things to persist, create a directory to hold them
  if (mCurrentThingsToPersist > 0) {
    if (aDataPath) {
      bool exists = false;
      bool haveDir = false;

      aDataPath->Exists(&exists);
      if (exists) {
        aDataPath->IsDirectory(&haveDir);
      }
      if (!haveDir) {
        nsresult rv = aDataPath->Create(nsIFile::DIRECTORY_TYPE, 0755);
        if (NS_SUCCEEDED(rv)) {
          haveDir = true;
        } else {
          SendErrorStatusChange(false, rv, nullptr, aFile);
        }
      }
      if (!haveDir) {
        EndDownload(NS_ERROR_FAILURE);
        return;
      }
      if (mPersistFlags & PERSIST_FLAGS_CLEANUP_ON_FAILURE) {
        // Add to list of things to delete later if all goes wrong
        auto* cleanupData = new CleanupData;
        cleanupData->mFile = aDataPath;
        cleanupData->mIsDirectory = true;
        mCleanupList.AppendElement(cleanupData);
      }
    }
  }

  if (mWalkStack.Length() > 0) {
    mozilla::UniquePtr<WalkData> toWalk = mWalkStack.PopLastElement();
    // Bounce this off the event loop to avoid stack overflow.
    using WalkStorage = StoreCopyPassByRRef<decltype(toWalk)>;
    auto saveMethod = &nsWebBrowserPersist::SaveDocumentDeferred;
    nsCOMPtr<nsIRunnable> saveLater = NewRunnableMethod<WalkStorage>(
        "nsWebBrowserPersist::FinishSaveDocumentInternal", this, saveMethod,
        std::move(toWalk));
    NS_DispatchToCurrentThread(saveLater);
  } else {
    // Done walking DOMs; on to the serialization phase.
    SerializeNextFile();
  }
}

void nsWebBrowserPersist::Cleanup() {
  mURIMap.Clear();
  nsClassHashtable<nsISupportsHashKey, OutputData> outputMapCopy;
  {
    MutexAutoLock lock(mOutputMapMutex);
    mOutputMap.SwapElements(outputMapCopy);
  }
  for (const auto& key : outputMapCopy.Keys()) {
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(key);
    if (channel) {
      channel->Cancel(NS_BINDING_ABORTED);
    }
  }
  outputMapCopy.Clear();

  for (const auto& key : mUploadList.Keys()) {
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(key);
    if (channel) {
      channel->Cancel(NS_BINDING_ABORTED);
    }
  }
  mUploadList.Clear();

  uint32_t i;
  for (i = 0; i < mDocList.Length(); i++) {
    DocData* docData = mDocList.ElementAt(i);
    delete docData;
  }
  mDocList.Clear();

  for (i = 0; i < mCleanupList.Length(); i++) {
    CleanupData* cleanupData = mCleanupList.ElementAt(i);
    delete cleanupData;
  }
  mCleanupList.Clear();

  mFilenameList.Clear();
}

void nsWebBrowserPersist::CleanupLocalFiles() {
  // Two passes, the first pass cleans up files, the second pass tests
  // for and then deletes empty directories. Directories that are not
  // empty after the first pass must contain files from something else
  // and are not deleted.
  int pass;
  for (pass = 0; pass < 2; pass++) {
    uint32_t i;
    for (i = 0; i < mCleanupList.Length(); i++) {
      CleanupData* cleanupData = mCleanupList.ElementAt(i);
      nsCOMPtr<nsIFile> file = cleanupData->mFile;

      // Test if the dir / file exists (something in an earlier loop
      // may have already removed it)
      bool exists = false;
      file->Exists(&exists);
      if (!exists) continue;

      // Test if the file has changed in between creation and deletion
      // in some way that means it should be ignored
      bool isDirectory = false;
      file->IsDirectory(&isDirectory);
      if (isDirectory != cleanupData->mIsDirectory)
        continue;  // A file has become a dir or vice versa !

      if (pass == 0 && !isDirectory) {
        file->Remove(false);
      } else if (pass == 1 && isDirectory)  // Directory
      {
        // Directories are more complicated. Enumerate through
        // children looking for files. Any files created by the
        // persist object would have been deleted by the first
        // pass so if there are any there at this stage, the dir
        // cannot be deleted because it has someone else's files
        // in it. Empty child dirs are deleted but they must be
        // recursed through to ensure they are actually empty.

        bool isEmptyDirectory = true;
        nsCOMArray<nsIDirectoryEnumerator> dirStack;
        int32_t stackSize = 0;

        // Push the top level enum onto the stack
        nsCOMPtr<nsIDirectoryEnumerator> pos;
        if (NS_SUCCEEDED(file->GetDirectoryEntries(getter_AddRefs(pos))))
          dirStack.AppendObject(pos);

        while (isEmptyDirectory && (stackSize = dirStack.Count())) {
          // Pop the last element
          nsCOMPtr<nsIDirectoryEnumerator> curPos;
          curPos = dirStack[stackSize - 1];
          dirStack.RemoveObjectAt(stackSize - 1);

          nsCOMPtr<nsIFile> child;
          if (NS_FAILED(curPos->GetNextFile(getter_AddRefs(child))) || !child) {
            continue;
          }

          bool childIsSymlink = false;
          child->IsSymlink(&childIsSymlink);
          bool childIsDir = false;
          child->IsDirectory(&childIsDir);
          if (!childIsDir || childIsSymlink) {
            // Some kind of file or symlink which means dir
            // is not empty so just drop out.
            isEmptyDirectory = false;
            break;
          }
          // Push parent enumerator followed by child enumerator
          nsCOMPtr<nsIDirectoryEnumerator> childPos;
          child->GetDirectoryEntries(getter_AddRefs(childPos));
          dirStack.AppendObject(curPos);
          if (childPos) dirStack.AppendObject(childPos);
        }
        dirStack.Clear();

        // If after all that walking the dir is deemed empty, delete it
        if (isEmptyDirectory) {
          file->Remove(true);
        }
      }
    }
  }
}

nsresult nsWebBrowserPersist::CalculateUniqueFilename(
    nsIURI* aURI, nsCOMPtr<nsIURI>& aOutURI) {
  nsCOMPtr<nsIURL> url(do_QueryInterface(aURI));
  NS_ENSURE_TRUE(url, NS_ERROR_FAILURE);

  bool nameHasChanged = false;
  nsresult rv;

  // Get the old filename
  nsAutoCString filename;
  rv = url->GetFileName(filename);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
  nsAutoCString directory;
  rv = url->GetDirectory(directory);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // Split the filename into a base and an extension.
  // e.g. "foo.html" becomes "foo" & ".html"
  //
  // The nsIURL methods GetFileBaseName & GetFileExtension don't
  // preserve the dot whereas this code does to save some effort
  // later when everything is put back together.
  int32_t lastDot = filename.RFind(".");
  nsAutoCString base;
  nsAutoCString ext;
  if (lastDot >= 0) {
    filename.Mid(base, 0, lastDot);
    filename.Mid(ext, lastDot, filename.Length() - lastDot);  // includes dot
  } else {
    // filename contains no dot
    base = filename;
  }

  // Test if the filename is longer than allowed by the OS
  int32_t needToChop = filename.Length() - kDefaultMaxFilenameLength;
  if (needToChop > 0) {
    // Truncate the base first and then the ext if necessary
    if (base.Length() > (uint32_t)needToChop) {
      base.Truncate(base.Length() - needToChop);
    } else {
      needToChop -= base.Length() - 1;
      base.Truncate(1);
      if (ext.Length() > (uint32_t)needToChop) {
        ext.Truncate(ext.Length() - needToChop);
      } else {
        ext.Truncate(0);
      }
      // If kDefaultMaxFilenameLength were 1 we'd be in trouble here,
      // but that won't happen because it will be set to a sensible
      // value.
    }

    filename.Assign(base);
    filename.Append(ext);
    nameHasChanged = true;
  }

  // Ensure the filename is unique
  // Create a filename if it's empty, or if the filename / datapath is
  // already taken by another URI and create an alternate name.

  if (base.IsEmpty() || !mFilenameList.IsEmpty()) {
    nsAutoCString tmpPath;
    nsAutoCString tmpBase;
    uint32_t duplicateCounter = 1;
    while (true) {
      // Make a file name,
      // Foo become foo_001, foo_002, etc.
      // Empty files become _001, _002 etc.

      if (base.IsEmpty() || duplicateCounter > 1) {
        SmprintfPointer tmp = mozilla::Smprintf("_%03d", duplicateCounter);
        NS_ENSURE_TRUE(tmp, NS_ERROR_OUT_OF_MEMORY);
        if (filename.Length() < kDefaultMaxFilenameLength - 4) {
          tmpBase = base;
        } else {
          base.Mid(tmpBase, 0, base.Length() - 4);
        }
        tmpBase.Append(tmp.get());
      } else {
        tmpBase = base;
      }

      tmpPath.Assign(directory);
      tmpPath.Append(tmpBase);
      tmpPath.Append(ext);

      // Test if the name is a duplicate
      if (!mFilenameList.Contains(tmpPath)) {
        if (!base.Equals(tmpBase)) {
          filename.Assign(tmpBase);
          filename.Append(ext);
          nameHasChanged = true;
        }
        break;
      }
      duplicateCounter++;
    }
  }

  // Add name to list of those already used
  nsAutoCString newFilepath(directory);
  newFilepath.Append(filename);
  mFilenameList.AppendElement(newFilepath);

  // Update the uri accordingly if the filename actually changed
  if (nameHasChanged) {
    // Final sanity test
    if (filename.Length() > kDefaultMaxFilenameLength) {
      NS_WARNING(
          "Filename wasn't truncated less than the max file length - how can "
          "that be?");
      return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsIFile> localFile;
    GetLocalFileFromURI(aURI, getter_AddRefs(localFile));

    if (localFile) {
      nsAutoString filenameAsUnichar;
      CopyASCIItoUTF16(filename, filenameAsUnichar);
      localFile->SetLeafName(filenameAsUnichar);

      // Resync the URI with the file after the extension has been appended
      return NS_MutateURI(aURI)
          .Apply(&nsIFileURLMutator::SetFile, localFile)
          .Finalize(aOutURI);
    }
    return NS_MutateURI(url)
        .Apply(&nsIURLMutator::SetFileName, filename, nullptr)
        .Finalize(aOutURI);
  }

  // TODO (:valentin) This method should always clone aURI
  aOutURI = aURI;
  return NS_OK;
}

nsresult nsWebBrowserPersist::MakeFilenameFromURI(nsIURI* aURI,
                                                  nsString& aFilename) {
  // Try to get filename from the URI.
  nsAutoString fileName;

  // Get a suggested file name from the URL but strip it of characters
  // likely to cause the name to be illegal.

  nsCOMPtr<nsIURL> url(do_QueryInterface(aURI));
  if (url) {
    nsAutoCString nameFromURL;
    url->GetFileName(nameFromURL);
    if (mPersistFlags & PERSIST_FLAGS_DONT_CHANGE_FILENAMES) {
      CopyASCIItoUTF16(NS_UnescapeURL(nameFromURL), fileName);
      aFilename = fileName;
      return NS_OK;
    }
    if (!nameFromURL.IsEmpty()) {
      // Unescape the file name (GetFileName escapes it)
      NS_UnescapeURL(nameFromURL);
      uint32_t nameLength = 0;
      const char* p = nameFromURL.get();
      for (; *p && *p != ';' && *p != '?' && *p != '#' && *p != '.'; p++) {
        if (IsAsciiAlpha(*p) || IsAsciiDigit(*p) || *p == '.' || *p == '-' ||
            *p == '_' || (*p == ' ')) {
          fileName.Append(char16_t(*p));
          if (++nameLength == kDefaultMaxFilenameLength) {
            // Note:
            // There is no point going any further since it will be
            // truncated in CalculateUniqueFilename anyway.
            // More importantly, certain implementations of
            // nsIFile (e.g. the Mac impl) might truncate
            // names in undesirable ways, such as truncating from
            // the middle, inserting ellipsis and so on.
            break;
          }
        }
      }
    }
  }

  // Empty filenames can confuse the local file object later
  // when it attempts to set the leaf name in CalculateUniqueFilename
  // for duplicates and ends up replacing the parent dir. To avoid
  // the problem, all filenames are made at least one character long.
  if (fileName.IsEmpty()) {
    fileName.Append(char16_t('a'));  // 'a' is for arbitrary
  }

  aFilename = fileName;
  return NS_OK;
}

nsresult nsWebBrowserPersist::CalculateAndAppendFileExt(
    nsIURI* aURI, nsIChannel* aChannel, nsIURI* aOriginalURIWithExtension,
    nsCOMPtr<nsIURI>& aOutURI) {
  nsresult rv = NS_OK;

  if (!mMIMEService) {
    mMIMEService = do_GetService(NS_MIMESERVICE_CONTRACTID, &rv);
    NS_ENSURE_TRUE(mMIMEService, NS_ERROR_FAILURE);
  }

  nsAutoCString contentType;

  // Get the content type from the channel
  aChannel->GetContentType(contentType);

  // Get the content type from the MIME service
  if (contentType.IsEmpty()) {
    nsCOMPtr<nsIURI> uri;
    aChannel->GetOriginalURI(getter_AddRefs(uri));
    mMIMEService->GetTypeFromURI(uri, contentType);
  }

  // Validate the filename
  if (!contentType.IsEmpty()) {
    nsAutoString newFileName;
    if (NS_SUCCEEDED(mMIMEService->GetValidFileName(
            aChannel, contentType, aOriginalURIWithExtension,
            nsIMIMEService::VALIDATE_DEFAULT, newFileName))) {
      nsCOMPtr<nsIFile> localFile;
      GetLocalFileFromURI(aURI, getter_AddRefs(localFile));
      if (localFile) {
        localFile->SetLeafName(newFileName);

        // Resync the URI with the file after the extension has been appended
        return NS_MutateURI(aURI)
            .Apply(&nsIFileURLMutator::SetFile, localFile)
            .Finalize(aOutURI);
      }
      return NS_MutateURI(aURI)
          .Apply(&nsIURLMutator::SetFileName,
                 NS_ConvertUTF16toUTF8(newFileName), nullptr)
          .Finalize(aOutURI);
    }
  }

  // TODO (:valentin) This method should always clone aURI
  aOutURI = aURI;
  return NS_OK;
}

// Note: the MakeOutputStream helpers can be called from a background thread.
nsresult nsWebBrowserPersist::MakeOutputStream(
    nsIURI* aURI, nsIOutputStream** aOutputStream) {
  nsresult rv;

  nsCOMPtr<nsIFile> localFile;
  GetLocalFileFromURI(aURI, getter_AddRefs(localFile));
  if (localFile)
    rv = MakeOutputStreamFromFile(localFile, aOutputStream);
  else
    rv = MakeOutputStreamFromURI(aURI, aOutputStream);

  return rv;
}

nsresult nsWebBrowserPersist::MakeOutputStreamFromFile(
    nsIFile* aFile, nsIOutputStream** aOutputStream) {
  nsresult rv = NS_OK;

  nsCOMPtr<nsIFileOutputStream> fileOutputStream =
      do_CreateInstance(NS_LOCALFILEOUTPUTSTREAM_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // XXX brade:  get the right flags here!
  int32_t ioFlags = -1;
  if (mPersistFlags & nsIWebBrowserPersist::PERSIST_FLAGS_APPEND_TO_FILE)
    ioFlags = PR_APPEND | PR_CREATE_FILE | PR_WRONLY;
  rv = fileOutputStream->Init(aFile, ioFlags, -1, 0);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = NS_NewBufferedOutputStream(aOutputStream, fileOutputStream.forget(),
                                  BUFFERED_OUTPUT_SIZE);
  NS_ENSURE_SUCCESS(rv, rv);

  if (mPersistFlags & PERSIST_FLAGS_CLEANUP_ON_FAILURE) {
    // Add to cleanup list in event of failure
    auto* cleanupData = new CleanupData;
    cleanupData->mFile = aFile;
    cleanupData->mIsDirectory = false;
    if (NS_IsMainThread()) {
      mCleanupList.AppendElement(cleanupData);
    } else {
      // If we're on a background thread, add the cleanup back on the main
      // thread.
      RefPtr<Runnable> addCleanup = NS_NewRunnableFunction(
          "nsWebBrowserPersist::AddCleanupToList",
          [self = RefPtr{this}, cleanup = std::move(cleanupData)]() {
            self->mCleanupList.AppendElement(cleanup);
          });
      NS_DispatchToMainThread(addCleanup);
    }
  }

  return NS_OK;
}

nsresult nsWebBrowserPersist::MakeOutputStreamFromURI(
    nsIURI* aURI, nsIOutputStream** aOutputStream) {
  uint32_t segsize = 8192;
  uint32_t maxsize = uint32_t(-1);
  nsCOMPtr<nsIStorageStream> storStream;
  nsresult rv =
      NS_NewStorageStream(segsize, maxsize, getter_AddRefs(storStream));
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_SUCCESS(CallQueryInterface(storStream, aOutputStream),
                    NS_ERROR_FAILURE);
  return NS_OK;
}

void nsWebBrowserPersist::FinishDownload() {
  // We call FinishDownload when we run out of things to download for this
  // persist operation, by dispatching this method to the main thread. By now,
  // it's possible that we have been canceled or encountered an error earlier
  // in the download, or something else called EndDownload. In that case, don't
  // re-run EndDownload.
  if (mEndCalled) {
    return;
  }
  EndDownload(NS_OK);
}

void nsWebBrowserPersist::EndDownload(nsresult aResult) {
  MOZ_ASSERT(NS_IsMainThread(), "Should end download on the main thread.");

  // Really this should just never happen, but if it does, at least avoid
  // no-op notifications or pretending we succeeded if we already failed.
  if (mEndCalled && (NS_SUCCEEDED(aResult) || mPersistResult == aResult)) {
    return;
  }

  // Store the error code in the result if it is an error
  if (NS_SUCCEEDED(mPersistResult) && NS_FAILED(aResult)) {
    mPersistResult = aResult;
  }

  if (mEndCalled) {
    MOZ_ASSERT(!mEndCalled, "Should only end the download once.");
    return;
  }
  mEndCalled = true;

  ClosePromise::All(GetCurrentSerialEventTarget(), mFileClosePromises)
      ->Then(GetCurrentSerialEventTarget(), __func__,
             [self = RefPtr{this}, aResult]() {
               self->EndDownloadInternal(aResult);
             });
}

void nsWebBrowserPersist::EndDownloadInternal(nsresult aResult) {
  // mCompleted needs to be set before issuing the stop notification.
  // (Bug 1224437)
  mCompleted = true;
  // State stop notification
  if (mProgressListener) {
    mProgressListener->OnStateChange(
        nullptr, nullptr,
        nsIWebProgressListener::STATE_STOP |
            nsIWebProgressListener::STATE_IS_NETWORK,
        mPersistResult);
  }

  // Do file cleanup if required
  if (NS_FAILED(aResult) &&
      (mPersistFlags & PERSIST_FLAGS_CLEANUP_ON_FAILURE)) {
    CleanupLocalFiles();
  }

  // Cleanup the channels
  Cleanup();

  mProgressListener = nullptr;
  mProgressListener2 = nullptr;
  mEventSink = nullptr;
}

nsresult nsWebBrowserPersist::FixRedirectedChannelEntry(
    nsIChannel* aNewChannel) {
  NS_ENSURE_ARG_POINTER(aNewChannel);

  // Iterate through existing open channels looking for one with a URI
  // matching the one specified.
  nsCOMPtr<nsIURI> originalURI;
  aNewChannel->GetOriginalURI(getter_AddRefs(originalURI));
  nsISupports* matchingKey = nullptr;
  for (nsISupports* key : mOutputMap.Keys()) {
    nsCOMPtr<nsIChannel> thisChannel = do_QueryInterface(key);
    nsCOMPtr<nsIURI> thisURI;

    thisChannel->GetOriginalURI(getter_AddRefs(thisURI));

    // Compare this channel's URI to the one passed in.
    bool matchingURI = false;
    thisURI->Equals(originalURI, &matchingURI);
    if (matchingURI) {
      matchingKey = key;
      break;
    }
  }

  if (matchingKey) {
    // We only get called from OnStartRequest, so this is always on the
    // main thread. Make sure we don't pull the rug from under anything else.
    MutexAutoLock lock(mOutputMapMutex);
    // If a match was found, remove the data entry with the old channel
    // key and re-add it with the new channel key.
    mozilla::UniquePtr<OutputData> outputData;
    mOutputMap.Remove(matchingKey, &outputData);
    NS_ENSURE_TRUE(outputData, NS_ERROR_FAILURE);

    // Store data again with new channel unless told to ignore redirects.
    if (!(mPersistFlags & PERSIST_FLAGS_IGNORE_REDIRECTED_DATA)) {
      nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(aNewChannel);
      mOutputMap.InsertOrUpdate(keyPtr, std::move(outputData));
    }
  }

  return NS_OK;
}

void nsWebBrowserPersist::CalcTotalProgress() {
  mTotalCurrentProgress = 0;
  mTotalMaxProgress = 0;

  if (mOutputMap.Count() > 0) {
    // Total up the progress of each output stream
    for (const auto& data : mOutputMap.Values()) {
      // Only count toward total progress if destination file is local.
      nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(data->mFile);
      if (fileURL) {
        mTotalCurrentProgress += data->mSelfProgress;
        mTotalMaxProgress += data->mSelfProgressMax;
      }
    }
  }

  if (mUploadList.Count() > 0) {
    // Total up the progress of each upload
    for (const auto& data : mUploadList.Values()) {
      if (data) {
        mTotalCurrentProgress += data->mSelfProgress;
        mTotalMaxProgress += data->mSelfProgressMax;
      }
    }
  }

  // XXX this code seems pretty bogus and pointless
  if (mTotalCurrentProgress == 0 && mTotalMaxProgress == 0) {
    // No output streams so we must be complete
    mTotalCurrentProgress = 10000;
    mTotalMaxProgress = 10000;
  }
}

nsresult nsWebBrowserPersist::StoreURI(const nsACString& aURI,
                                       nsIWebBrowserPersistDocument* aDoc,
                                       nsContentPolicyType aContentPolicyType,
                                       bool aNeedsPersisting, URIData** aData) {
  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_NewURI(getter_AddRefs(uri), aURI, mCurrentCharset.get(),
                          mCurrentBaseURI);
  NS_ENSURE_SUCCESS(rv, rv);

  return StoreURI(uri, aDoc, aContentPolicyType, aNeedsPersisting, aData);
}

nsresult nsWebBrowserPersist::StoreURI(nsIURI* aURI,
                                       nsIWebBrowserPersistDocument* aDoc,
                                       nsContentPolicyType aContentPolicyType,
                                       bool aNeedsPersisting, URIData** aData) {
  NS_ENSURE_ARG_POINTER(aURI);
  if (aData) {
    *aData = nullptr;
  }

  // Test if this URI should be persisted. By default
  // we should assume the URI  is persistable.
  bool doNotPersistURI;
  nsresult rv = NS_URIChainHasFlags(
      aURI, nsIProtocolHandler::URI_NON_PERSISTABLE, &doNotPersistURI);
  if (NS_FAILED(rv)) {
    doNotPersistURI = false;
  }

  if (doNotPersistURI) {
    return NS_OK;
  }

  URIData* data = nullptr;
  MakeAndStoreLocalFilenameInURIMap(aURI, aDoc, aContentPolicyType,
                                    aNeedsPersisting, &data);
  if (aData) {
    *aData = data;
  }

  return NS_OK;
}

nsresult nsWebBrowserPersist::URIData::GetLocalURI(nsIURI* targetBaseURI,
                                                   nsCString& aSpecOut) {
  aSpecOut.SetIsVoid(true);
  if (!mNeedsFixup) {
    return NS_OK;
  }
  nsresult rv;
  nsCOMPtr<nsIURI> fileAsURI;
  if (mFile) {
    fileAsURI = mFile;
  } else {
    fileAsURI = mDataPath;
    rv = AppendPathToURI(fileAsURI, mFilename, fileAsURI);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // remove username/password if present
  Unused << NS_MutateURI(fileAsURI).SetUserPass(""_ns).Finalize(fileAsURI);

  // reset node attribute
  // Use relative or absolute links
  if (mDataPathIsRelative) {
    bool isEqual = false;
    if (NS_SUCCEEDED(mRelativeDocumentURI->Equals(targetBaseURI, &isEqual)) &&
        isEqual) {
      nsCOMPtr<nsIURL> url(do_QueryInterface(fileAsURI));
      if (!url) {
        return NS_ERROR_FAILURE;
      }

      nsAutoCString filename;
      url->GetFileName(filename);

      nsAutoCString rawPathURL(mRelativePathToData);
      rawPathURL.Append(filename);

      rv = NS_EscapeURL(rawPathURL, esc_FilePath, aSpecOut, fallible);
      NS_ENSURE_SUCCESS(rv, rv);
    } else {
      nsAutoCString rawPathURL;

      nsCOMPtr<nsIFile> dataFile;
      rv = GetLocalFileFromURI(mFile, getter_AddRefs(dataFile));
      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<nsIFile> docFile;
      rv = GetLocalFileFromURI(targetBaseURI, getter_AddRefs(docFile));
      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<nsIFile> parentDir;
      rv = docFile->GetParent(getter_AddRefs(parentDir));
      NS_ENSURE_SUCCESS(rv, rv);

      rv = dataFile->GetRelativePath(parentDir, rawPathURL);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = NS_EscapeURL(rawPathURL, esc_FilePath, aSpecOut, fallible);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  } else {
    fileAsURI->GetSpec(aSpecOut);
  }
  if (mIsSubFrame) {
    AppendUTF16toUTF8(mSubFrameExt, aSpecOut);
  }

  return NS_OK;
}

bool nsWebBrowserPersist::DocumentEncoderExists(const char* aContentType) {
  return do_getDocumentTypeSupportedForEncoding(aContentType);
}

nsresult nsWebBrowserPersist::SaveSubframeContent(
    nsIWebBrowserPersistDocument* aFrameContent,
    nsIWebBrowserPersistDocument* aParentDocument, const nsCString& aURISpec,
    URIData* aData) {
  NS_ENSURE_ARG_POINTER(aData);

  // Extract the content type for the frame's contents.
  nsAutoCString contentType;
  nsresult rv = aFrameContent->GetContentType(contentType);
  NS_ENSURE_SUCCESS(rv, rv);

  nsString ext;
  GetExtensionForContentType(NS_ConvertASCIItoUTF16(contentType).get(),
                             getter_Copies(ext));

  // We must always have an extension so we will try to re-assign
  // the original extension if GetExtensionForContentType fails.
  if (ext.IsEmpty()) {
    nsCOMPtr<nsIURI> docURI;
    rv = NS_NewURI(getter_AddRefs(docURI), aURISpec, mCurrentCharset.get());
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIURL> url(do_QueryInterface(docURI, &rv));
    nsAutoCString extension;
    if (NS_SUCCEEDED(rv)) {
      url->GetFileExtension(extension);
    } else {
      extension.AssignLiteral("htm");
    }
    aData->mSubFrameExt.Assign(char16_t('.'));
    AppendUTF8toUTF16(extension, aData->mSubFrameExt);
  } else {
    aData->mSubFrameExt.Assign(char16_t('.'));
    aData->mSubFrameExt.Append(ext);
  }

  nsString filenameWithExt = aData->mFilename;
  filenameWithExt.Append(aData->mSubFrameExt);

  // Work out the path for the subframe
  nsCOMPtr<nsIURI> frameURI = mCurrentDataPath;
  rv = AppendPathToURI(frameURI, filenameWithExt, frameURI);
  NS_ENSURE_SUCCESS(rv, rv);

  // Work out the path for the subframe data
  nsCOMPtr<nsIURI> frameDataURI = mCurrentDataPath;
  nsAutoString newFrameDataPath(aData->mFilename);

  // Append _data
  newFrameDataPath.AppendLiteral("_data");
  rv = AppendPathToURI(frameDataURI, newFrameDataPath, frameDataURI);
  NS_ENSURE_SUCCESS(rv, rv);

  // Make frame document & data path conformant and unique
  nsCOMPtr<nsIURI> out;
  rv = CalculateUniqueFilename(frameURI, out);
  NS_ENSURE_SUCCESS(rv, rv);
  frameURI = out;

  rv = CalculateUniqueFilename(frameDataURI, out);
  NS_ENSURE_SUCCESS(rv, rv);
  frameDataURI = out;

  mCurrentThingsToPersist++;

  // We shouldn't use SaveDocumentInternal for the contents
  // of frames that are not documents, e.g. images.
  if (DocumentEncoderExists(contentType.get())) {
    auto toWalk = mozilla::MakeUnique<WalkData>();
    toWalk->mDocument = aFrameContent;
    toWalk->mFile = frameURI;
    toWalk->mDataPath = frameDataURI;
    mWalkStack.AppendElement(std::move(toWalk));
  } else {
    nsContentPolicyType policyType = nsIContentPolicy::TYPE_OTHER;
    if (StringBeginsWith(contentType, "image/"_ns)) {
      policyType = nsIContentPolicy::TYPE_IMAGE;
    } else if (StringBeginsWith(contentType, "audio/"_ns) ||
               StringBeginsWith(contentType, "video/"_ns)) {
      policyType = nsIContentPolicy::TYPE_MEDIA;
    }
    rv = StoreURI(aURISpec, aParentDocument, policyType);
  }
  NS_ENSURE_SUCCESS(rv, rv);

  // Store the updated uri to the frame
  aData->mFile = frameURI;
  aData->mSubFrameExt.Truncate();  // we already put this in frameURI

  return NS_OK;
}

nsresult nsWebBrowserPersist::CreateChannelFromURI(nsIURI* aURI,
                                                   nsIChannel** aChannel) {
  nsresult rv = NS_OK;
  *aChannel = nullptr;

  rv = NS_NewChannel(aChannel, aURI, nsContentUtils::GetSystemPrincipal(),
                     nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
                     nsIContentPolicy::TYPE_OTHER);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_ARG_POINTER(*aChannel);

  rv = (*aChannel)->SetNotificationCallbacks(
      static_cast<nsIInterfaceRequestor*>(this));
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_OK;
}

// we store the current location as the key (absolutized version of domnode's
// attribute's value)
nsresult nsWebBrowserPersist::MakeAndStoreLocalFilenameInURIMap(
    nsIURI* aURI, nsIWebBrowserPersistDocument* aDoc,
    nsContentPolicyType aContentPolicyType, bool aNeedsPersisting,
    URIData** aData) {
  NS_ENSURE_ARG_POINTER(aURI);

  nsAutoCString spec;
  nsresult rv = aURI->GetSpec(spec);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // Create a sensibly named filename for the URI and store in the URI map
  URIData* data;
  if (mURIMap.Get(spec, &data)) {
    if (aNeedsPersisting) {
      data->mNeedsPersisting = true;
    }
    if (aData) {
      *aData = data;
    }
    return NS_OK;
  }

  // Create a unique file name for the uri
  nsString filename;
  rv = MakeFilenameFromURI(aURI, filename);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // Store the file name
  data = new URIData;

  data->mContentPolicyType = aContentPolicyType;
  data->mNeedsPersisting = aNeedsPersisting;
  data->mNeedsFixup = true;
  data->mFilename = filename;
  data->mSaved = false;
  data->mIsSubFrame = false;
  data->mDataPath = mCurrentDataPath;
  data->mDataPathIsRelative = mCurrentDataPathIsRelative;
  data->mRelativePathToData = mCurrentRelativePathToData;
  data->mRelativeDocumentURI = mTargetBaseURI;
  data->mCharset = mCurrentCharset;

  aDoc->GetPrincipal(getter_AddRefs(data->mTriggeringPrincipal));
  aDoc->GetCookieJarSettings(getter_AddRefs(data->mCookieJarSettings));

  if (aNeedsPersisting) mCurrentThingsToPersist++;

  mURIMap.InsertOrUpdate(spec, UniquePtr<URIData>(data));
  if (aData) {
    *aData = data;
  }

  return NS_OK;
}

// Decide if we need to apply conversion to the passed channel.
void nsWebBrowserPersist::SetApplyConversionIfNeeded(nsIChannel* aChannel) {
  nsresult rv = NS_OK;
  nsCOMPtr<nsIEncodedChannel> encChannel = do_QueryInterface(aChannel, &rv);
  if (NS_FAILED(rv)) return;

  // Set the default conversion preference:
  encChannel->SetApplyConversion(false);

  nsCOMPtr<nsIURI> thisURI;
  aChannel->GetURI(getter_AddRefs(thisURI));
  nsCOMPtr<nsIURL> sourceURL(do_QueryInterface(thisURI));
  if (!sourceURL) return;
  nsAutoCString extension;
  sourceURL->GetFileExtension(extension);

  nsCOMPtr<nsIUTF8StringEnumerator> encEnum;
  encChannel->GetContentEncodings(getter_AddRefs(encEnum));
  if (!encEnum) return;
  nsCOMPtr<nsIExternalHelperAppService> helperAppService =
      do_GetService(NS_EXTERNALHELPERAPPSERVICE_CONTRACTID, &rv);
  if (NS_FAILED(rv)) return;
  bool hasMore;
  rv = encEnum->HasMore(&hasMore);
  if (NS_SUCCEEDED(rv) && hasMore) {
    nsAutoCString encType;
    rv = encEnum->GetNext(encType);
    if (NS_SUCCEEDED(rv)) {
      bool applyConversion = false;
      rv = helperAppService->ApplyDecodingForExtension(extension, encType,
                                                       &applyConversion);
      if (NS_SUCCEEDED(rv)) encChannel->SetApplyConversion(applyConversion);
    }
  }
}