summaryrefslogtreecommitdiffstats
path: root/netwerk/cache/nsDiskCacheDeviceSQL.cpp
blob: f4b1d72c98d212529d4949e4d900c37dec6782c3 (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
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cin: */
/* 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 <inttypes.h>

#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/Sprintf.h"
#include "mozilla/ThreadLocal.h"

#include "nsCache.h"
#include "nsDiskCache.h"
#include "nsDiskCacheDeviceSQL.h"
#include "nsCacheService.h"
#include "nsApplicationCache.h"

#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsIURI.h"
#include "nsAutoPtr.h"
#include "nsEscape.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsString.h"
#include "nsPrintfCString.h"
#include "nsCRT.h"
#include "nsArrayUtils.h"
#include "nsIArray.h"
#include "nsIVariant.h"
#include "nsILoadContextInfo.h"
#include "nsThreadUtils.h"
#include "nsISerializable.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsSerializationHelper.h"

#include "mozIStorageService.h"
#include "mozIStorageStatement.h"
#include "mozIStorageFunction.h"
#include "mozStorageHelper.h"

#include "nsICacheVisitor.h"
#include "nsISeekableStream.h"

#include "mozilla/Telemetry.h"

#include "sqlite3.h"
#include "mozilla/storage.h"
#include "nsVariant.h"
#include "mozilla/BasePrincipal.h"

using namespace mozilla;
using namespace mozilla::storage;
using mozilla::NeckoOriginAttributes;

static const char OFFLINE_CACHE_DEVICE_ID[] = { "offline" };

#define LOG(args) CACHE_LOG_DEBUG(args)

static uint32_t gNextTemporaryClientID = 0;

/*****************************************************************************
 * helpers
 */

static nsresult
EnsureDir(nsIFile *dir)
{
  bool exists;
  nsresult rv = dir->Exists(&exists);
  if (NS_SUCCEEDED(rv) && !exists)
    rv = dir->Create(nsIFile::DIRECTORY_TYPE, 0700);
  return rv;
}

static bool
DecomposeCacheEntryKey(const nsCString *fullKey,
                       const char **cid,
                       const char **key,
                       nsCString &buf)
{
  buf = *fullKey;

  int32_t colon = buf.FindChar(':');
  if (colon == kNotFound)
  {
    NS_ERROR("Invalid key");
    return false;
  }
  buf.SetCharAt('\0', colon);

  *cid = buf.get();
  *key = buf.get() + colon + 1;

  return true;
}

class AutoResetStatement
{
  public:
    explicit AutoResetStatement(mozIStorageStatement *s)
      : mStatement(s) {}
    ~AutoResetStatement() { mStatement->Reset(); }
    mozIStorageStatement *operator->() MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mStatement; }
  private:
    mozIStorageStatement *mStatement;
};

class EvictionObserver
{
  public:
  EvictionObserver(mozIStorageConnection *db,
                   nsOfflineCacheEvictionFunction *evictionFunction)
    : mDB(db), mEvictionFunction(evictionFunction)
    {
      mEvictionFunction->Init();
      mDB->ExecuteSimpleSQL(
          NS_LITERAL_CSTRING("CREATE TEMP TRIGGER cache_on_delete BEFORE DELETE"
                             " ON moz_cache FOR EACH ROW BEGIN SELECT"
                             " cache_eviction_observer("
                             "  OLD.ClientID, OLD.key, OLD.generation);"
                             " END;"));
    }

    ~EvictionObserver()
    {
      mDB->ExecuteSimpleSQL(
        NS_LITERAL_CSTRING("DROP TRIGGER cache_on_delete;"));
      mEvictionFunction->Reset();
    }

    void Apply() { return mEvictionFunction->Apply(); }

  private:
    mozIStorageConnection *mDB;
    RefPtr<nsOfflineCacheEvictionFunction> mEvictionFunction;
};

#define DCACHE_HASH_MAX  INT64_MAX
#define DCACHE_HASH_BITS 64

/**
 *  nsOfflineCache::Hash(const char * key)
 *
 *  This algorithm of this method implies nsOfflineCacheRecords will be stored
 *  in a certain order on disk.  If the algorithm changes, existing cache
 *  map files may become invalid, and therefore the kCurrentVersion needs
 *  to be revised.
 */
static uint64_t
DCacheHash(const char * key)
{
  // initval 0x7416f295 was chosen randomly
  return (uint64_t(nsDiskCache::Hash(key, 0)) << 32) | nsDiskCache::Hash(key, 0x7416f295);
}

/******************************************************************************
 * nsOfflineCacheEvictionFunction
 */

NS_IMPL_ISUPPORTS(nsOfflineCacheEvictionFunction, mozIStorageFunction)

// helper function for directly exposing the same data file binding
// path algorithm used in nsOfflineCacheBinding::Create
static nsresult
GetCacheDataFile(nsIFile *cacheDir, const char *key,
                 int generation, nsCOMPtr<nsIFile> &file)
{
  cacheDir->Clone(getter_AddRefs(file));
  if (!file)
    return NS_ERROR_OUT_OF_MEMORY;

  uint64_t hash = DCacheHash(key);

  uint32_t dir1 = (uint32_t) (hash & 0x0F);
  uint32_t dir2 = (uint32_t)((hash & 0xF0) >> 4);

  hash >>= 8;

  file->AppendNative(nsPrintfCString("%X", dir1));
  file->AppendNative(nsPrintfCString("%X", dir2));

  char leaf[64];
  SprintfLiteral(leaf, "%014" PRIX64 "-%X", hash, generation);
  return file->AppendNative(nsDependentCString(leaf));
}

namespace appcachedetail {

typedef nsCOMArray<nsIFile> FileArray;
static MOZ_THREAD_LOCAL(FileArray*) tlsEvictionItems;

} // appcachedetail

NS_IMETHODIMP
nsOfflineCacheEvictionFunction::OnFunctionCall(mozIStorageValueArray *values, nsIVariant **_retval)
{
  LOG(("nsOfflineCacheEvictionFunction::OnFunctionCall\n"));

  *_retval = nullptr;

  uint32_t numEntries;
  nsresult rv = values->GetNumEntries(&numEntries);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ASSERTION(numEntries == 3, "unexpected number of arguments");

  uint32_t valueLen;
  const char *clientID = values->AsSharedUTF8String(0, &valueLen);
  const char *key = values->AsSharedUTF8String(1, &valueLen);
  nsAutoCString fullKey(clientID);
  fullKey.Append(':');
  fullKey.Append(key);
  int generation  = values->AsInt32(2);

  // If the key is currently locked, refuse to delete this row.
  if (mDevice->IsLocked(fullKey)) {
    NS_ADDREF(*_retval = new IntegerVariant(SQLITE_IGNORE));
    return NS_OK;
  }

  nsCOMPtr<nsIFile> file;
  rv = GetCacheDataFile(mDevice->CacheDirectory(), key,
                        generation, file);
  if (NS_FAILED(rv))
  {
    LOG(("GetCacheDataFile [key=%s generation=%d] failed [rv=%x]!\n",
         key, generation, rv));
    return rv;
  }

  appcachedetail::FileArray* items = appcachedetail::tlsEvictionItems.get();
  MOZ_ASSERT(items);
  if (items) {
    items->AppendObject(file);
  }

  return NS_OK;
}

nsOfflineCacheEvictionFunction::nsOfflineCacheEvictionFunction(nsOfflineCacheDevice * device)
  : mDevice(device)
{
  mTLSInited = appcachedetail::tlsEvictionItems.init();
}

void nsOfflineCacheEvictionFunction::Init()
{
  if (mTLSInited) {
    appcachedetail::tlsEvictionItems.set(new appcachedetail::FileArray());
  }
}

void nsOfflineCacheEvictionFunction::Reset()
{
  if (!mTLSInited) {
    return;
  }

  appcachedetail::FileArray* items = appcachedetail::tlsEvictionItems.get();
  if (!items) {
    return;
  }

  appcachedetail::tlsEvictionItems.set(nullptr);
  delete items;
}

void
nsOfflineCacheEvictionFunction::Apply()
{
  LOG(("nsOfflineCacheEvictionFunction::Apply\n"));

  if (!mTLSInited) {
    return;
  }

  appcachedetail::FileArray* pitems = appcachedetail::tlsEvictionItems.get();
  if (!pitems) {
    return;
  }

  appcachedetail::FileArray items;
  items.SwapElements(*pitems);

  for (int32_t i = 0; i < items.Count(); i++) {
    if (MOZ_LOG_TEST(gCacheLog, LogLevel::Debug)) {
      nsAutoCString path;
      items[i]->GetNativePath(path);
      LOG(("  removing %s\n", path.get()));
    }

    items[i]->Remove(false);
  }
}

class nsOfflineCacheDiscardCache : public Runnable
{
public:
  nsOfflineCacheDiscardCache(nsOfflineCacheDevice *device,
			     nsCString &group,
			     nsCString &clientID)
    : mDevice(device)
    , mGroup(group)
    , mClientID(clientID)
  {
  }

  NS_IMETHOD Run() override
  {
    if (mDevice->IsActiveCache(mGroup, mClientID))
    {
      mDevice->DeactivateGroup(mGroup);
    }

    return mDevice->EvictEntries(mClientID.get());
  }

private:
  RefPtr<nsOfflineCacheDevice> mDevice;
  nsCString mGroup;
  nsCString mClientID;
};

/******************************************************************************
 * nsOfflineCacheDeviceInfo
 */

class nsOfflineCacheDeviceInfo final : public nsICacheDeviceInfo
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSICACHEDEVICEINFO

  explicit nsOfflineCacheDeviceInfo(nsOfflineCacheDevice* device)
    : mDevice(device)
  {}

private:
  ~nsOfflineCacheDeviceInfo() {}

  nsOfflineCacheDevice* mDevice;
};

NS_IMPL_ISUPPORTS(nsOfflineCacheDeviceInfo, nsICacheDeviceInfo)

NS_IMETHODIMP
nsOfflineCacheDeviceInfo::GetDescription(char **aDescription)
{
  *aDescription = NS_strdup("Offline cache device");
  return *aDescription ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}

NS_IMETHODIMP
nsOfflineCacheDeviceInfo::GetUsageReport(char ** usageReport)
{
  nsAutoCString buffer;
  buffer.AssignLiteral("  <tr>\n"
                       "    <th>Cache Directory:</th>\n"
                       "    <td>");
  nsIFile *cacheDir = mDevice->CacheDirectory();
  if (!cacheDir)
    return NS_OK;

  nsAutoString path;
  nsresult rv = cacheDir->GetPath(path);
  if (NS_SUCCEEDED(rv))
    AppendUTF16toUTF8(path, buffer);
  else
    buffer.AppendLiteral("directory unavailable");
  
  buffer.AppendLiteral("</td>\n"
                       "  </tr>\n");

  *usageReport = ToNewCString(buffer);
  if (!*usageReport)
    return NS_ERROR_OUT_OF_MEMORY;

  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheDeviceInfo::GetEntryCount(uint32_t *aEntryCount)
{
  *aEntryCount = mDevice->EntryCount();
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheDeviceInfo::GetTotalSize(uint32_t *aTotalSize)
{
  *aTotalSize = mDevice->CacheSize();
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheDeviceInfo::GetMaximumSize(uint32_t *aMaximumSize)
{
  *aMaximumSize = mDevice->CacheCapacity();
  return NS_OK;
}

/******************************************************************************
 * nsOfflineCacheBinding
 */

class nsOfflineCacheBinding final : public nsISupports
{
  ~nsOfflineCacheBinding() {}

public:
  NS_DECL_THREADSAFE_ISUPPORTS

  static nsOfflineCacheBinding *
      Create(nsIFile *cacheDir, const nsCString *key, int generation);

  enum { FLAG_NEW_ENTRY = 1 };

  nsCOMPtr<nsIFile> mDataFile;
  int               mGeneration;
  int		    mFlags;

  bool IsNewEntry() { return mFlags & FLAG_NEW_ENTRY; }
  void MarkNewEntry() { mFlags |= FLAG_NEW_ENTRY; }
  void ClearNewEntry() { mFlags &= ~FLAG_NEW_ENTRY; }
};

NS_IMPL_ISUPPORTS0(nsOfflineCacheBinding)

nsOfflineCacheBinding *
nsOfflineCacheBinding::Create(nsIFile *cacheDir,
                              const nsCString *fullKey,
                              int generation)
{
  nsCOMPtr<nsIFile> file;
  cacheDir->Clone(getter_AddRefs(file));
  if (!file)
    return nullptr;

  nsAutoCString keyBuf;
  const char *cid, *key;
  if (!DecomposeCacheEntryKey(fullKey, &cid, &key, keyBuf))
    return nullptr;

  uint64_t hash = DCacheHash(key);

  uint32_t dir1 = (uint32_t) (hash & 0x0F);
  uint32_t dir2 = (uint32_t)((hash & 0xF0) >> 4);

  hash >>= 8;

  // XXX we might want to create these directories up-front

  file->AppendNative(nsPrintfCString("%X", dir1));
  Unused << file->Create(nsIFile::DIRECTORY_TYPE, 00700);

  file->AppendNative(nsPrintfCString("%X", dir2));
  Unused << file->Create(nsIFile::DIRECTORY_TYPE, 00700);

  nsresult rv;
  char leaf[64];

  if (generation == -1)
  {
    file->AppendNative(NS_LITERAL_CSTRING("placeholder"));

    for (generation = 0; ; ++generation)
    {
      SprintfLiteral(leaf, "%014" PRIX64 "-%X", hash, generation);

      rv = file->SetNativeLeafName(nsDependentCString(leaf));
      if (NS_FAILED(rv))
        return nullptr;
      rv = file->Create(nsIFile::NORMAL_FILE_TYPE, 00600);
      if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS)
        return nullptr;
      if (NS_SUCCEEDED(rv))
        break;
    }
  }
  else
  {
    SprintfLiteral(leaf, "%014" PRIX64 "-%X", hash, generation);
    rv = file->AppendNative(nsDependentCString(leaf));
    if (NS_FAILED(rv))
      return nullptr;
  }

  nsOfflineCacheBinding *binding = new nsOfflineCacheBinding;
  if (!binding)
    return nullptr;

  binding->mDataFile.swap(file);
  binding->mGeneration = generation;
  binding->mFlags = 0;
  return binding;
}

/******************************************************************************
 * nsOfflineCacheRecord
 */

struct nsOfflineCacheRecord
{
  const char    *clientID;
  const char    *key;
  const uint8_t *metaData;
  uint32_t       metaDataLen;
  int32_t        generation;
  int32_t        dataSize;
  int32_t        fetchCount;
  int64_t        lastFetched;
  int64_t        lastModified;
  int64_t        expirationTime;
};

static nsCacheEntry *
CreateCacheEntry(nsOfflineCacheDevice *device,
                 const nsCString *fullKey,
                 const nsOfflineCacheRecord &rec)
{
  nsCacheEntry *entry;

  if (device->IsLocked(*fullKey)) {
      return nullptr;
  }
  
  nsresult rv = nsCacheEntry::Create(fullKey->get(), // XXX enable sharing
                                     nsICache::STREAM_BASED,
                                     nsICache::STORE_OFFLINE,
                                     device, &entry);
  if (NS_FAILED(rv))
    return nullptr;

  entry->SetFetchCount((uint32_t) rec.fetchCount);
  entry->SetLastFetched(SecondsFromPRTime(rec.lastFetched));
  entry->SetLastModified(SecondsFromPRTime(rec.lastModified));
  entry->SetExpirationTime(SecondsFromPRTime(rec.expirationTime));
  entry->SetDataSize((uint32_t) rec.dataSize);

  entry->UnflattenMetaData((const char *) rec.metaData, rec.metaDataLen);

  // Restore security info, if present
  const char* info = entry->GetMetaDataElement("security-info");
  if (info) {
    nsCOMPtr<nsISupports> infoObj;
    rv = NS_DeserializeObject(nsDependentCString(info),
                              getter_AddRefs(infoObj));
    if (NS_FAILED(rv)) {
      delete entry;
      return nullptr;
    }
    entry->SetSecurityInfo(infoObj);
  }

  // create a binding object for this entry
  nsOfflineCacheBinding *binding =
      nsOfflineCacheBinding::Create(device->CacheDirectory(),
                                    fullKey,
                                    rec.generation);
  if (!binding)
  {
    delete entry;
    return nullptr;
  }
  entry->SetData(binding);

  return entry;
}


/******************************************************************************
 * nsOfflineCacheEntryInfo
 */

class nsOfflineCacheEntryInfo final : public nsICacheEntryInfo
{
  ~nsOfflineCacheEntryInfo() {}

public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSICACHEENTRYINFO

  nsOfflineCacheRecord *mRec;
};

NS_IMPL_ISUPPORTS(nsOfflineCacheEntryInfo, nsICacheEntryInfo)

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetClientID(char **result)
{
  *result = NS_strdup(mRec->clientID);
  return *result ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetDeviceID(char ** deviceID)
{
  *deviceID = NS_strdup(OFFLINE_CACHE_DEVICE_ID);
  return *deviceID ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetKey(nsACString &clientKey)
{
  clientKey.Assign(mRec->key);
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetFetchCount(int32_t *aFetchCount)
{
  *aFetchCount = mRec->fetchCount;
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetLastFetched(uint32_t *aLastFetched)
{
  *aLastFetched = SecondsFromPRTime(mRec->lastFetched);
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetLastModified(uint32_t *aLastModified)
{
  *aLastModified = SecondsFromPRTime(mRec->lastModified);
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetExpirationTime(uint32_t *aExpirationTime)
{
  *aExpirationTime = SecondsFromPRTime(mRec->expirationTime);
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::IsStreamBased(bool *aStreamBased)
{
  *aStreamBased = true;
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheEntryInfo::GetDataSize(uint32_t *aDataSize)
{
  *aDataSize = mRec->dataSize;
  return NS_OK;
}


/******************************************************************************
 * nsApplicationCacheNamespace
 */

NS_IMPL_ISUPPORTS(nsApplicationCacheNamespace, nsIApplicationCacheNamespace)

NS_IMETHODIMP
nsApplicationCacheNamespace::Init(uint32_t itemType,
                                  const nsACString &namespaceSpec,
                                  const nsACString &data)
{
  mItemType = itemType;
  mNamespaceSpec = namespaceSpec;
  mData = data;
  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCacheNamespace::GetItemType(uint32_t *out)
{
  *out = mItemType;
  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCacheNamespace::GetNamespaceSpec(nsACString &out)
{
  out = mNamespaceSpec;
  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCacheNamespace::GetData(nsACString &out)
{
  out = mData;
  return NS_OK;
}

/******************************************************************************
 * nsApplicationCache
 */

NS_IMPL_ISUPPORTS(nsApplicationCache,
                  nsIApplicationCache,
                  nsISupportsWeakReference)

nsApplicationCache::nsApplicationCache()
  : mDevice(nullptr)
  , mValid(true)
{
}

nsApplicationCache::nsApplicationCache(nsOfflineCacheDevice *device,
                                       const nsACString &group,
                                       const nsACString &clientID)
  : mDevice(device)
  , mGroup(group)
  , mClientID(clientID)
  , mValid(true)
{
}

nsApplicationCache::~nsApplicationCache()
{
  if (!mDevice)
    return;

  {
    MutexAutoLock lock(mDevice->mLock);
    mDevice->mCaches.Remove(mClientID);
  }

  // If this isn't an active cache anymore, it can be destroyed.
  if (mValid && !mDevice->IsActiveCache(mGroup, mClientID))
    Discard();
}

void
nsApplicationCache::MarkInvalid()
{
  mValid = false;
}

NS_IMETHODIMP
nsApplicationCache::InitAsHandle(const nsACString &groupId,
                                 const nsACString &clientId)
{
  NS_ENSURE_FALSE(mDevice, NS_ERROR_ALREADY_INITIALIZED);
  NS_ENSURE_TRUE(mGroup.IsEmpty(), NS_ERROR_ALREADY_INITIALIZED);

  mGroup = groupId;
  mClientID = clientId;
  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::GetManifestURI(nsIURI **out)
{
  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_NewURI(getter_AddRefs(uri), mGroup);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = uri->CloneIgnoringRef(out);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::GetGroupID(nsACString &out)
{
  out = mGroup;
  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::GetClientID(nsACString &out)
{
  out = mClientID;
  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::GetProfileDirectory(nsIFile **out)
{
  if (mDevice->BaseDirectory())
      NS_ADDREF(*out = mDevice->BaseDirectory());
  else
      *out = nullptr;

  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::GetActive(bool *out)
{
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  *out = mDevice->IsActiveCache(mGroup, mClientID);
  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::Activate()
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  mDevice->ActivateCache(mGroup, mClientID);

  if (mDevice->AutoShutdown(this))
    mDevice = nullptr;

  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::Discard()
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  mValid = false;

  nsCOMPtr<nsIRunnable> ev =
    new nsOfflineCacheDiscardCache(mDevice, mGroup, mClientID);
  nsresult rv = nsCacheService::DispatchToCacheIOThread(ev);
  return rv;
}

NS_IMETHODIMP
nsApplicationCache::MarkEntry(const nsACString &key,
                              uint32_t typeBits)
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  return mDevice->MarkEntry(mClientID, key, typeBits);
}


NS_IMETHODIMP
nsApplicationCache::UnmarkEntry(const nsACString &key,
                                uint32_t typeBits)
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  return mDevice->UnmarkEntry(mClientID, key, typeBits);
}

NS_IMETHODIMP
nsApplicationCache::GetTypes(const nsACString &key,
                             uint32_t *typeBits)
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  return mDevice->GetTypes(mClientID, key, typeBits);
}

NS_IMETHODIMP
nsApplicationCache::GatherEntries(uint32_t typeBits,
                                  uint32_t * count,
                                  char *** keys)
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  return mDevice->GatherEntries(mClientID, typeBits, count, keys);
}

NS_IMETHODIMP
nsApplicationCache::AddNamespaces(nsIArray *namespaces)
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  if (!namespaces)
    return NS_OK;

  mozStorageTransaction transaction(mDevice->mDB, false);

  uint32_t length;
  nsresult rv = namespaces->GetLength(&length);
  NS_ENSURE_SUCCESS(rv, rv);

  for (uint32_t i = 0; i < length; i++) {
    nsCOMPtr<nsIApplicationCacheNamespace> ns =
      do_QueryElementAt(namespaces, i);
    if (ns) {
      rv = mDevice->AddNamespace(mClientID, ns);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  rv = transaction.Commit();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

NS_IMETHODIMP
nsApplicationCache::GetMatchingNamespace(const nsACString &key,
                                         nsIApplicationCacheNamespace **out)

{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  return mDevice->GetMatchingNamespace(mClientID, key, out);
}

NS_IMETHODIMP
nsApplicationCache::GetUsage(uint32_t *usage)
{
  NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
  NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);

  return mDevice->GetUsage(mClientID, usage);
}

/******************************************************************************
 * nsCloseDBEvent
 *****************************************************************************/

class nsCloseDBEvent : public Runnable {
public:
  explicit nsCloseDBEvent(mozIStorageConnection *aDB)
  {
    mDB = aDB;
  }

  NS_IMETHOD Run() override
  {
    mDB->Close();
    return NS_OK;
  }

protected:
  virtual ~nsCloseDBEvent() {}

private:
  nsCOMPtr<mozIStorageConnection> mDB;
};



/******************************************************************************
 * nsOfflineCacheDevice
 */

NS_IMPL_ISUPPORTS0(nsOfflineCacheDevice)

nsOfflineCacheDevice::nsOfflineCacheDevice()
  : mDB(nullptr)
  , mCacheCapacity(0)
  , mDeltaCounter(0)
  , mAutoShutdown(false)
  , mLock("nsOfflineCacheDevice.lock")
  , mActiveCaches(4)
  , mLockedEntries(32)
{
}

nsOfflineCacheDevice::~nsOfflineCacheDevice()
{}

/* static */
bool
nsOfflineCacheDevice::GetStrictFileOriginPolicy()
{
    nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);

    bool retval;
    if (prefs && NS_SUCCEEDED(prefs->GetBoolPref("security.fileuri.strict_origin_policy", &retval)))
        return retval;

    // As default value use true (be more strict)
    return true;
}

uint32_t
nsOfflineCacheDevice::CacheSize()
{
  NS_ENSURE_TRUE(Initialized(), 0);

  AutoResetStatement statement(mStatement_CacheSize);

  bool hasRows;
  nsresult rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && hasRows, 0);
  
  return (uint32_t) statement->AsInt32(0);
}

uint32_t
nsOfflineCacheDevice::EntryCount()
{
  NS_ENSURE_TRUE(Initialized(), 0);

  AutoResetStatement statement(mStatement_EntryCount);

  bool hasRows;
  nsresult rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && hasRows, 0);

  return (uint32_t) statement->AsInt32(0);
}

nsresult
nsOfflineCacheDevice::UpdateEntry(nsCacheEntry *entry)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  // Decompose the key into "ClientID" and "Key"
  nsAutoCString keyBuf;
  const char *cid, *key;

  if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf))
    return NS_ERROR_UNEXPECTED;

  // Store security info, if it is serializable
  nsCOMPtr<nsISupports> infoObj = entry->SecurityInfo();
  nsCOMPtr<nsISerializable> serializable = do_QueryInterface(infoObj);
  if (infoObj && !serializable)
    return NS_ERROR_UNEXPECTED;

  if (serializable) {
    nsCString info;
    nsresult rv = NS_SerializeToString(serializable, info);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = entry->SetMetaDataElement("security-info", info.get());
    NS_ENSURE_SUCCESS(rv, rv);
  }

  nsCString metaDataBuf;
  uint32_t mdSize = entry->MetaDataSize();
  if (!metaDataBuf.SetLength(mdSize, fallible))
    return NS_ERROR_OUT_OF_MEMORY;
  char *md = metaDataBuf.BeginWriting();
  entry->FlattenMetaData(md, mdSize);

  nsOfflineCacheRecord rec;
  rec.metaData = (const uint8_t *) md;
  rec.metaDataLen = mdSize;
  rec.dataSize = entry->DataSize();
  rec.fetchCount = entry->FetchCount();
  rec.lastFetched = PRTimeFromSeconds(entry->LastFetched());
  rec.lastModified = PRTimeFromSeconds(entry->LastModified());
  rec.expirationTime = PRTimeFromSeconds(entry->ExpirationTime());

  AutoResetStatement statement(mStatement_UpdateEntry);

  nsresult rv;
  rv = statement->BindBlobByIndex(0, rec.metaData, rec.metaDataLen);
  nsresult tmp = statement->BindInt32ByIndex(1, rec.dataSize);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt32ByIndex(2, rec.fetchCount);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt64ByIndex(3, rec.lastFetched);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt64ByIndex(4, rec.lastModified);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt64ByIndex(5, rec.expirationTime);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindUTF8StringByIndex(6, nsDependentCString(cid));
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindUTF8StringByIndex(7, nsDependentCString(key));
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ASSERTION(!hasRows, "UPDATE should not result in output");
  return rv;
}

nsresult
nsOfflineCacheDevice::UpdateEntrySize(nsCacheEntry *entry, uint32_t newSize)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  // Decompose the key into "ClientID" and "Key"
  nsAutoCString keyBuf;
  const char *cid, *key;
  if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf))
    return NS_ERROR_UNEXPECTED;

  AutoResetStatement statement(mStatement_UpdateEntrySize);

  nsresult rv = statement->BindInt32ByIndex(0, newSize);
  nsresult tmp = statement->BindUTF8StringByIndex(1, nsDependentCString(cid));
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindUTF8StringByIndex(2, nsDependentCString(key));
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ASSERTION(!hasRows, "UPDATE should not result in output");
  return rv;
}

nsresult
nsOfflineCacheDevice::DeleteEntry(nsCacheEntry *entry, bool deleteData)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  if (deleteData)
  {
    nsresult rv = DeleteData(entry);
    if (NS_FAILED(rv))
      return rv;
  }

  // Decompose the key into "ClientID" and "Key"
  nsAutoCString keyBuf;
  const char *cid, *key;
  if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf))
    return NS_ERROR_UNEXPECTED;

  AutoResetStatement statement(mStatement_DeleteEntry);

  nsresult rv = statement->BindUTF8StringByIndex(0, nsDependentCString(cid));
  nsresult rv2 = statement->BindUTF8StringByIndex(1, nsDependentCString(key));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_SUCCESS(rv2, rv2);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ASSERTION(!hasRows, "DELETE should not result in output");
  return rv;
}

nsresult
nsOfflineCacheDevice::DeleteData(nsCacheEntry *entry)
{
  nsOfflineCacheBinding *binding = (nsOfflineCacheBinding *) entry->Data();
  NS_ENSURE_STATE(binding);

  return binding->mDataFile->Remove(false);
}

/**
 * nsCacheDevice implementation
 */

// This struct is local to nsOfflineCacheDevice::Init, but ISO C++98 doesn't
// allow a template (mozilla::ArrayLength) to be instantiated based on a local
// type.  Boo-urns!
struct StatementSql {
    nsCOMPtr<mozIStorageStatement> &statement;
    const char *sql;
    StatementSql (nsCOMPtr<mozIStorageStatement> &aStatement, const char *aSql):
      statement (aStatement), sql (aSql) {}
};

nsresult
nsOfflineCacheDevice::Init()
{
  MOZ_ASSERT(false, "Need to be initialized with sqlite");
  return NS_ERROR_NOT_IMPLEMENTED;
}

nsresult
nsOfflineCacheDevice::InitWithSqlite(mozIStorageService * ss)
{
  NS_ENSURE_TRUE(!mDB, NS_ERROR_ALREADY_INITIALIZED);

  // SetCacheParentDirectory must have been called
  NS_ENSURE_TRUE(mCacheDirectory, NS_ERROR_UNEXPECTED);

  // make sure the cache directory exists
  nsresult rv = EnsureDir(mCacheDirectory);
  NS_ENSURE_SUCCESS(rv, rv);

  // build path to index file
  nsCOMPtr<nsIFile> indexFile; 
  rv = mCacheDirectory->Clone(getter_AddRefs(indexFile));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = indexFile->AppendNative(NS_LITERAL_CSTRING("index.sqlite"));
  NS_ENSURE_SUCCESS(rv, rv);

  MOZ_ASSERT(ss, "nsOfflineCacheDevice::InitWithSqlite called before nsCacheService::Init() ?");
  NS_ENSURE_TRUE(ss, NS_ERROR_UNEXPECTED);

  rv = ss->OpenDatabase(indexFile, getter_AddRefs(mDB));
  NS_ENSURE_SUCCESS(rv, rv);

  mInitThread = do_GetCurrentThread();

  mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = OFF;"));

  // XXX ... other initialization steps

  // XXX in the future we may wish to verify the schema for moz_cache
  //     perhaps using "PRAGMA table_info" ?

  // build the table
  //
  //  "Generation" is the data file generation number.
  //
  rv = mDB->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS moz_cache (\n"
                         "  ClientID        TEXT,\n"
                         "  Key             TEXT,\n"
                         "  MetaData        BLOB,\n"
                         "  Generation      INTEGER,\n"
                         "  DataSize        INTEGER,\n"
                         "  FetchCount      INTEGER,\n"
                         "  LastFetched     INTEGER,\n"
                         "  LastModified    INTEGER,\n"
                         "  ExpirationTime  INTEGER,\n"
                         "  ItemType        INTEGER DEFAULT 0\n"
                         ");\n"));
  NS_ENSURE_SUCCESS(rv, rv);

  // Databases from 1.9.0 don't have the ItemType column.  Add the column
  // here, but don't worry about failures (the column probably already exists)
  mDB->ExecuteSimpleSQL(
    NS_LITERAL_CSTRING("ALTER TABLE moz_cache ADD ItemType INTEGER DEFAULT 0"));

  // Create the table for storing cache groups.  All actions on
  // moz_cache_groups use the GroupID, so use it as the primary key.
  rv = mDB->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS moz_cache_groups (\n"
                         " GroupID TEXT PRIMARY KEY,\n"
                         " ActiveClientID TEXT\n"
                         ");\n"));
  NS_ENSURE_SUCCESS(rv, rv);

  mDB->ExecuteSimpleSQL(
    NS_LITERAL_CSTRING("ALTER TABLE moz_cache_groups "
                       "ADD ActivateTimeStamp INTEGER DEFAULT 0"));

  // ClientID: clientID joining moz_cache and moz_cache_namespaces
  // tables.
  // Data: Data associated with this namespace (e.g. a fallback URI
  // for fallback entries).
  // ItemType: the type of namespace.
  rv = mDB->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS"
                         " moz_cache_namespaces (\n"
                         " ClientID TEXT,\n"
                         " NameSpace TEXT,\n"
                         " Data TEXT,\n"
                         " ItemType INTEGER\n"
                          ");\n"));
   NS_ENSURE_SUCCESS(rv, rv);

  // Databases from 1.9.0 have a moz_cache_index that should be dropped
  rv = mDB->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("DROP INDEX IF EXISTS moz_cache_index"));
  NS_ENSURE_SUCCESS(rv, rv);

  // Key/ClientID pairs should be unique in the database.  All queries
  // against moz_cache use the Key (which is also the most unique), so
  // use it as the primary key for this index.
  rv = mDB->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("CREATE UNIQUE INDEX IF NOT EXISTS "
                         " moz_cache_key_clientid_index"
                         " ON moz_cache (Key, ClientID);"));
  NS_ENSURE_SUCCESS(rv, rv);

  // Used for ClientID lookups and to keep ClientID/NameSpace pairs unique.
  rv = mDB->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("CREATE UNIQUE INDEX IF NOT EXISTS"
                         " moz_cache_namespaces_clientid_index"
                         " ON moz_cache_namespaces (ClientID, NameSpace);"));
  NS_ENSURE_SUCCESS(rv, rv);

  // Used for namespace lookups.
  rv = mDB->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("CREATE INDEX IF NOT EXISTS"
                         " moz_cache_namespaces_namespace_index"
                         " ON moz_cache_namespaces (NameSpace);"));
  NS_ENSURE_SUCCESS(rv, rv);


  mEvictionFunction = new nsOfflineCacheEvictionFunction(this);
  if (!mEvictionFunction) return NS_ERROR_OUT_OF_MEMORY;

  rv = mDB->CreateFunction(NS_LITERAL_CSTRING("cache_eviction_observer"), 3, mEvictionFunction);
  NS_ENSURE_SUCCESS(rv, rv);

  // create all (most) of our statements up front
  StatementSql prepared[] = {
    StatementSql ( mStatement_CacheSize,         "SELECT Sum(DataSize) from moz_cache;" ),
    StatementSql ( mStatement_ApplicationCacheSize, "SELECT Sum(DataSize) from moz_cache WHERE ClientID = ?;" ),
    StatementSql ( mStatement_EntryCount,        "SELECT count(*) from moz_cache;" ),
    StatementSql ( mStatement_UpdateEntry,       "UPDATE moz_cache SET MetaData = ?, DataSize = ?, FetchCount = ?, LastFetched = ?, LastModified = ?, ExpirationTime = ? WHERE ClientID = ? AND Key = ?;" ),
    StatementSql ( mStatement_UpdateEntrySize,   "UPDATE moz_cache SET DataSize = ? WHERE ClientID = ? AND Key = ?;" ),
    StatementSql ( mStatement_DeleteEntry,       "DELETE FROM moz_cache WHERE ClientID = ? AND Key = ?;" ),
    StatementSql ( mStatement_FindEntry,         "SELECT MetaData, Generation, DataSize, FetchCount, LastFetched, LastModified, ExpirationTime, ItemType FROM moz_cache WHERE ClientID = ? AND Key = ?;" ),
    StatementSql ( mStatement_BindEntry,         "INSERT INTO moz_cache (ClientID, Key, MetaData, Generation, DataSize, FetchCount, LastFetched, LastModified, ExpirationTime) VALUES(?,?,?,?,?,?,?,?,?);" ),

    StatementSql ( mStatement_MarkEntry,         "UPDATE moz_cache SET ItemType = (ItemType | ?) WHERE ClientID = ? AND Key = ?;" ),
    StatementSql ( mStatement_UnmarkEntry,       "UPDATE moz_cache SET ItemType = (ItemType & ~?) WHERE ClientID = ? AND Key = ?;" ),
    StatementSql ( mStatement_GetTypes,          "SELECT ItemType FROM moz_cache WHERE ClientID = ? AND Key = ?;"),
    StatementSql ( mStatement_CleanupUnmarked,   "DELETE FROM moz_cache WHERE ClientID = ? AND Key = ? AND ItemType = 0;" ),
    StatementSql ( mStatement_GatherEntries,     "SELECT Key FROM moz_cache WHERE ClientID = ? AND (ItemType & ?) > 0;" ),

    StatementSql ( mStatement_ActivateClient,    "INSERT OR REPLACE INTO moz_cache_groups (GroupID, ActiveClientID, ActivateTimeStamp) VALUES (?, ?, ?);" ),
    StatementSql ( mStatement_DeactivateGroup,   "DELETE FROM moz_cache_groups WHERE GroupID = ?;" ),
    StatementSql ( mStatement_FindClient,        "SELECT ClientID, ItemType FROM moz_cache WHERE Key = ? ORDER BY LastFetched DESC, LastModified DESC;" ),

    // Search for namespaces that match the URI.  Use the <= operator
    // to ensure that we use the index on moz_cache_namespaces.
    StatementSql ( mStatement_FindClientByNamespace, "SELECT ns.ClientID, ns.ItemType FROM"
                                                     "  moz_cache_namespaces AS ns JOIN moz_cache_groups AS groups"
                                                     "  ON ns.ClientID = groups.ActiveClientID"
                                                     " WHERE ns.NameSpace <= ?1 AND ?1 GLOB ns.NameSpace || '*'"
                                                     " ORDER BY ns.NameSpace DESC, groups.ActivateTimeStamp DESC;"),
    StatementSql ( mStatement_FindNamespaceEntry,    "SELECT NameSpace, Data, ItemType FROM moz_cache_namespaces"
                                                     " WHERE ClientID = ?1"
                                                     " AND NameSpace <= ?2 AND ?2 GLOB NameSpace || '*'"
                                                     " ORDER BY NameSpace DESC;"),
    StatementSql ( mStatement_InsertNamespaceEntry,  "INSERT INTO moz_cache_namespaces (ClientID, NameSpace, Data, ItemType) VALUES(?, ?, ?, ?);"),
    StatementSql ( mStatement_EnumerateApps,         "SELECT GroupID, ActiveClientID FROM moz_cache_groups WHERE GroupID LIKE ?1;"),
    StatementSql ( mStatement_EnumerateGroups,       "SELECT GroupID, ActiveClientID FROM moz_cache_groups;"),
    StatementSql ( mStatement_EnumerateGroupsTimeOrder, "SELECT GroupID, ActiveClientID FROM moz_cache_groups ORDER BY ActivateTimeStamp;")
  };
  for (uint32_t i = 0; NS_SUCCEEDED(rv) && i < ArrayLength(prepared); ++i)
  {
    LOG(("Creating statement: %s\n", prepared[i].sql));

    rv = mDB->CreateStatement(nsDependentCString(prepared[i].sql),
                              getter_AddRefs(prepared[i].statement));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  rv = InitActiveCaches();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

namespace {

nsresult
GetGroupForCache(const nsCSubstring &clientID, nsCString &group)
{
  group.Assign(clientID);
  group.Truncate(group.FindChar('|'));
  NS_UnescapeURL(group);

  return NS_OK;
}

} // namespace

// static
nsresult
nsOfflineCacheDevice::BuildApplicationCacheGroupID(nsIURI *aManifestURL,
                                                   nsACString const &aOriginSuffix,
                                                   nsACString &_result)
{
  nsCOMPtr<nsIURI> newURI;
  nsresult rv = aManifestURL->CloneIgnoringRef(getter_AddRefs(newURI));
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString manifestSpec;
  rv = newURI->GetAsciiSpec(manifestSpec);
  NS_ENSURE_SUCCESS(rv, rv);

  _result.Assign(manifestSpec);
  _result.Append('#');
  _result.Append(aOriginSuffix);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::InitActiveCaches()
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  MutexAutoLock lock(mLock);

  AutoResetStatement statement(mStatement_EnumerateGroups);

  bool hasRows;
  nsresult rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  while (hasRows)
  {
    nsAutoCString group;
    statement->GetUTF8String(0, group);
    nsCString clientID;
    statement->GetUTF8String(1, clientID);

    mActiveCaches.PutEntry(clientID);
    mActiveCachesByGroup.Put(group, new nsCString(clientID));

    rv = statement->ExecuteStep(&hasRows);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::Shutdown()
{
  NS_ENSURE_TRUE(mDB, NS_ERROR_NOT_INITIALIZED);

  {
    MutexAutoLock lock(mLock);
    for (auto iter = mCaches.Iter(); !iter.Done(); iter.Next()) {
      nsCOMPtr<nsIApplicationCache> obj = do_QueryReferent(iter.UserData());
      if (obj) {
        auto appCache = static_cast<nsApplicationCache*>(obj.get());
        appCache->MarkInvalid();
      }
    }
  }

  {
  EvictionObserver evictionObserver(mDB, mEvictionFunction);

  // Delete all rows whose clientID is not an active clientID.
  nsresult rv = mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
    "DELETE FROM moz_cache WHERE rowid IN"
    "  (SELECT moz_cache.rowid FROM"
    "    moz_cache LEFT OUTER JOIN moz_cache_groups ON"
    "      (moz_cache.ClientID = moz_cache_groups.ActiveClientID)"
    "   WHERE moz_cache_groups.GroupID ISNULL)"));

  if (NS_FAILED(rv))
    NS_WARNING("Failed to clean up unused application caches.");
  else
    evictionObserver.Apply();

  // Delete all namespaces whose clientID is not an active clientID.
  rv = mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
    "DELETE FROM moz_cache_namespaces WHERE rowid IN"
    "  (SELECT moz_cache_namespaces.rowid FROM"
    "    moz_cache_namespaces LEFT OUTER JOIN moz_cache_groups ON"
    "      (moz_cache_namespaces.ClientID = moz_cache_groups.ActiveClientID)"
    "   WHERE moz_cache_groups.GroupID ISNULL)"));

  if (NS_FAILED(rv))
    NS_WARNING("Failed to clean up namespaces.");

  mEvictionFunction = nullptr;

  mStatement_CacheSize = nullptr;
  mStatement_ApplicationCacheSize = nullptr;
  mStatement_EntryCount = nullptr;
  mStatement_UpdateEntry = nullptr;
  mStatement_UpdateEntrySize = nullptr;
  mStatement_DeleteEntry = nullptr;
  mStatement_FindEntry = nullptr;
  mStatement_BindEntry = nullptr;
  mStatement_ClearDomain = nullptr;
  mStatement_MarkEntry = nullptr;
  mStatement_UnmarkEntry = nullptr;
  mStatement_GetTypes = nullptr;
  mStatement_FindNamespaceEntry = nullptr;
  mStatement_InsertNamespaceEntry = nullptr;
  mStatement_CleanupUnmarked = nullptr;
  mStatement_GatherEntries = nullptr;
  mStatement_ActivateClient = nullptr;
  mStatement_DeactivateGroup = nullptr;
  mStatement_FindClient = nullptr;
  mStatement_FindClientByNamespace = nullptr;
  mStatement_EnumerateApps = nullptr;
  mStatement_EnumerateGroups = nullptr;
  mStatement_EnumerateGroupsTimeOrder = nullptr;
  }

  // Close Database on the correct thread
  bool isOnCurrentThread = true;
  if (mInitThread)
    mInitThread->IsOnCurrentThread(&isOnCurrentThread);

  if (!isOnCurrentThread) {
    nsCOMPtr<nsIRunnable> ev = new nsCloseDBEvent(mDB);

    if (ev) {
      mInitThread->Dispatch(ev, NS_DISPATCH_NORMAL);
    }
  }
  else {
    mDB->Close();
  }

  mDB = nullptr;
  mInitThread = nullptr;

  return NS_OK;
}

const char *
nsOfflineCacheDevice::GetDeviceID()
{
  return OFFLINE_CACHE_DEVICE_ID;
}

nsCacheEntry *
nsOfflineCacheDevice::FindEntry(nsCString *fullKey, bool *collision)
{
  NS_ENSURE_TRUE(Initialized(), nullptr);

  LOG(("nsOfflineCacheDevice::FindEntry [key=%s]\n", fullKey->get()));

  // SELECT * FROM moz_cache WHERE key = ?

  // Decompose the key into "ClientID" and "Key"
  nsAutoCString keyBuf;
  const char *cid, *key;
  if (!DecomposeCacheEntryKey(fullKey, &cid, &key, keyBuf))
    return nullptr;

  AutoResetStatement statement(mStatement_FindEntry);

  nsresult rv = statement->BindUTF8StringByIndex(0, nsDependentCString(cid));
  nsresult rv2 = statement->BindUTF8StringByIndex(1, nsDependentCString(key));
  NS_ENSURE_SUCCESS(rv, nullptr);
  NS_ENSURE_SUCCESS(rv2, nullptr);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  if (NS_FAILED(rv) || !hasRows)
    return nullptr; // entry not found

  nsOfflineCacheRecord rec;
  statement->GetSharedBlob(0, &rec.metaDataLen,
                           (const uint8_t **) &rec.metaData);
  rec.generation     = statement->AsInt32(1);
  rec.dataSize       = statement->AsInt32(2);
  rec.fetchCount     = statement->AsInt32(3);
  rec.lastFetched    = statement->AsInt64(4);
  rec.lastModified   = statement->AsInt64(5);
  rec.expirationTime = statement->AsInt64(6);

  LOG(("entry: [%u %d %d %d %lld %lld %lld]\n",
        rec.metaDataLen,
        rec.generation,
        rec.dataSize,
        rec.fetchCount,
        rec.lastFetched,
        rec.lastModified,
        rec.expirationTime));

  nsCacheEntry *entry = CreateCacheEntry(this, fullKey, rec);

  if (entry)
  {
    // make sure that the data file exists
    nsOfflineCacheBinding *binding = (nsOfflineCacheBinding*)entry->Data();
    bool isFile;
    rv = binding->mDataFile->IsFile(&isFile);
    if (NS_FAILED(rv) || !isFile)
    {
      DeleteEntry(entry, false);
      delete entry;
      return nullptr;
    }

    // lock the entry
    Lock(*fullKey);
  }

  return entry;
}

nsresult
nsOfflineCacheDevice::DeactivateEntry(nsCacheEntry *entry)
{
  LOG(("nsOfflineCacheDevice::DeactivateEntry [key=%s]\n",
       entry->Key()->get()));

  // This method is called to inform us that the nsCacheEntry object is going
  // away.  We should persist anything that needs to be persisted, or if the
  // entry is doomed, we can go ahead and clear its storage.

  if (entry->IsDoomed())
  {
    // remove corresponding row and file if they exist

    // the row should have been removed in DoomEntry... we could assert that
    // that happened.  otherwise, all we have to do here is delete the file
    // on disk.
    DeleteData(entry);
  }
  else if (((nsOfflineCacheBinding *)entry->Data())->IsNewEntry())
  {
    // UPDATE the database row

    // Only new entries are updated, since offline cache is updated in
    // transactions.  New entries are those who is returned from
    // BindEntry().

    LOG(("nsOfflineCacheDevice::DeactivateEntry updating new entry\n"));
    UpdateEntry(entry);
  } else {
    LOG(("nsOfflineCacheDevice::DeactivateEntry "
	 "skipping update since entry is not dirty\n"));
  }

  // Unlock the entry
  Unlock(*entry->Key());

  delete entry;

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::BindEntry(nsCacheEntry *entry)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::BindEntry [key=%s]\n", entry->Key()->get()));

  NS_ENSURE_STATE(!entry->Data());

  // This method is called to inform us that we have a new entry.  The entry
  // may collide with an existing entry in our DB, but if that happens we can
  // assume that the entry is not being used.

  // INSERT the database row

  // XXX Assumption: if the row already exists, then FindEntry would have
  // returned it.  if that entry was doomed, then DoomEntry would have removed
  // it from the table.  so, we should always have to insert at this point.

  // Decompose the key into "ClientID" and "Key"
  nsAutoCString keyBuf;
  const char *cid, *key;
  if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf))
    return NS_ERROR_UNEXPECTED;

  // create binding, pick best generation number
  RefPtr<nsOfflineCacheBinding> binding =
      nsOfflineCacheBinding::Create(mCacheDirectory, entry->Key(), -1);
  if (!binding)
    return NS_ERROR_OUT_OF_MEMORY;
  binding->MarkNewEntry();

  nsOfflineCacheRecord rec;
  rec.clientID = cid;
  rec.key = key;
  rec.metaData = nullptr; // don't write any metadata now.
  rec.metaDataLen = 0;
  rec.generation = binding->mGeneration;
  rec.dataSize = 0;
  rec.fetchCount = entry->FetchCount();
  rec.lastFetched = PRTimeFromSeconds(entry->LastFetched());
  rec.lastModified = PRTimeFromSeconds(entry->LastModified());
  rec.expirationTime = PRTimeFromSeconds(entry->ExpirationTime());

  AutoResetStatement statement(mStatement_BindEntry);

  nsresult rv = statement->BindUTF8StringByIndex(0, nsDependentCString(rec.clientID));
  nsresult tmp = statement->BindUTF8StringByIndex(1, nsDependentCString(rec.key));
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindBlobByIndex(2, rec.metaData, rec.metaDataLen);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt32ByIndex(3, rec.generation);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt32ByIndex(4, rec.dataSize);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt32ByIndex(5, rec.fetchCount);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt64ByIndex(6, rec.lastFetched);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt64ByIndex(7, rec.lastModified);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  tmp = statement->BindInt64ByIndex(8, rec.expirationTime);
  if (NS_FAILED(tmp)) {
    rv = tmp;
  }
  NS_ENSURE_SUCCESS(rv, rv);
  
  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ASSERTION(!hasRows, "INSERT should not result in output");

  entry->SetData(binding);

  // lock the entry
  Lock(*entry->Key());

  return NS_OK;
}

void
nsOfflineCacheDevice::DoomEntry(nsCacheEntry *entry)
{
  LOG(("nsOfflineCacheDevice::DoomEntry [key=%s]\n", entry->Key()->get()));

  // This method is called to inform us that we should mark the entry to be
  // deleted when it is no longer in use.

  // We can go ahead and delete the corresponding row in our table,
  // but we must not delete the file on disk until we are deactivated.
  // In another word, the file should be deleted if the entry had been
  // deactivated.
  
  DeleteEntry(entry, !entry->IsActive());
}

nsresult
nsOfflineCacheDevice::OpenInputStreamForEntry(nsCacheEntry      *entry,
                                              nsCacheAccessMode  mode,
                                              uint32_t           offset,
                                              nsIInputStream   **result)
{
  LOG(("nsOfflineCacheDevice::OpenInputStreamForEntry [key=%s]\n",
       entry->Key()->get()));

  *result = nullptr;

  NS_ENSURE_TRUE(!offset || (offset < entry->DataSize()), NS_ERROR_INVALID_ARG);

  // return an input stream to the entry's data file.  the stream
  // may be read on a background thread.

  nsOfflineCacheBinding *binding = (nsOfflineCacheBinding *) entry->Data();
  NS_ENSURE_STATE(binding);

  nsCOMPtr<nsIInputStream> in;
  NS_NewLocalFileInputStream(getter_AddRefs(in), binding->mDataFile, PR_RDONLY);
  if (!in)
    return NS_ERROR_UNEXPECTED;

  // respect |offset| param
  if (offset != 0)
  {
    nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(in);
    NS_ENSURE_TRUE(seekable, NS_ERROR_UNEXPECTED);

    seekable->Seek(nsISeekableStream::NS_SEEK_SET, offset);
  }

  in.swap(*result);
  return NS_OK;
}

nsresult
nsOfflineCacheDevice::OpenOutputStreamForEntry(nsCacheEntry       *entry,
                                               nsCacheAccessMode   mode,
                                               uint32_t            offset,
                                               nsIOutputStream   **result)
{
  LOG(("nsOfflineCacheDevice::OpenOutputStreamForEntry [key=%s]\n",
       entry->Key()->get()));

  *result = nullptr;

  NS_ENSURE_TRUE(offset <= entry->DataSize(), NS_ERROR_INVALID_ARG);

  // return an output stream to the entry's data file.  we can assume
  // that the output stream will only be used on the main thread.

  nsOfflineCacheBinding *binding = (nsOfflineCacheBinding *) entry->Data();
  NS_ENSURE_STATE(binding);

  nsCOMPtr<nsIOutputStream> out;
  NS_NewLocalFileOutputStream(getter_AddRefs(out), binding->mDataFile,
                              PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
                              00600);
  if (!out)
    return NS_ERROR_UNEXPECTED;

  // respect |offset| param
  nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(out);
  NS_ENSURE_TRUE(seekable, NS_ERROR_UNEXPECTED);
  if (offset != 0)
    seekable->Seek(nsISeekableStream::NS_SEEK_SET, offset);

  // truncate the file at the given offset
  seekable->SetEOF();

  nsCOMPtr<nsIOutputStream> bufferedOut;
  nsresult rv =
    NS_NewBufferedOutputStream(getter_AddRefs(bufferedOut), out, 16 * 1024);
  NS_ENSURE_SUCCESS(rv, rv);

  bufferedOut.swap(*result);
  return NS_OK;
}

nsresult
nsOfflineCacheDevice::GetFileForEntry(nsCacheEntry *entry, nsIFile **result)
{
  LOG(("nsOfflineCacheDevice::GetFileForEntry [key=%s]\n",
       entry->Key()->get()));

  nsOfflineCacheBinding *binding = (nsOfflineCacheBinding *) entry->Data();
  NS_ENSURE_STATE(binding);

  NS_IF_ADDREF(*result = binding->mDataFile);
  return NS_OK;
}

nsresult
nsOfflineCacheDevice::OnDataSizeChange(nsCacheEntry *entry, int32_t deltaSize)
{
  LOG(("nsOfflineCacheDevice::OnDataSizeChange [key=%s delta=%d]\n",
      entry->Key()->get(), deltaSize));

  const int32_t DELTA_THRESHOLD = 1<<14; // 16k

  // called to notify us of an impending change in the total size of the
  // specified entry.

  uint32_t oldSize = entry->DataSize();
  NS_ASSERTION(deltaSize >= 0 || int32_t(oldSize) + deltaSize >= 0, "oops");
  uint32_t newSize = int32_t(oldSize) + deltaSize;
  UpdateEntrySize(entry, newSize);

  mDeltaCounter += deltaSize; // this may go negative

  if (mDeltaCounter >= DELTA_THRESHOLD)
  {
    if (CacheSize() > mCacheCapacity) {
      // the entry will overrun the cache capacity, doom the entry
      // and abort
#ifdef DEBUG
      nsresult rv =
#endif
        nsCacheService::DoomEntry(entry);
      NS_ASSERTION(NS_SUCCEEDED(rv), "DoomEntry() failed.");
      return NS_ERROR_ABORT;
    }

    mDeltaCounter = 0; // reset counter
  }

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::Visit(nsICacheVisitor *visitor)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  // called to enumerate the offline cache.

  nsCOMPtr<nsICacheDeviceInfo> deviceInfo =
      new nsOfflineCacheDeviceInfo(this);

  bool keepGoing;
  nsresult rv = visitor->VisitDevice(OFFLINE_CACHE_DEVICE_ID, deviceInfo,
                                     &keepGoing);
  if (NS_FAILED(rv))
    return rv;
  
  if (!keepGoing)
    return NS_OK;

  // SELECT * from moz_cache;

  nsOfflineCacheRecord rec;
  RefPtr<nsOfflineCacheEntryInfo> info = new nsOfflineCacheEntryInfo;
  if (!info)
    return NS_ERROR_OUT_OF_MEMORY;
  info->mRec = &rec;

  // XXX may want to list columns explicitly
  nsCOMPtr<mozIStorageStatement> statement;
  rv = mDB->CreateStatement(
      NS_LITERAL_CSTRING("SELECT * FROM moz_cache;"),
      getter_AddRefs(statement));
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  for (;;)
  {
    rv = statement->ExecuteStep(&hasRows);
    if (NS_FAILED(rv) || !hasRows)
      break;

    statement->GetSharedUTF8String(0, nullptr, &rec.clientID);
    statement->GetSharedUTF8String(1, nullptr, &rec.key);
    statement->GetSharedBlob(2, &rec.metaDataLen,
                             (const uint8_t **) &rec.metaData);
    rec.generation     = statement->AsInt32(3);
    rec.dataSize       = statement->AsInt32(4);
    rec.fetchCount     = statement->AsInt32(5);
    rec.lastFetched    = statement->AsInt64(6);
    rec.lastModified   = statement->AsInt64(7);
    rec.expirationTime = statement->AsInt64(8);

    bool keepGoing;
    rv = visitor->VisitEntry(OFFLINE_CACHE_DEVICE_ID, info, &keepGoing);
    if (NS_FAILED(rv) || !keepGoing)
      break;
  }

  info->mRec = nullptr;
  return NS_OK;
}

nsresult
nsOfflineCacheDevice::EvictEntries(const char *clientID)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::EvictEntries [cid=%s]\n",
       clientID ? clientID : ""));

  // called to evict all entries matching the given clientID.

  // need trigger to fire user defined function after a row is deleted
  // so we can delete the corresponding data file.
  EvictionObserver evictionObserver(mDB, mEvictionFunction);

  nsCOMPtr<mozIStorageStatement> statement;
  nsresult rv;
  if (clientID)
  {
    rv = mDB->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_cache WHERE ClientID=?;"),
                              getter_AddRefs(statement));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    rv = mDB->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_cache_groups WHERE ActiveClientID=?;"),
                              getter_AddRefs(statement));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    // TODO - Should update internal hashtables.
    // Low priority, since this API is not widely used.
  }
  else
  {
    rv = mDB->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_cache;"),
                              getter_AddRefs(statement));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    rv = mDB->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_cache_groups;"),
                              getter_AddRefs(statement));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    MutexAutoLock lock(mLock);
    mCaches.Clear();
    mActiveCaches.Clear();
    mActiveCachesByGroup.Clear();
  }

  evictionObserver.Apply();

  statement = nullptr;
  // Also evict any namespaces associated with this clientID.
  if (clientID)
  {
    rv = mDB->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_cache_namespaces WHERE ClientID=?"),
                              getter_AddRefs(statement));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID));
    NS_ENSURE_SUCCESS(rv, rv);
  }
  else
  {
    rv = mDB->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_cache_namespaces;"),
                              getter_AddRefs(statement));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  rv = statement->Execute();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::MarkEntry(const nsCString &clientID,
                                const nsACString &key,
                                uint32_t typeBits)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::MarkEntry [cid=%s, key=%s, typeBits=%d]\n",
       clientID.get(), PromiseFlatCString(key).get(), typeBits));

  AutoResetStatement statement(mStatement_MarkEntry);
  nsresult rv = statement->BindInt32ByIndex(0, typeBits);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindUTF8StringByIndex(1, clientID);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindUTF8StringByIndex(2, key);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->Execute();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::UnmarkEntry(const nsCString &clientID,
                                  const nsACString &key,
                                  uint32_t typeBits)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::UnmarkEntry [cid=%s, key=%s, typeBits=%d]\n",
       clientID.get(), PromiseFlatCString(key).get(), typeBits));

  AutoResetStatement statement(mStatement_UnmarkEntry);
  nsresult rv = statement->BindInt32ByIndex(0, typeBits);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindUTF8StringByIndex(1, clientID);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindUTF8StringByIndex(2, key);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->Execute();
  NS_ENSURE_SUCCESS(rv, rv);

  // Remove the entry if it is now empty.

  EvictionObserver evictionObserver(mDB, mEvictionFunction);

  AutoResetStatement cleanupStatement(mStatement_CleanupUnmarked);
  rv = cleanupStatement->BindUTF8StringByIndex(0, clientID);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = cleanupStatement->BindUTF8StringByIndex(1, key);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = cleanupStatement->Execute();
  NS_ENSURE_SUCCESS(rv, rv);

  evictionObserver.Apply();

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::GetMatchingNamespace(const nsCString &clientID,
                                           const nsACString &key,
                                           nsIApplicationCacheNamespace **out)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::GetMatchingNamespace [cid=%s, key=%s]\n",
       clientID.get(), PromiseFlatCString(key).get()));

  nsresult rv;

  AutoResetStatement statement(mStatement_FindNamespaceEntry);

  rv = statement->BindUTF8StringByIndex(0, clientID);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindUTF8StringByIndex(1, key);
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  *out = nullptr;

  bool found = false;
  nsCString nsSpec;
  int32_t nsType = 0;
  nsCString nsData;

  while (hasRows)
  {
    int32_t itemType;
    rv = statement->GetInt32(2, &itemType);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!found || itemType > nsType)
    {
      nsType = itemType;

      rv = statement->GetUTF8String(0, nsSpec);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = statement->GetUTF8String(1, nsData);
      NS_ENSURE_SUCCESS(rv, rv);

      found = true;
    }

    rv = statement->ExecuteStep(&hasRows);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (found) {
    nsCOMPtr<nsIApplicationCacheNamespace> ns =
      new nsApplicationCacheNamespace();
    if (!ns)
      return NS_ERROR_OUT_OF_MEMORY;
    rv = ns->Init(nsType, nsSpec, nsData);
    NS_ENSURE_SUCCESS(rv, rv);

    ns.swap(*out);
  }

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::CacheOpportunistically(const nsCString &clientID,
                                             const nsACString &key)
{
  // XXX: We should also be propagating this cache entry to other matching
  // caches.  See bug 444807.

  return MarkEntry(clientID, key, nsIApplicationCache::ITEM_OPPORTUNISTIC);
}

nsresult
nsOfflineCacheDevice::GetTypes(const nsCString &clientID,
                               const nsACString &key,
                               uint32_t *typeBits)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::GetTypes [cid=%s, key=%s]\n",
       clientID.get(), PromiseFlatCString(key).get()));

  AutoResetStatement statement(mStatement_GetTypes);
  nsresult rv = statement->BindUTF8StringByIndex(0, clientID);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindUTF8StringByIndex(1, key);
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!hasRows)
    return NS_ERROR_CACHE_KEY_NOT_FOUND;

  *typeBits = statement->AsInt32(0);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::GatherEntries(const nsCString &clientID,
                                    uint32_t typeBits,
                                    uint32_t *count,
                                    char ***keys)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::GatherEntries [cid=%s, typeBits=%X]\n",
       clientID.get(), typeBits));

  AutoResetStatement statement(mStatement_GatherEntries);
  nsresult rv = statement->BindUTF8StringByIndex(0, clientID);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->BindInt32ByIndex(1, typeBits);
  NS_ENSURE_SUCCESS(rv, rv);

  return RunSimpleQuery(mStatement_GatherEntries, 0, count, keys);
}

nsresult
nsOfflineCacheDevice::AddNamespace(const nsCString &clientID,
                                   nsIApplicationCacheNamespace *ns)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  nsCString namespaceSpec;
  nsresult rv = ns->GetNamespaceSpec(namespaceSpec);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString data;
  rv = ns->GetData(data);
  NS_ENSURE_SUCCESS(rv, rv);

  uint32_t itemType;
  rv = ns->GetItemType(&itemType);
  NS_ENSURE_SUCCESS(rv, rv);

  LOG(("nsOfflineCacheDevice::AddNamespace [cid=%s, ns=%s, data=%s, type=%d]",
       clientID.get(), namespaceSpec.get(), data.get(), itemType));

  AutoResetStatement statement(mStatement_InsertNamespaceEntry);

  rv = statement->BindUTF8StringByIndex(0, clientID);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->BindUTF8StringByIndex(1, namespaceSpec);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->BindUTF8StringByIndex(2, data);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->BindInt32ByIndex(3, itemType);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->Execute();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::GetUsage(const nsACString &clientID,
                               uint32_t *usage)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::GetUsage [cid=%s]\n",
       PromiseFlatCString(clientID).get()));

  *usage = 0;

  AutoResetStatement statement(mStatement_ApplicationCacheSize);

  nsresult rv = statement->BindUTF8StringByIndex(0, clientID);
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!hasRows)
    return NS_OK;

  *usage = static_cast<uint32_t>(statement->AsInt32(0));

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::GetGroups(uint32_t *count,
                                 char ***keys)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::GetGroups"));

  return RunSimpleQuery(mStatement_EnumerateGroups, 0, count, keys);
}

nsresult
nsOfflineCacheDevice::GetGroupsTimeOrdered(uint32_t *count,
					   char ***keys)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  LOG(("nsOfflineCacheDevice::GetGroupsTimeOrder"));

  return RunSimpleQuery(mStatement_EnumerateGroupsTimeOrder, 0, count, keys);
}

bool
nsOfflineCacheDevice::IsLocked(const nsACString &key)
{
  MutexAutoLock lock(mLock);
  return mLockedEntries.GetEntry(key);
}

void
nsOfflineCacheDevice::Lock(const nsACString &key)
{
  MutexAutoLock lock(mLock);
  mLockedEntries.PutEntry(key);
}

void
nsOfflineCacheDevice::Unlock(const nsACString &key)
{
  MutexAutoLock lock(mLock);
  mLockedEntries.RemoveEntry(key);
}

nsresult
nsOfflineCacheDevice::RunSimpleQuery(mozIStorageStatement * statement,
                                     uint32_t resultIndex,
                                     uint32_t * count,
                                     char *** values)
{
  bool hasRows;
  nsresult rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  nsTArray<nsCString> valArray;
  while (hasRows)
  {
    uint32_t length;
    valArray.AppendElement(
      nsDependentCString(statement->AsSharedUTF8String(resultIndex, &length)));

    rv = statement->ExecuteStep(&hasRows);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  *count = valArray.Length();
  char **ret = static_cast<char **>(moz_xmalloc(*count * sizeof(char*)));
  if (!ret) return NS_ERROR_OUT_OF_MEMORY;

  for (uint32_t i = 0; i <  *count; i++) {
    ret[i] = NS_strdup(valArray[i].get());
    if (!ret[i]) {
      NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, ret);
      return NS_ERROR_OUT_OF_MEMORY;
    }
  }

  *values = ret;

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::CreateApplicationCache(const nsACString &group,
                                             nsIApplicationCache **out)
{
  *out = nullptr;

  nsCString clientID;
  // Some characters are special in the clientID.  Escape the groupID
  // before putting it in to the client key.
  if (!NS_Escape(nsCString(group), clientID, url_Path)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  PRTime now = PR_Now();

  // Include the timestamp to guarantee uniqueness across runs, and
  // the gNextTemporaryClientID for uniqueness within a second.
  clientID.Append(nsPrintfCString("|%016lld|%d",
                                  now / PR_USEC_PER_SEC,
                                  gNextTemporaryClientID++));

  nsCOMPtr<nsIApplicationCache> cache = new nsApplicationCache(this,
                                                               group,
                                                               clientID);
  if (!cache)
    return NS_ERROR_OUT_OF_MEMORY;

  nsCOMPtr<nsIWeakReference> weak = do_GetWeakReference(cache);
  if (!weak)
    return NS_ERROR_OUT_OF_MEMORY;

  MutexAutoLock lock(mLock);
  mCaches.Put(clientID, weak);

  cache.swap(*out);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::GetApplicationCache(const nsACString &clientID,
                                          nsIApplicationCache **out)
{
  MutexAutoLock lock(mLock);
  return GetApplicationCache_Unlocked(clientID, out);
}

nsresult
nsOfflineCacheDevice::GetApplicationCache_Unlocked(const nsACString &clientID,
                                                   nsIApplicationCache **out)
{
  *out = nullptr;

  nsCOMPtr<nsIApplicationCache> cache;

  nsWeakPtr weak;
  if (mCaches.Get(clientID, getter_AddRefs(weak)))
    cache = do_QueryReferent(weak);

  if (!cache)
  {
    nsCString group;
    nsresult rv = GetGroupForCache(clientID, group);
    NS_ENSURE_SUCCESS(rv, rv);

    if (group.IsEmpty()) {
      return NS_OK;
    }

    cache = new nsApplicationCache(this, group, clientID);
    weak = do_GetWeakReference(cache);
    if (!weak)
      return NS_ERROR_OUT_OF_MEMORY;

    mCaches.Put(clientID, weak);
  }

  cache.swap(*out);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::GetActiveCache(const nsACString &group,
                                     nsIApplicationCache **out)
{
  *out = nullptr;

  MutexAutoLock lock(mLock);

  nsCString *clientID;
  if (mActiveCachesByGroup.Get(group, &clientID))
    return GetApplicationCache_Unlocked(*clientID, out);

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::DeactivateGroup(const nsACString &group)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  nsCString *active = nullptr;

  AutoResetStatement statement(mStatement_DeactivateGroup);
  nsresult rv = statement->BindUTF8StringByIndex(0, group);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->Execute();
  NS_ENSURE_SUCCESS(rv, rv);

  MutexAutoLock lock(mLock);

  if (mActiveCachesByGroup.Get(group, &active))
  {
    mActiveCaches.RemoveEntry(*active);
    mActiveCachesByGroup.Remove(group);
    active = nullptr;
  }

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::Evict(nsILoadContextInfo *aInfo)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  NS_ENSURE_ARG(aInfo);

  nsresult rv;

  mozilla::OriginAttributes const *oa = aInfo->OriginAttributesPtr();

  if (oa->mAppId == NECKO_NO_APP_ID && oa->mInIsolatedMozBrowser == false) {
    nsCOMPtr<nsICacheService> serv = do_GetService(kCacheServiceCID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    return nsCacheService::GlobalInstance()->EvictEntriesInternal(nsICache::STORE_OFFLINE);
  }

  nsAutoCString jaridsuffix;
  jaridsuffix.Append('%');

  nsAutoCString suffix;
  oa->CreateSuffix(suffix);
  jaridsuffix.Append('#');
  jaridsuffix.Append(suffix);

  AutoResetStatement statement(mStatement_EnumerateApps);
  rv = statement->BindUTF8StringByIndex(0, jaridsuffix);
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  while (hasRows) {
    nsAutoCString group;
    rv = statement->GetUTF8String(0, group);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCString clientID;
    rv = statement->GetUTF8String(1, clientID);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIRunnable> ev =
      new nsOfflineCacheDiscardCache(this, group, clientID);

    rv = nsCacheService::DispatchToCacheIOThread(ev);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->ExecuteStep(&hasRows);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

namespace { // anon

class OriginMatch final : public mozIStorageFunction
{
  ~OriginMatch() {}
  mozilla::OriginAttributesPattern const mPattern;

  NS_DECL_ISUPPORTS
  NS_DECL_MOZISTORAGEFUNCTION
  explicit OriginMatch(mozilla::OriginAttributesPattern const &aPattern)
    : mPattern(aPattern) {}
};

NS_IMPL_ISUPPORTS(OriginMatch, mozIStorageFunction)

NS_IMETHODIMP
OriginMatch::OnFunctionCall(mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult)
{
  nsresult rv;

  nsAutoCString groupId;
  rv = aFunctionArguments->GetUTF8String(0, groupId);
  NS_ENSURE_SUCCESS(rv, rv);

  int32_t hash = groupId.Find(NS_LITERAL_CSTRING("#"));
  if (hash == kNotFound) {
    // Just ignore...
    return NS_OK;
  }

  ++hash;

  nsDependentCSubstring suffix(groupId.BeginReading() + hash, groupId.Length() - hash);

  mozilla::NeckoOriginAttributes oa;
  bool ok = oa.PopulateFromSuffix(suffix);
  NS_ENSURE_TRUE(ok, NS_ERROR_UNEXPECTED);

  bool match = mPattern.Matches(oa);

  RefPtr<nsVariant> outVar(new nsVariant());
  rv = outVar->SetAsUint32(match ? 1 : 0);
  NS_ENSURE_SUCCESS(rv, rv);

  outVar.forget(aResult);
  return NS_OK;
}

} // anon

nsresult
nsOfflineCacheDevice::Evict(mozilla::OriginAttributesPattern const &aPattern)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  nsresult rv;

  nsCOMPtr<mozIStorageFunction> function1(new OriginMatch(aPattern));
  rv = mDB->CreateFunction(NS_LITERAL_CSTRING("ORIGIN_MATCH"), 1, function1);
  NS_ENSURE_SUCCESS(rv, rv);

  class AutoRemoveFunc {
  public:
    mozIStorageConnection* mDB;
    explicit AutoRemoveFunc(mozIStorageConnection* aDB) : mDB(aDB) {}
    ~AutoRemoveFunc() {
      mDB->RemoveFunction(NS_LITERAL_CSTRING("ORIGIN_MATCH"));
    }
  };
  AutoRemoveFunc autoRemove(mDB);

  nsCOMPtr<mozIStorageStatement> statement;
  rv = mDB->CreateStatement(
    NS_LITERAL_CSTRING("SELECT GroupID, ActiveClientID FROM moz_cache_groups WHERE ORIGIN_MATCH(GroupID);"),
    getter_AddRefs(statement));
  NS_ENSURE_SUCCESS(rv, rv);

  AutoResetStatement statementScope(statement);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  while (hasRows) {
    nsAutoCString group;
    rv = statement->GetUTF8String(0, group);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCString clientID;
    rv = statement->GetUTF8String(1, clientID);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIRunnable> ev =
      new nsOfflineCacheDiscardCache(this, group, clientID);

    rv = nsCacheService::DispatchToCacheIOThread(ev);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = statement->ExecuteStep(&hasRows);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

bool
nsOfflineCacheDevice::CanUseCache(nsIURI *keyURI,
                                  const nsACString &clientID,
                                  nsILoadContextInfo *loadContextInfo)
{
  {
    MutexAutoLock lock(mLock);
    if (!mActiveCaches.Contains(clientID))
      return false;
  }

  nsAutoCString groupID;
  nsresult rv = GetGroupForCache(clientID, groupID);
  NS_ENSURE_SUCCESS(rv, false);

  nsCOMPtr<nsIURI> groupURI;
  rv = NS_NewURI(getter_AddRefs(groupURI), groupID);
  if (NS_FAILED(rv)) {
    return false;
  }

  // When we are choosing an initial cache to load the top
  // level document from, the URL of that document must have
  // the same origin as the manifest, according to the spec.
  // The following check is here because explicit, fallback
  // and dynamic entries might have origin different from the
  // manifest origin.
  if (!NS_SecurityCompareURIs(keyURI, groupURI,
                              GetStrictFileOriginPolicy())) {
    return false;
  }

  // Check the groupID we found is equal to groupID based
  // on the load context demanding load from app cache.
  // This is check of extended origin.

  nsAutoCString originSuffix;
  loadContextInfo->OriginAttributesPtr()->CreateSuffix(originSuffix);

  nsAutoCString demandedGroupID;
  rv = BuildApplicationCacheGroupID(groupURI, originSuffix, demandedGroupID);
  NS_ENSURE_SUCCESS(rv, false);

  if (groupID != demandedGroupID) {
    return false;
  }

  return true;
}


nsresult
nsOfflineCacheDevice::ChooseApplicationCache(const nsACString &key,
                                             nsILoadContextInfo *loadContextInfo,
                                             nsIApplicationCache **out)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  NS_ENSURE_ARG(loadContextInfo);

  nsresult rv;

  *out = nullptr;

  nsCOMPtr<nsIURI> keyURI;
  rv = NS_NewURI(getter_AddRefs(keyURI), key);
  NS_ENSURE_SUCCESS(rv, rv);

  // First try to find a matching cache entry.
  AutoResetStatement statement(mStatement_FindClient);
  rv = statement->BindUTF8StringByIndex(0, key);
  NS_ENSURE_SUCCESS(rv, rv);

  bool hasRows;
  rv = statement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  while (hasRows) {
    int32_t itemType;
    rv = statement->GetInt32(1, &itemType);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!(itemType & nsIApplicationCache::ITEM_FOREIGN)) {
      nsAutoCString clientID;
      rv = statement->GetUTF8String(0, clientID);
      NS_ENSURE_SUCCESS(rv, rv);

      if (CanUseCache(keyURI, clientID, loadContextInfo)) {
        return GetApplicationCache(clientID, out);
      }
    }

    rv = statement->ExecuteStep(&hasRows);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // OK, we didn't find an exact match.  Search for a client with a
  // matching namespace.

  AutoResetStatement nsstatement(mStatement_FindClientByNamespace);

  rv = nsstatement->BindUTF8StringByIndex(0, key);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = nsstatement->ExecuteStep(&hasRows);
  NS_ENSURE_SUCCESS(rv, rv);

  while (hasRows)
  {
    int32_t itemType;
    rv = nsstatement->GetInt32(1, &itemType);
    NS_ENSURE_SUCCESS(rv, rv);

    // Don't associate with a cache based solely on a whitelist entry
    if (!(itemType & nsIApplicationCacheNamespace::NAMESPACE_BYPASS)) {
      nsAutoCString clientID;
      rv = nsstatement->GetUTF8String(0, clientID);
      NS_ENSURE_SUCCESS(rv, rv);

      if (CanUseCache(keyURI, clientID, loadContextInfo)) {
        return GetApplicationCache(clientID, out);
      }
    }

    rv = nsstatement->ExecuteStep(&hasRows);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

nsresult
nsOfflineCacheDevice::CacheOpportunistically(nsIApplicationCache* cache,
                                             const nsACString &key)
{
  NS_ENSURE_ARG_POINTER(cache);

  nsresult rv;

  nsAutoCString clientID;
  rv = cache->GetClientID(clientID);
  NS_ENSURE_SUCCESS(rv, rv);

  return CacheOpportunistically(clientID, key);
}

nsresult
nsOfflineCacheDevice::ActivateCache(const nsCSubstring &group,
                                    const nsCSubstring &clientID)
{
  NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED);

  AutoResetStatement statement(mStatement_ActivateClient);
  nsresult rv = statement->BindUTF8StringByIndex(0, group);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindUTF8StringByIndex(1, clientID);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = statement->BindInt32ByIndex(2, SecondsFromPRTime(PR_Now()));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = statement->Execute();
  NS_ENSURE_SUCCESS(rv, rv);

  MutexAutoLock lock(mLock);

  nsCString *active;
  if (mActiveCachesByGroup.Get(group, &active))
  {
    mActiveCaches.RemoveEntry(*active);
    mActiveCachesByGroup.Remove(group);
    active = nullptr;
  }

  if (!clientID.IsEmpty())
  {
    mActiveCaches.PutEntry(clientID);
    mActiveCachesByGroup.Put(group, new nsCString(clientID));
  }

  return NS_OK;
}

bool
nsOfflineCacheDevice::IsActiveCache(const nsCSubstring &group,
                                    const nsCSubstring &clientID)
{
  nsCString *active = nullptr;
  MutexAutoLock lock(mLock);
  return mActiveCachesByGroup.Get(group, &active) && *active == clientID;
}

/**
 * Preference accessors
 */

void
nsOfflineCacheDevice::SetCacheParentDirectory(nsIFile *parentDir)
{
  if (Initialized())
  {
    NS_ERROR("cannot switch cache directory once initialized");
    return;
  }

  if (!parentDir)
  {
    mCacheDirectory = nullptr;
    return;
  }

  // ensure parent directory exists
  nsresult rv = EnsureDir(parentDir);
  if (NS_FAILED(rv))
  {
    NS_WARNING("unable to create parent directory");
    return;
  }

  mBaseDirectory = parentDir;

  // cache dir may not exist, but that's ok
  nsCOMPtr<nsIFile> dir;
  rv = parentDir->Clone(getter_AddRefs(dir));
  if (NS_FAILED(rv))
    return;
  rv = dir->AppendNative(NS_LITERAL_CSTRING("OfflineCache"));
  if (NS_FAILED(rv))
    return;

  mCacheDirectory = do_QueryInterface(dir);
}

void
nsOfflineCacheDevice::SetCapacity(uint32_t capacity)
{
  mCacheCapacity = capacity * 1024;
}

bool
nsOfflineCacheDevice::AutoShutdown(nsIApplicationCache * aAppCache)
{
  if (!mAutoShutdown)
    return false;

  mAutoShutdown = false;

  Shutdown();

  nsCOMPtr<nsICacheService> serv = do_GetService(kCacheServiceCID);
  RefPtr<nsCacheService> cacheService = nsCacheService::GlobalInstance();
  cacheService->RemoveCustomOfflineDevice(this);

  nsAutoCString clientID;
  aAppCache->GetClientID(clientID);

  MutexAutoLock lock(mLock);
  mCaches.Remove(clientID);

  return true;
}