DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (5b81998bb7ab)

VCS Links

Line Code
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 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */


#ifdef MOZ_LOGGING
// this next define has to appear before the include of prlog.h
#define FORCE_PR_LOG // Allow logging in the release build
#endif

#include "mozilla/net/CookieServiceChild.h"
#include "mozilla/net/NeckoCommon.h"

#include "nsCookieService.h"
#include "nsIServiceManager.h"

#include "nsIIOService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsICookiePermission.h"
#include "nsIURI.h"
#include "nsIURL.h"
#include "nsIChannel.h"
#include "nsIFile.h"
#include "nsIObserverService.h"
#include "nsILineInputStream.h"
#include "nsIEffectiveTLDService.h"
#include "nsIIDNService.h"
#include "mozIThirdPartyUtil.h"

#include "nsTArray.h"
#include "nsCOMArray.h"
#include "nsIMutableArray.h"
#include "nsArrayEnumerator.h"
#include "nsEnumeratorUtils.h"
#include "nsAutoPtr.h"
#include "nsReadableUtils.h"
#include "nsCRT.h"
#include "prtime.h"
#include "prprf.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsIPrivateBrowsingService.h"
#include "nsNetCID.h"
#include "mozilla/storage.h"
#include "mozilla/FunctionTimer.h"
#include "mozilla/Util.h" // for DebugOnly
#include "mozilla/Attributes.h"

using namespace mozilla;
using namespace mozilla::net;

/******************************************************************************
 * nsCookieService impl:
 * useful types & constants
 ******************************************************************************/

static nsCookieService *gCookieService;

// XXX_hack. See bug 178993.
// This is a hack to hide HttpOnly cookies from older browsers
static const char kHttpOnlyPrefix[] = "#HttpOnly_";

#define COOKIES_FILE "cookies.sqlite"
#define COOKIES_SCHEMA_VERSION 4

static const int64_t kCookieStaleThreshold = 60 * PR_USEC_PER_SEC; // 1 minute in microseconds
static const int64_t kCookiePurgeAge =
  int64_t(30 * 24 * 60 * 60) * PR_USEC_PER_SEC; // 30 days in microseconds

static const char kOldCookieFileName[] = "cookies.txt";

#undef  LIMIT
#define LIMIT(x, low, high, default) ((x) >= (low) && (x) <= (high) ? (x) : (default))

#undef  ADD_TEN_PERCENT
#define ADD_TEN_PERCENT(i) ((i) + (i)/10)

// default limits for the cookie list. these can be tuned by the
// network.cookie.maxNumber and network.cookie.maxPerHost prefs respectively.
static const uint32_t kMaxNumberOfCookies = 3000;
static const uint32_t kMaxCookiesPerHost  = 150;
static const uint32_t kMaxBytesPerCookie  = 4096;
static const uint32_t kMaxBytesPerPath    = 1024;

// behavior pref constants
static const uint32_t BEHAVIOR_ACCEPT        = 0;
static const uint32_t BEHAVIOR_REJECTFOREIGN = 1;
static const uint32_t BEHAVIOR_REJECT        = 2;

// pref string constants
static const char kPrefCookieBehavior[]     = "network.cookie.cookieBehavior";
static const char kPrefMaxNumberOfCookies[] = "network.cookie.maxNumber";
static const char kPrefMaxCookiesPerHost[]  = "network.cookie.maxPerHost";
static const char kPrefCookiePurgeAge[]     = "network.cookie.purgeAge";
static const char kPrefThirdPartySession[]  = "network.cookie.thirdparty.sessionOnly";

static void
bindCookieParameters(mozIStorageBindingParamsArray *aParamsArray,
                     const nsCString &aBaseDomain,
                     const nsCookie *aCookie);

// struct for temporarily storing cookie attributes during header parsing
struct nsCookieAttributes
{
  nsCAutoString name;
  nsCAutoString value;
  nsCAutoString host;
  nsCAutoString path;
  nsCAutoString expires;
  nsCAutoString maxage;
  int64_t expiryTime;
  bool isSession;
  bool isSecure;
  bool isHttpOnly;
};

// stores the nsCookieEntry entryclass and an index into the cookie array
// within that entryclass, for purposes of storing an iteration state that
// points to a certain cookie.
struct nsListIter
{
  // default (non-initializing) constructor.
  nsListIter()
  {
  }

  // explicit constructor to a given iterator state with entryclass 'aEntry'
  // and index 'aIndex'.
  explicit
  nsListIter(nsCookieEntry *aEntry, nsCookieEntry::IndexType aIndex)
   : entry(aEntry)
   , index(aIndex)
  {
  }

  // get the nsCookie * the iterator currently points to.
  nsCookie * Cookie() const
  {
    return entry->GetCookies()[index];
  }

  nsCookieEntry            *entry;
  nsCookieEntry::IndexType  index;
};

/******************************************************************************
 * Cookie logging handlers
 * used for logging in nsCookieService
 ******************************************************************************/

// logging handlers
#ifdef MOZ_LOGGING
// in order to do logging, the following environment variables need to be set:
//
//    set NSPR_LOG_MODULES=cookie:3 -- shows rejected cookies
//    set NSPR_LOG_MODULES=cookie:4 -- shows accepted and rejected cookies
//    set NSPR_LOG_FILE=cookie.log
//
#include "prlog.h"
#endif

// define logging macros for convenience
#define SET_COOKIE true
#define GET_COOKIE false

#ifdef PR_LOGGING
static PRLogModuleInfo *sCookieLog = PR_NewLogModule("cookie");

#define COOKIE_LOGFAILURE(a, b, c, d)    LogFailure(a, b, c, d)
#define COOKIE_LOGSUCCESS(a, b, c, d, e) LogSuccess(a, b, c, d, e)

#define COOKIE_LOGEVICTED(a, details)          \
  PR_BEGIN_MACRO                               \
    if (PR_LOG_TEST(sCookieLog, PR_LOG_DEBUG)) \
      LogEvicted(a, details);                  \
  PR_END_MACRO

#define COOKIE_LOGSTRING(lvl, fmt)   \
  PR_BEGIN_MACRO                     \
    PR_LOG(sCookieLog, lvl, fmt);    \
    PR_LOG(sCookieLog, lvl, ("\n")); \
  PR_END_MACRO

static void
LogFailure(bool aSetCookie, nsIURI *aHostURI, const char *aCookieString, const char *aReason)
{
  // if logging isn't enabled, return now to save cycles
  if (!PR_LOG_TEST(sCookieLog, PR_LOG_WARNING))
    return;

  nsCAutoString spec;
  if (aHostURI)
    aHostURI->GetAsciiSpec(spec);

  PR_LOG(sCookieLog, PR_LOG_WARNING,
    ("===== %s =====\n", aSetCookie ? "COOKIE NOT ACCEPTED" : "COOKIE NOT SENT"));
  PR_LOG(sCookieLog, PR_LOG_WARNING,("request URL: %s\n", spec.get()));
  if (aSetCookie)
    PR_LOG(sCookieLog, PR_LOG_WARNING,("cookie string: %s\n", aCookieString));

  PRExplodedTime explodedTime;
  PR_ExplodeTime(PR_Now(), PR_GMTParameters, &explodedTime);
  char timeString[40];
  PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);

  PR_LOG(sCookieLog, PR_LOG_WARNING,("current time: %s", timeString));
  PR_LOG(sCookieLog, PR_LOG_WARNING,("rejected because %s\n", aReason));
  PR_LOG(sCookieLog, PR_LOG_WARNING,("\n"));
}

static void
LogCookie(nsCookie *aCookie)
{
  PRExplodedTime explodedTime;
  PR_ExplodeTime(PR_Now(), PR_GMTParameters, &explodedTime);
  char timeString[40];
  PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);

  PR_LOG(sCookieLog, PR_LOG_DEBUG,("current time: %s", timeString));

  if (aCookie) {
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("----------------\n"));
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("name: %s\n", aCookie->Name().get()));
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("value: %s\n", aCookie->Value().get()));
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("%s: %s\n", aCookie->IsDomain() ? "domain" : "host", aCookie->Host().get()));
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("path: %s\n", aCookie->Path().get()));

    PR_ExplodeTime(aCookie->Expiry() * int64_t(PR_USEC_PER_SEC),
                   PR_GMTParameters, &explodedTime);
    PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);
    PR_LOG(sCookieLog, PR_LOG_DEBUG,
      ("expires: %s%s", timeString, aCookie->IsSession() ? " (at end of session)" : ""));

    PR_ExplodeTime(aCookie->CreationTime(), PR_GMTParameters, &explodedTime);
    PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("created: %s", timeString));

    PR_LOG(sCookieLog, PR_LOG_DEBUG,("is secure: %s\n", aCookie->IsSecure() ? "true" : "false"));
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("is httpOnly: %s\n", aCookie->IsHttpOnly() ? "true" : "false"));
  }
}

static void
LogSuccess(bool aSetCookie, nsIURI *aHostURI, const char *aCookieString, nsCookie *aCookie, bool aReplacing)
{
  // if logging isn't enabled, return now to save cycles
  if (!PR_LOG_TEST(sCookieLog, PR_LOG_DEBUG)) {
    return;
  }

  nsCAutoString spec;
  if (aHostURI)
    aHostURI->GetAsciiSpec(spec);

  PR_LOG(sCookieLog, PR_LOG_DEBUG,
    ("===== %s =====\n", aSetCookie ? "COOKIE ACCEPTED" : "COOKIE SENT"));
  PR_LOG(sCookieLog, PR_LOG_DEBUG,("request URL: %s\n", spec.get()));
  PR_LOG(sCookieLog, PR_LOG_DEBUG,("cookie string: %s\n", aCookieString));
  if (aSetCookie)
    PR_LOG(sCookieLog, PR_LOG_DEBUG,("replaces existing cookie: %s\n", aReplacing ? "true" : "false"));

  LogCookie(aCookie);

  PR_LOG(sCookieLog, PR_LOG_DEBUG,("\n"));
}

static void
LogEvicted(nsCookie *aCookie, const char* details)
{
  PR_LOG(sCookieLog, PR_LOG_DEBUG,("===== COOKIE EVICTED =====\n"));
  PR_LOG(sCookieLog, PR_LOG_DEBUG,("%s\n", details));

  LogCookie(aCookie);

  PR_LOG(sCookieLog, PR_LOG_DEBUG,("\n"));
}

// inline wrappers to make passing in nsAFlatCStrings easier
static inline void
LogFailure(bool aSetCookie, nsIURI *aHostURI, const nsAFlatCString &aCookieString, const char *aReason)
{
  LogFailure(aSetCookie, aHostURI, aCookieString.get(), aReason);
}

static inline void
LogSuccess(bool aSetCookie, nsIURI *aHostURI, const nsAFlatCString &aCookieString, nsCookie *aCookie, bool aReplacing)
{
  LogSuccess(aSetCookie, aHostURI, aCookieString.get(), aCookie, aReplacing);
}

#else
#define COOKIE_LOGFAILURE(a, b, c, d)    PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#define COOKIE_LOGSUCCESS(a, b, c, d, e) PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#define COOKIE_LOGEVICTED(a, b)          PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#define COOKIE_LOGSTRING(a, b)           PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#endif

#ifdef DEBUG
#define NS_ASSERT_SUCCESS(res)                                               \
  PR_BEGIN_MACRO                                                             \
  nsresult __rv = res; /* Do not evaluate |res| more than once! */           \
  if (NS_FAILED(__rv)) {                                                     \
    char *msg = PR_smprintf("NS_ASSERT_SUCCESS(%s) failed with result 0x%X", \
                            #res, __rv);                                     \
    NS_ASSERTION(NS_SUCCEEDED(__rv), msg);                                   \
    PR_smprintf_free(msg);                                                   \
  }                                                                          \
  PR_END_MACRO
#else
#define NS_ASSERT_SUCCESS(res) PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#endif

/******************************************************************************
 * DBListenerErrorHandler impl:
 * Parent class for our async storage listeners that handles the logging of
 * errors.
 ******************************************************************************/
class DBListenerErrorHandler : public mozIStorageStatementCallback
{
protected:
  DBListenerErrorHandler(DBState* dbState) : mDBState(dbState) { }
  nsRefPtr<DBState> mDBState;
  virtual const char *GetOpType() = 0;

public:
  NS_IMETHOD HandleError(mozIStorageError* aError)
  {
    int32_t result = -1;
    aError->GetResult(&result);

#ifdef PR_LOGGING
    nsCAutoString message;
    aError->GetMessage(message);
    COOKIE_LOGSTRING(PR_LOG_WARNING,
      ("DBListenerErrorHandler::HandleError(): Error %d occurred while "
       "performing operation '%s' with message '%s'; rebuilding database.",
       result, GetOpType(), message.get()));
#endif

    // Rebuild the database.
    gCookieService->HandleCorruptDB(mDBState);

    return NS_OK;
  }
};

/******************************************************************************
 * InsertCookieDBListener impl:
 * mozIStorageStatementCallback used to track asynchronous insertion operations.
 ******************************************************************************/
class InsertCookieDBListener MOZ_FINAL : public DBListenerErrorHandler
{
protected:
  virtual const char *GetOpType() { return "INSERT"; }

public:
  NS_DECL_ISUPPORTS

  InsertCookieDBListener(DBState* dbState) : DBListenerErrorHandler(dbState) { }
  NS_IMETHOD HandleResult(mozIStorageResultSet*)
  {
    NS_NOTREACHED("Unexpected call to InsertCookieDBListener::HandleResult");
    return NS_OK;
  }
  NS_IMETHOD HandleCompletion(uint16_t aReason)
  {
    // If we were rebuilding the db and we succeeded, make our corruptFlag say
    // so.
    if (mDBState->corruptFlag == DBState::REBUILDING &&
        aReason == mozIStorageStatementCallback::REASON_FINISHED) {
      COOKIE_LOGSTRING(PR_LOG_DEBUG,
        ("InsertCookieDBListener::HandleCompletion(): rebuild complete"));
      mDBState->corruptFlag = DBState::OK;
    }
    return NS_OK;
  }
};

NS_IMPL_ISUPPORTS1(InsertCookieDBListener, mozIStorageStatementCallback)

/******************************************************************************
 * UpdateCookieDBListener impl:
 * mozIStorageStatementCallback used to track asynchronous update operations.
 ******************************************************************************/
class UpdateCookieDBListener MOZ_FINAL : public DBListenerErrorHandler
{
protected:
  virtual const char *GetOpType() { return "UPDATE"; }

public:
  NS_DECL_ISUPPORTS

  UpdateCookieDBListener(DBState* dbState) : DBListenerErrorHandler(dbState) { }
  NS_IMETHOD HandleResult(mozIStorageResultSet*)
  {
    NS_NOTREACHED("Unexpected call to UpdateCookieDBListener::HandleResult");
    return NS_OK;
  }
  NS_IMETHOD HandleCompletion(uint16_t aReason)
  {
    return NS_OK;
  }
};

NS_IMPL_ISUPPORTS1(UpdateCookieDBListener, mozIStorageStatementCallback)

/******************************************************************************
 * RemoveCookieDBListener impl:
 * mozIStorageStatementCallback used to track asynchronous removal operations.
 ******************************************************************************/
class RemoveCookieDBListener MOZ_FINAL : public DBListenerErrorHandler
{
protected:
  virtual const char *GetOpType() { return "REMOVE"; }

public:
  NS_DECL_ISUPPORTS

  RemoveCookieDBListener(DBState* dbState) : DBListenerErrorHandler(dbState) { }
  NS_IMETHOD HandleResult(mozIStorageResultSet*)
  {
    NS_NOTREACHED("Unexpected call to RemoveCookieDBListener::HandleResult");
    return NS_OK;
  }
  NS_IMETHOD HandleCompletion(uint16_t aReason)
  {
    return NS_OK;
  }
};

NS_IMPL_ISUPPORTS1(RemoveCookieDBListener, mozIStorageStatementCallback)

/******************************************************************************
 * ReadCookieDBListener impl:
 * mozIStorageStatementCallback used to track asynchronous removal operations.
 ******************************************************************************/
class ReadCookieDBListener MOZ_FINAL : public DBListenerErrorHandler
{
protected:
  virtual const char *GetOpType() { return "READ"; }
  bool mCanceled;

public:
  NS_DECL_ISUPPORTS

  ReadCookieDBListener(DBState* dbState)
    : DBListenerErrorHandler(dbState)
    , mCanceled(false)
  {
  }

  void Cancel() { mCanceled = true; }

  NS_IMETHOD HandleResult(mozIStorageResultSet *aResult)
  {
    nsresult rv;
    nsCOMPtr<mozIStorageRow> row;

    while (1) {
      rv = aResult->GetNextRow(getter_AddRefs(row));
      NS_ASSERT_SUCCESS(rv);

      if (!row)
        break;

      CookieDomainTuple *tuple = mDBState->hostArray.AppendElement();
      row->GetUTF8String(9, tuple->baseDomain);
      tuple->cookie = gCookieService->GetCookieFromRow(row);
    }

    return NS_OK;
  }
  NS_IMETHOD HandleCompletion(uint16_t aReason)
  {
    // Process the completion of the read operation. If we have been canceled,
    // we cannot assume that the cookieservice still has an open connection
    // or that it even refers to the same database, so we must return early.
    // Conversely, the cookieservice guarantees that if we have not been
    // canceled, the database connection is still alive and we can safely
    // operate on it.

    if (mCanceled) {
      // We may receive a REASON_FINISHED after being canceled;
      // tweak the reason accordingly.
      aReason = mozIStorageStatementCallback::REASON_CANCELED;
    }

    switch (aReason) {
    case mozIStorageStatementCallback::REASON_FINISHED:
      gCookieService->AsyncReadComplete();
      break;
    case mozIStorageStatementCallback::REASON_CANCELED:
      // Nothing more to do here. The partially read data has already been
      // thrown away.
      COOKIE_LOGSTRING(PR_LOG_DEBUG, ("Read canceled"));
      break;
    case mozIStorageStatementCallback::REASON_ERROR:
      // Nothing more to do here. DBListenerErrorHandler::HandleError()
      // can handle it.
      COOKIE_LOGSTRING(PR_LOG_DEBUG, ("Read error"));
      break;
    default:
      NS_NOTREACHED("invalid reason");
    }
    return NS_OK;
  }
};

NS_IMPL_ISUPPORTS1(ReadCookieDBListener, mozIStorageStatementCallback)

/******************************************************************************
 * CloseCookieDBListener imp:
 * Static mozIStorageCompletionCallback used to notify when the database is
 * successfully closed.
 ******************************************************************************/
class CloseCookieDBListener MOZ_FINAL :  public mozIStorageCompletionCallback
{
public:
  CloseCookieDBListener(DBState* dbState) : mDBState(dbState) { }
  nsRefPtr<DBState> mDBState;
  NS_DECL_ISUPPORTS

  NS_IMETHOD Complete()
  {
    gCookieService->HandleDBClosed(mDBState);
    return NS_OK;
  }
};

NS_IMPL_ISUPPORTS1(CloseCookieDBListener, mozIStorageCompletionCallback)

/******************************************************************************
 * nsCookieService impl:
 * singleton instance ctor/dtor methods
 ******************************************************************************/

nsICookieService*
nsCookieService::GetXPCOMSingleton()
{
  if (IsNeckoChild())
    return CookieServiceChild::GetSingleton();

  return GetSingleton();
}

nsCookieService*
nsCookieService::GetSingleton()
{
  NS_ASSERTION(!IsNeckoChild(), "not a parent process");

  if (gCookieService) {
    NS_ADDREF(gCookieService);
    return gCookieService;
  }

  // Create a new singleton nsCookieService.
  // We AddRef only once since XPCOM has rules about the ordering of module
  // teardowns - by the time our module destructor is called, it's too late to
  // Release our members (e.g. nsIObserverService and nsIPrefBranch), since GC
  // cycles have already been completed and would result in serious leaks.
  // See bug 209571.
  gCookieService = new nsCookieService();
  if (gCookieService) {
    NS_ADDREF(gCookieService);
    if (NS_FAILED(gCookieService->Init())) {
      NS_RELEASE(gCookieService);
    }
  }

  return gCookieService;
}

/******************************************************************************
 * nsCookieService impl:
 * public methods
 ******************************************************************************/

NS_IMPL_ISUPPORTS5(nsCookieService,
                   nsICookieService,
                   nsICookieManager,
                   nsICookieManager2,
                   nsIObserver,
                   nsISupportsWeakReference)

nsCookieService::nsCookieService()
 : mDBState(NULL)
 , mCookieBehavior(BEHAVIOR_ACCEPT)
 , mThirdPartySession(false)
 , mMaxNumberOfCookies(kMaxNumberOfCookies)
 , mMaxCookiesPerHost(kMaxCookiesPerHost)
 , mCookiePurgeAge(kCookiePurgeAge)
{
}

nsresult
nsCookieService::Init()
{
  NS_TIME_FUNCTION;

  nsresult rv;
  mTLDService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  mIDNService = do_GetService(NS_IDNSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // init our pref and observer
  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
  if (prefBranch) {
    prefBranch->AddObserver(kPrefCookieBehavior,     this, true);
    prefBranch->AddObserver(kPrefMaxNumberOfCookies, this, true);
    prefBranch->AddObserver(kPrefMaxCookiesPerHost,  this, true);
    prefBranch->AddObserver(kPrefCookiePurgeAge,     this, true);
    prefBranch->AddObserver(kPrefThirdPartySession,  this, true);
    PrefChanged(prefBranch);
  }

  mStorageService = do_GetService("@mozilla.org/storage/service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Init our default, and possibly private DBStates.
  InitDBStates();

  mObserverService = mozilla::services::GetObserverService();
  NS_ENSURE_STATE(mObserverService);
  mObserverService->AddObserver(this, "profile-before-change", true);
  mObserverService->AddObserver(this, "profile-do-change", true);
  mObserverService->AddObserver(this, NS_PRIVATE_BROWSING_SWITCH_TOPIC, true);

  mPermissionService = do_GetService(NS_COOKIEPERMISSION_CONTRACTID);
  if (!mPermissionService) {
    NS_WARNING("nsICookiePermission implementation not available - some features won't work!");
    COOKIE_LOGSTRING(PR_LOG_WARNING, ("Init(): nsICookiePermission implementation not available"));
  }

  return NS_OK;
}

void
nsCookieService::InitDBStates()
{
  NS_ASSERTION(!mDBState, "already have a DBState");
  NS_ASSERTION(!mDefaultDBState, "already have a default DBState");
  NS_ASSERTION(!mPrivateDBState, "already have a private DBState");

  // Create a new default DBState and set our current one.
  mDefaultDBState = new DBState();
  mDBState = mDefaultDBState;

  // If we're in private browsing mode, create a private DBState.
  nsCOMPtr<nsIPrivateBrowsingService> pbs =
    do_GetService(NS_PRIVATE_BROWSING_SERVICE_CONTRACTID);
  if (pbs) {
    bool inPrivateBrowsing = false;
    pbs->GetPrivateBrowsingEnabled(&inPrivateBrowsing);
    if (inPrivateBrowsing) {
      mPrivateDBState = new DBState();
      mDBState = mPrivateDBState;
    }
  }

  // Get our cookie file.
  nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
    getter_AddRefs(mDefaultDBState->cookieFile));
  if (NS_FAILED(rv)) {
    // We've already set up our DBStates appropriately; nothing more to do.
    COOKIE_LOGSTRING(PR_LOG_WARNING,
      ("InitDBStates(): couldn't get cookie file"));
    return;
  }
  mDefaultDBState->cookieFile->AppendNative(NS_LITERAL_CSTRING(COOKIES_FILE));

  // Attempt to open and read the database. If TryInitDB() returns RESULT_RETRY,
  // do so.
  OpenDBResult result = TryInitDB(false);
  if (result == RESULT_RETRY) {
    // Database may be corrupt. Synchronously close the connection, clean up the
    // default DBState, and try again.
    COOKIE_LOGSTRING(PR_LOG_WARNING, ("InitDBStates(): retrying TryInitDB()"));

    CloseDefaultDBConnection();
    result = TryInitDB(true);
    if (result == RESULT_RETRY) {
      // We're done. Change the code to failure so we clean up below.
      result = RESULT_FAILURE;
    }
  }

  if (result == RESULT_FAILURE) {
    COOKIE_LOGSTRING(PR_LOG_WARNING,
      ("InitDBStates(): TryInitDB() failed, closing connection"));

    // Connection failure is unrecoverable. Clean up our connection. We can run
    // fine without persistent storage -- e.g. if there's no profile.
    CloseDefaultDBConnection();
  }
}

/* Attempt to open and read the database. If 'aRecreateDB' is true, try to
 * move the existing database file out of the way and create a new one.
 *
 * @returns RESULT_OK if opening or creating the database succeeded;
 *          RESULT_RETRY if the database cannot be opened, is corrupt, or some
 *          other failure occurred that might be resolved by recreating the
 *          database; or RESULT_FAILED if there was an unrecoverable error and
 *          we must run without a database.
 *
 * If RESULT_RETRY or RESULT_FAILED is returned, the caller should perform
 * cleanup of the default DBState.
 */
OpenDBResult
nsCookieService::TryInitDB(bool aRecreateDB)
{
  NS_ASSERTION(!mDefaultDBState->dbConn, "nonnull dbConn");
  NS_ASSERTION(!mDefaultDBState->stmtInsert, "nonnull stmtInsert");
  NS_ASSERTION(!mDefaultDBState->insertListener, "nonnull insertListener");
  NS_ASSERTION(!mDefaultDBState->syncConn, "nonnull syncConn");

  // Ditch an existing db, if we've been told to (i.e. it's corrupt). We don't
  // want to delete it outright, since it may be useful for debugging purposes,
  // so we move it out of the way.
  nsresult rv;
  if (aRecreateDB) {
    nsCOMPtr<nsIFile> backupFile;
    mDefaultDBState->cookieFile->Clone(getter_AddRefs(backupFile));
    rv = backupFile->MoveToNative(NULL,
      NS_LITERAL_CSTRING(COOKIES_FILE ".bak"));
    NS_ENSURE_SUCCESS(rv, RESULT_FAILURE);
  }

  // open a connection to the cookie database, and only cache our connection
  // and statements upon success. The connection is opened unshared to eliminate
  // cache contention between the main and background threads.
  rv = mStorageService->OpenUnsharedDatabase(mDefaultDBState->cookieFile,
    getter_AddRefs(mDefaultDBState->dbConn));
  NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  // Set up our listeners.
  mDefaultDBState->insertListener = new InsertCookieDBListener(mDefaultDBState);
  mDefaultDBState->updateListener = new UpdateCookieDBListener(mDefaultDBState);
  mDefaultDBState->removeListener = new RemoveCookieDBListener(mDefaultDBState);
  mDefaultDBState->closeListener = new CloseCookieDBListener(mDefaultDBState);

  // Grow cookie db in 512KB increments
  mDefaultDBState->dbConn->SetGrowthIncrement(512 * 1024, EmptyCString());

  bool tableExists = false;
  mDefaultDBState->dbConn->TableExists(NS_LITERAL_CSTRING("moz_cookies"),
    &tableExists);
  if (!tableExists) {
    rv = CreateTable();
    NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  } else {
    // table already exists; check the schema version before reading
    int32_t dbSchemaVersion;
    rv = mDefaultDBState->dbConn->GetSchemaVersion(&dbSchemaVersion);
    NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

    // Start a transaction for the whole migration block.
    mozStorageTransaction transaction(mDefaultDBState->dbConn, true);

    switch (dbSchemaVersion) {
    // Upgrading.
    // Every time you increment the database schema, you need to implement
    // the upgrading code from the previous version to the new one. If migration
    // fails for any reason, it's a bug -- so we return RESULT_RETRY such that
    // the original database will be saved, in the hopes that we might one day
    // see it and fix it.
    case 1:
      {
        // Add the lastAccessed column to the table.
        rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "ALTER TABLE moz_cookies ADD lastAccessed INTEGER"));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
      }
      // Fall through to the next upgrade.

    case 2:
      {
        // Add the baseDomain column and index to the table.
        rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "ALTER TABLE moz_cookies ADD baseDomain TEXT"));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        // Compute the baseDomains for the table. This must be done eagerly
        // otherwise we won't be able to synchronously read in individual
        // domains on demand.
        nsCOMPtr<mozIStorageStatement> select;
        rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
          "SELECT id, host FROM moz_cookies"), getter_AddRefs(select));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        nsCOMPtr<mozIStorageStatement> update;
        rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
          "UPDATE moz_cookies SET baseDomain = :baseDomain WHERE id = :id"),
          getter_AddRefs(update));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        nsCString baseDomain, host;
        bool hasResult;
        while (1) {
          rv = select->ExecuteStep(&hasResult);
          NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

          if (!hasResult)
            break;

          int64_t id = select->AsInt64(0);
          select->GetUTF8String(1, host);

          rv = GetBaseDomainFromHost(host, baseDomain);
          NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

          mozStorageStatementScoper scoper(update);

          rv = update->BindUTF8StringByName(NS_LITERAL_CSTRING("baseDomain"),
                                            baseDomain);
          NS_ASSERT_SUCCESS(rv);
          rv = update->BindInt64ByName(NS_LITERAL_CSTRING("id"),
                                       id);
          NS_ASSERT_SUCCESS(rv);

          rv = update->ExecuteStep(&hasResult);
          NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
        }

        // Create an index on baseDomain.
        rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)"));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
      }
      // Fall through to the next upgrade.

    case 3:
      {
        // Add the creationTime column to the table, and create a unique index
        // on (name, host, path). Before we do this, we have to purge the table
        // of expired cookies such that we know that the (name, host, path)
        // index is truly unique -- otherwise we can't create the index. Note
        // that we can't just execute a statement to delete all rows where the
        // expiry column is in the past -- doing so would rely on the clock
        // (both now and when previous cookies were set) being monotonic.

        // Select the whole table, and order by the fields we're interested in.
        // This means we can simply do a linear traversal of the results and
        // check for duplicates as we go.
        nsCOMPtr<mozIStorageStatement> select;
        rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
          "SELECT id, name, host, path FROM moz_cookies "
            "ORDER BY name ASC, host ASC, path ASC, expiry ASC"),
          getter_AddRefs(select));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        nsCOMPtr<mozIStorageStatement> deleteExpired;
        rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
          "DELETE FROM moz_cookies WHERE id = :id"),
          getter_AddRefs(deleteExpired));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        // Read the first row.
        bool hasResult;
        rv = select->ExecuteStep(&hasResult);
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        if (hasResult) {
          nsCString name1, host1, path1;
          int64_t id1 = select->AsInt64(0);
          select->GetUTF8String(1, name1);
          select->GetUTF8String(2, host1);
          select->GetUTF8String(3, path1);

          nsCString name2, host2, path2;
          while (1) {
            // Read the second row.
            rv = select->ExecuteStep(&hasResult);
            NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

            if (!hasResult)
              break;

            int64_t id2 = select->AsInt64(0);
            select->GetUTF8String(1, name2);
            select->GetUTF8String(2, host2);
            select->GetUTF8String(3, path2);

            // If the two rows match in (name, host, path), we know the earlier
            // row has an earlier expiry time. Delete it.
            if (name1 == name2 && host1 == host2 && path1 == path2) {
              mozStorageStatementScoper scoper(deleteExpired);

              rv = deleteExpired->BindInt64ByName(NS_LITERAL_CSTRING("id"),
                id1);
              NS_ASSERT_SUCCESS(rv);

              rv = deleteExpired->ExecuteStep(&hasResult);
              NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
            }

            // Make the second row the first for the next iteration.
            name1 = name2;
            host1 = host2;
            path1 = path2;
            id1 = id2;
          }
        }

        // Add the creationTime column to the table.
        rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "ALTER TABLE moz_cookies ADD creationTime INTEGER"));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        // Copy the id of each row into the new creationTime column.
        rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "UPDATE moz_cookies SET creationTime = "
            "(SELECT id WHERE id = moz_cookies.id)"));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        // Create a unique index on (name, host, path) to allow fast lookup.
        rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "CREATE UNIQUE INDEX moz_uniqueid "
          "ON moz_cookies (name, host, path)"));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
      }
      // Fall through to the next upgrade.

      // No more upgrades. Update the schema version.
      rv = mDefaultDBState->dbConn->SetSchemaVersion(COOKIES_SCHEMA_VERSION);
      NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

    case COOKIES_SCHEMA_VERSION:
      break;

    case 0:
      {
        NS_WARNING("couldn't get schema version!");
          
        // the table may be usable; someone might've just clobbered the schema
        // version. we can treat this case like a downgrade using the codepath
        // below, by verifying the columns we care about are all there. for now,
        // re-set the schema version in the db, in case the checks succeed (if
        // they don't, we're dropping the table anyway).
        rv = mDefaultDBState->dbConn->SetSchemaVersion(COOKIES_SCHEMA_VERSION);
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
      }
      // fall through to downgrade check

    // downgrading.
    // if columns have been added to the table, we can still use the ones we
    // understand safely. if columns have been deleted or altered, just
    // blow away the table and start from scratch! if you change the way
    // a column is interpreted, make sure you also change its name so this
    // check will catch it.
    default:
      {
        // check if all the expected columns exist
        nsCOMPtr<mozIStorageStatement> stmt;
        rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
          "SELECT "
            "id, "
            "baseDomain, "
            "name, "
            "value, "
            "host, "
            "path, "
            "expiry, "
            "lastAccessed, "
            "creationTime, "
            "isSecure, "
            "isHttpOnly "
          "FROM moz_cookies"), getter_AddRefs(stmt));
        if (NS_SUCCEEDED(rv))
          break;

        // our columns aren't there - drop the table!
        rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "DROP TABLE moz_cookies"));
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

        rv = CreateTable();
        NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
      }
      break;
    }
  }

  // make operations on the table asynchronous, for performance
  mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
    "PRAGMA synchronous = OFF"));

  // Use write-ahead-logging for performance. We cap the autocheckpoint limit at
  // 16 pages (around 500KB).
  mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
    MOZ_STORAGE_UNIQUIFY_QUERY_STR "PRAGMA journal_mode = WAL"));
  mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
    "PRAGMA wal_autocheckpoint = 16"));

  // cache frequently used statements (for insertion, deletion, and updating)
  rv = mDefaultDBState->dbConn->CreateAsyncStatement(NS_LITERAL_CSTRING(
    "INSERT INTO moz_cookies ("
      "baseDomain, "
      "name, "
      "value, "
      "host, "
      "path, "
      "expiry, "
      "lastAccessed, "
      "creationTime, "
      "isSecure, "
      "isHttpOnly"
    ") VALUES ("
      ":baseDomain, "
      ":name, "
      ":value, "
      ":host, "
      ":path, "
      ":expiry, "
      ":lastAccessed, "
      ":creationTime, "
      ":isSecure, "
      ":isHttpOnly"
    ")"),
    getter_AddRefs(mDefaultDBState->stmtInsert));
  NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  rv = mDefaultDBState->dbConn->CreateAsyncStatement(NS_LITERAL_CSTRING(
    "DELETE FROM moz_cookies "
    "WHERE name = :name AND host = :host AND path = :path"),
    getter_AddRefs(mDefaultDBState->stmtDelete));
  NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  rv = mDefaultDBState->dbConn->CreateAsyncStatement(NS_LITERAL_CSTRING(
    "UPDATE moz_cookies SET lastAccessed = :lastAccessed "
    "WHERE name = :name AND host = :host AND path = :path"),
    getter_AddRefs(mDefaultDBState->stmtUpdate));
  NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  // if we deleted a corrupt db, don't attempt to import - return now
  if (aRecreateDB)
    return RESULT_OK;

  // check whether to import or just read in the db
  if (tableExists)
    return Read();

  nsCOMPtr<nsIFile> oldCookieFile;
  rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
    getter_AddRefs(oldCookieFile));
  if (NS_FAILED(rv)) return RESULT_OK;

  // Import cookies, and clean up the old file regardless of success or failure.
  // Note that we have to switch out our DBState temporarily, in case we're in
  // private browsing mode; otherwise ImportCookies() won't be happy.
  DBState* initialState = mDBState;
  mDBState = mDefaultDBState;
  oldCookieFile->AppendNative(NS_LITERAL_CSTRING(kOldCookieFileName));
  ImportCookies(oldCookieFile);
  oldCookieFile->Remove(false);
  mDBState = initialState;

  return RESULT_OK;
}

// Sets the schema version and creates the moz_cookies table.
nsresult
nsCookieService::CreateTable()
{
  // Set the schema version, before creating the table.
  nsresult rv = mDefaultDBState->dbConn->SetSchemaVersion(
    COOKIES_SCHEMA_VERSION);
  if (NS_FAILED(rv)) return rv;

  // Create the table.
  rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
    "CREATE TABLE moz_cookies ("
      "id INTEGER PRIMARY KEY, "
      "baseDomain TEXT, "
      "name TEXT, "
      "value TEXT, "
      "host TEXT, "
      "path TEXT, "
      "expiry INTEGER, "
      "lastAccessed INTEGER, "
      "creationTime INTEGER, "
      "isSecure INTEGER, "
      "isHttpOnly INTEGER, "
      "CONSTRAINT moz_uniqueid UNIQUE (name, host, path)"
    ")"));
  if (NS_FAILED(rv)) return rv;

  // Create an index on baseDomain.
  return mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
    "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)"));
}

void
nsCookieService::CloseDBStates()
{
  // Null out our private and pointer DBStates regardless.
  mPrivateDBState = NULL;
  mDBState = NULL;

  // If we don't have a default DBState, we're done.
  if (!mDefaultDBState)
    return;

  if (mDefaultDBState->dbConn) {
    // Cancel any pending read. No further results will be received by our
    // read listener.
    if (mDefaultDBState->pendingRead) {
      CancelAsyncRead(true);
    }

    // Asynchronously close the connection. We will null it below.
    mDefaultDBState->dbConn->AsyncClose(mDefaultDBState->closeListener);
  }

  CloseDefaultDBConnection();

  mDefaultDBState = NULL;
}

// Close the default connection by nulling out statements, listeners, and the
// connection itself. This will not cancel a pending read or asynchronously
// close the connection -- these must be done beforehand if necessary.
void
nsCookieService::CloseDefaultDBConnection()
{
  // Destroy our statements before we close the db.
  mDefaultDBState->stmtInsert = NULL;
  mDefaultDBState->stmtDelete = NULL;
  mDefaultDBState->stmtUpdate = NULL;

  // Null out the database connections. If 'dbConn' has not been used for any
  // asynchronous operations yet, this will synchronously close it; otherwise,
  // it's expected that the caller has performed an AsyncClose prior.
  mDefaultDBState->dbConn = NULL;
  mDefaultDBState->syncConn = NULL;

  // Manually null out our listeners. This is necessary because they hold a
  // strong ref to the DBState itself. They'll stay alive until whatever
  // statements are still executing complete.
  mDefaultDBState->readListener = NULL;
  mDefaultDBState->insertListener = NULL;
  mDefaultDBState->updateListener = NULL;
  mDefaultDBState->removeListener = NULL;
  mDefaultDBState->closeListener = NULL;
}

void
nsCookieService::HandleDBClosed(DBState* aDBState)
{
  COOKIE_LOGSTRING(PR_LOG_DEBUG,
    ("HandleDBClosed(): DBState %x closed", aDBState));

  switch (aDBState->corruptFlag) {
  case DBState::OK: {
    // Database is healthy. Notify of closure.
    mObserverService->NotifyObservers(nullptr, "cookie-db-closed", nullptr);
    break;
  }
  case DBState::CLOSING_FOR_REBUILD: {
    // Our close finished. Start the rebuild, and notify of db closure later.
    RebuildCorruptDB(aDBState);
    break;
  }
  case DBState::REBUILDING: {
    // We encountered an error during rebuild, closed the database, and now
    // here we are. We already have a 'cookies.sqlite.bak' from the original
    // dead database; we don't want to overwrite it, so let's move this one to
    // 'cookies.sqlite.bak-rebuild'.
    nsCOMPtr<nsIFile> backupFile;
    aDBState->cookieFile->Clone(getter_AddRefs(backupFile));
    nsresult rv = backupFile->MoveToNative(NULL,
      NS_LITERAL_CSTRING(COOKIES_FILE ".bak-rebuild"));

    COOKIE_LOGSTRING(PR_LOG_WARNING,
      ("HandleDBClosed(): DBState %x encountered error rebuilding db; move to "
       "'cookies.sqlite.bak-rebuild' gave rv 0x%x", aDBState, rv));
    mObserverService->NotifyObservers(nullptr, "cookie-db-closed", nullptr);
    break;
  }
  }
}

void
nsCookieService::HandleCorruptDB(DBState* aDBState)
{
  if (mDefaultDBState != aDBState) {
    // We've either closed the state or we've switched profiles. It's getting
    // a bit late to rebuild -- bail instead.
    COOKIE_LOGSTRING(PR_LOG_WARNING,
      ("HandleCorruptDB(): DBState %x is already closed, aborting", aDBState));
    return;
  }

  COOKIE_LOGSTRING(PR_LOG_DEBUG,
    ("HandleCorruptDB(): DBState %x has corruptFlag %u", aDBState,
      aDBState->corruptFlag));

  // Mark the database corrupt, so the close listener can begin reconstructing
  // it.
  switch (mDefaultDBState->corruptFlag) {
  case DBState::OK: {
    // Move to 'closing' state.
    mDefaultDBState->corruptFlag = DBState::CLOSING_FOR_REBUILD;

    // Cancel any pending read and close the database. If we do have an
    // in-flight read we want to throw away all the results so far -- we have no
    // idea how consistent the database is. Note that we may have already
    // canceled the read but not emptied our readSet; do so now.
    mDefaultDBState->readSet.Clear();
    if (mDefaultDBState->pendingRead) {
      CancelAsyncRead(true);
      mDefaultDBState->syncConn = nullptr;
    }

    mDefaultDBState->dbConn->AsyncClose(mDefaultDBState->closeListener);
    CloseDefaultDBConnection();
    break;
  }
  case DBState::CLOSING_FOR_REBUILD: {
    // We had an error while waiting for close completion. That's OK, just
    // ignore it -- we're rebuilding anyway.
    return;
  }
  case DBState::REBUILDING: {
    // We had an error while rebuilding the DB. Game over. Close the database
    // and let the close handler do nothing; then we'll move it out of the way.
    if (mDefaultDBState->dbConn) {
      mDefaultDBState->dbConn->AsyncClose(mDefaultDBState->closeListener);
    }
    CloseDefaultDBConnection();
    break;
  }
  }
}

static PLDHashOperator
RebuildDBCallback(nsCookieEntry *aEntry,
                  void          *aArg)
{
  mozIStorageBindingParamsArray* paramsArray =
    static_cast<mozIStorageBindingParamsArray*>(aArg);

  const nsCookieEntry::ArrayType &cookies = aEntry->GetCookies();
  for (nsCookieEntry::IndexType i = 0; i < cookies.Length(); ++i) {
    nsCookie* cookie = cookies[i];

    if (!cookie->IsSession()) {
      bindCookieParameters(paramsArray, aEntry->GetKey(), cookie);
    }
  }

  return PL_DHASH_NEXT;
}

void
nsCookieService::RebuildCorruptDB(DBState* aDBState)
{
  NS_ASSERTION(!aDBState->dbConn, "shouldn't have an open db connection");
  NS_ASSERTION(aDBState->corruptFlag == DBState::CLOSING_FOR_REBUILD,
    "should be in CLOSING_FOR_REBUILD state");

  aDBState->corruptFlag = DBState::REBUILDING;

  if (mDefaultDBState != aDBState) {
    // We've either closed the state or we've switched profiles. It's getting
    // a bit late to rebuild -- bail instead. In any case, we were waiting
    // on rebuild completion to notify of the db closure, which won't happen --
    // do so now.
    COOKIE_LOGSTRING(PR_LOG_WARNING,
      ("RebuildCorruptDB(): DBState %x is stale, aborting", aDBState));
    mObserverService->NotifyObservers(nullptr, "cookie-db-closed", nullptr);
    return;
  }

  COOKIE_LOGSTRING(PR_LOG_DEBUG,
    ("RebuildCorruptDB(): creating new database"));

  // The database has been closed, and we're ready to rebuild. Open a
  // connection.
  OpenDBResult result = TryInitDB(true);
  if (result != RESULT_OK) {
    // We're done. Reset our DB connection and statements, and notify of
    // closure.
    COOKIE_LOGSTRING(PR_LOG_WARNING,
      ("RebuildCorruptDB(): TryInitDB() failed with result %u", result));
    CloseDefaultDBConnection();
    mDefaultDBState->corruptFlag = DBState::OK;
    mObserverService->NotifyObservers(nullptr, "cookie-db-closed", nullptr);
    return;
  }

  // Notify observers that we're beginning the rebuild.
  mObserverService->NotifyObservers(nullptr, "cookie-db-rebuilding", nullptr);

  // Enumerate the hash, and add cookies to the params array.
  mozIStorageAsyncStatement* stmt = aDBState->stmtInsert;
  nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
  stmt->NewBindingParamsArray(getter_AddRefs(paramsArray));
  aDBState->hostTable.EnumerateEntries(RebuildDBCallback, paramsArray.get());

  // Make sure we've got something to write. If we don't, we're done.
  uint32_t length;
  paramsArray->GetLength(&length);
  if (length == 0) {
    COOKIE_LOGSTRING(PR_LOG_DEBUG,
      ("RebuildCorruptDB(): nothing to write, rebuild complete"));
    mDefaultDBState->corruptFlag = DBState::OK;
    return;
  }

  // Execute the statement. If any errors crop up, we won't try again.
  nsresult rv = stmt->BindParameters(paramsArray);
  NS_ASSERT_SUCCESS(rv);
  nsCOMPtr<mozIStoragePendingStatement> handle;
  rv = stmt->ExecuteAsync(aDBState->insertListener, getter_AddRefs(handle));
  NS_ASSERT_SUCCESS(rv);    
}

nsCookieService::~nsCookieService()
{
  CloseDBStates();

  gCookieService = nullptr;
}

NS_IMETHODIMP
nsCookieService::Observe(nsISupports     *aSubject,
                         const char      *aTopic,
                         const PRUnichar *aData)
{
  // check the topic
  if (!strcmp(aTopic, "profile-before-change")) {
    // The profile is about to change,
    // or is going away because the application is shutting down.
    if (mDBState && mDBState->dbConn &&
        !nsCRT::strcmp(aData, NS_LITERAL_STRING("shutdown-cleanse").get())) {
      // Clear the cookie db if we're in the default DBState.
      RemoveAll();
    }

    // Close the default DB connection and null out our DBStates before
    // changing.
    CloseDBStates();

  } else if (!strcmp(aTopic, "profile-do-change")) {
    NS_ASSERTION(!mDefaultDBState, "shouldn't have a default DBState");
    NS_ASSERTION(!mPrivateDBState, "shouldn't have a private DBState");

    // the profile has already changed; init the db from the new location.
    // if we are in the private browsing state, however, we do not want to read
    // data into it - we should instead put it into the default state, so it's
    // ready for us if and when we switch back to it.
    InitDBStates();

  } else if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
    nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(aSubject);
    if (prefBranch)
      PrefChanged(prefBranch);

  } else if (!strcmp(aTopic, NS_PRIVATE_BROWSING_SWITCH_TOPIC)) {
    if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_ENTER).Equals(aData)) {
      NS_ASSERTION(mDefaultDBState, "don't have a default state");
      NS_ASSERTION(mDBState == mDefaultDBState, "not in default state");
      NS_ASSERTION(!mPrivateDBState, "already have a private state");

      // Create a new DBState, and swap it in.
      mPrivateDBState = new DBState();
      mDBState = mPrivateDBState;

    } else if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_LEAVE).Equals(aData)) {
      NS_ASSERTION(mDefaultDBState, "don't have a default state");
      NS_ASSERTION(mDBState == mPrivateDBState, "not in private state");
      NS_ASSERTION(!mPrivateDBState->dbConn, "private DB connection not null");

      // Clear the private DBState, and restore the default one.
      mPrivateDBState = NULL;
      mDBState = mDefaultDBState;
    }

    NotifyChanged(nullptr, NS_LITERAL_STRING("reload").get());
  }

  return NS_OK;
}

NS_IMETHODIMP
nsCookieService::GetCookieString(nsIURI     *aHostURI,
                                 nsIChannel *aChannel,
                                 char       **aCookie)
{
  return GetCookieStringCommon(aHostURI, aChannel, false, aCookie);
}

NS_IMETHODIMP
nsCookieService::GetCookieStringFromHttp(nsIURI     *aHostURI,
                                         nsIURI     *aFirstURI,
                                         nsIChannel *aChannel,
                                         char       **aCookie)
{
  return GetCookieStringCommon(aHostURI, aChannel, true, aCookie);
}

nsresult
nsCookieService::GetCookieStringCommon(nsIURI *aHostURI,
                                       nsIChannel *aChannel,
                                       bool aHttpBound,
                                       char** aCookie)
{
  NS_ENSURE_ARG(aHostURI);
  NS_ENSURE_ARG(aCookie);

  // Determine whether the request is foreign. Failure is acceptable.
  bool isForeign = true;
  if (RequireThirdPartyCheck())
    mThirdPartyUtil->IsThirdPartyChannel(aChannel, aHostURI, &isForeign);

  nsCAutoString result;
  GetCookieStringInternal(aHostURI, isForeign, aHttpBound, result);
  *aCookie = result.IsEmpty() ? nullptr : ToNewCString(result);
  return NS_OK;
}

NS_IMETHODIMP
nsCookieService::SetCookieString(nsIURI     *aHostURI,
                                 nsIPrompt  *aPrompt,
                                 const char *aCookieHeader,
                                 nsIChannel *aChannel)
{
  return SetCookieStringCommon(aHostURI, aCookieHeader, NULL, aChannel, false);
}

NS_IMETHODIMP
nsCookieService::SetCookieStringFromHttp(nsIURI     *aHostURI,
                                         nsIURI     *aFirstURI,
                                         nsIPrompt  *aPrompt,
                                         const char *aCookieHeader,
                                         const char *aServerTime,
                                         nsIChannel *aChannel) 
{
  return SetCookieStringCommon(aHostURI, aCookieHeader, aServerTime, aChannel,
                               true);
}

nsresult
nsCookieService::SetCookieStringCommon(nsIURI *aHostURI,
                                       const char *aCookieHeader,
                                       const char *aServerTime,
                                       nsIChannel *aChannel,
                                       bool aFromHttp) 
{
  NS_ENSURE_ARG(aHostURI);
  NS_ENSURE_ARG(aCookieHeader);

  // Determine whether the request is foreign. Failure is acceptable.
  bool isForeign = true;
  if (RequireThirdPartyCheck())
    mThirdPartyUtil->IsThirdPartyChannel(aChannel, aHostURI, &isForeign);

  nsDependentCString cookieString(aCookieHeader);
  nsDependentCString serverTime(aServerTime ? aServerTime : "");
  SetCookieStringInternal(aHostURI, isForeign, cookieString,
                          serverTime, aFromHttp);
  return NS_OK;
}

void
nsCookieService::SetCookieStringInternal(nsIURI             *aHostURI,
                                         bool                aIsForeign,
                                         nsDependentCString &aCookieHeader,
                                         const nsCString    &aServerTime,
                                         bool                aFromHttp)
{
  NS_ASSERTION(aHostURI, "null host!");

  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return;
  }

  // get the base domain for the host URI.
  // e.g. for "www.bbc.co.uk", this would be "bbc.co.uk".
  // file:// URI's (i.e. with an empty host) are allowed, but any other
  // scheme must have a non-empty host. A trailing dot in the host
  // is acceptable.
  bool requireHostMatch;
  nsCAutoString baseDomain;
  nsresult rv = GetBaseDomain(aHostURI, baseDomain, requireHostMatch);
  if (NS_FAILED(rv)) {
    COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader, 
                      "couldn't get base domain from URI");
    return;
  }

  // check default prefs
  CookieStatus cookieStatus = CheckPrefs(aHostURI, aIsForeign, baseDomain,
                                         requireHostMatch, aCookieHeader.get());
  // fire a notification if cookie was rejected (but not if there was an error)
  switch (cookieStatus) {
  case STATUS_REJECTED:
    NotifyRejected(aHostURI);
    return;
  case STATUS_REJECTED_WITH_ERROR:
    return;
  default:
    break;
  }

  // parse server local time. this is not just done here for efficiency
  // reasons - if there's an error parsing it, and we need to default it
  // to the current time, we must do it here since the current time in
  // SetCookieInternal() will change for each cookie processed (e.g. if the
  // user is prompted).
  PRTime tempServerTime;
  int64_t serverTime;
  PRStatus result = PR_ParseTimeString(aServerTime.get(), true,
                                       &tempServerTime);
  if (result == PR_SUCCESS) {
    serverTime = tempServerTime / int64_t(PR_USEC_PER_SEC);
  } else {
    serverTime = PR_Now() / PR_USEC_PER_SEC;
  }

  // process each cookie in the header
  while (SetCookieInternal(aHostURI, baseDomain, requireHostMatch, cookieStatus,
                           aCookieHeader, serverTime, aFromHttp)) {
    // document.cookie can only set one cookie at a time
    if (!aFromHttp)
      break;
  }
}

// notify observers that a cookie was rejected due to the users' prefs.
void
nsCookieService::NotifyRejected(nsIURI *aHostURI)
{
  if (mObserverService)
    mObserverService->NotifyObservers(aHostURI, "cookie-rejected", nullptr);
}

// notify observers that the cookie list changed. there are five possible
// values for aData:
// "deleted" means a cookie was deleted. aSubject is the deleted cookie.
// "added"   means a cookie was added. aSubject is the added cookie.
// "changed" means a cookie was altered. aSubject is the new cookie.
// "cleared" means the entire cookie list was cleared. aSubject is null.
// "batch-deleted" means a set of cookies was purged. aSubject is the list of
// cookies.
void
nsCookieService::NotifyChanged(nsISupports     *aSubject,
                               const PRUnichar *aData)
{
  if (mObserverService)
    mObserverService->NotifyObservers(aSubject, "cookie-changed", aData);
}

already_AddRefed<nsIArray>
nsCookieService::CreatePurgeList(nsICookie2* aCookie)
{
  nsCOMPtr<nsIMutableArray> removedList =
    do_CreateInstance(NS_ARRAY_CONTRACTID);
  removedList->AppendElement(aCookie, false);
  return removedList.forget();
}

/******************************************************************************
 * nsCookieService:
 * pref observer impl
 ******************************************************************************/

void
nsCookieService::PrefChanged(nsIPrefBranch *aPrefBranch)
{
  int32_t val;
  if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefCookieBehavior, &val)))
    mCookieBehavior = (uint8_t) LIMIT(val, 0, 2, 0);

  if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefMaxNumberOfCookies, &val)))
    mMaxNumberOfCookies = (uint16_t) LIMIT(val, 1, 0xFFFF, kMaxNumberOfCookies);

  if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefMaxCookiesPerHost, &val)))
    mMaxCookiesPerHost = (uint16_t) LIMIT(val, 1, 0xFFFF, kMaxCookiesPerHost);

  if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefCookiePurgeAge, &val))) {
    mCookiePurgeAge =
      int64_t(LIMIT(val, 0, PR_INT32_MAX, PR_INT32_MAX)) * PR_USEC_PER_SEC;
  }

  bool boolval;
  if (NS_SUCCEEDED(aPrefBranch->GetBoolPref(kPrefThirdPartySession, &boolval)))
    mThirdPartySession = boolval;

  // Lazily instantiate the third party service if necessary.
  if (!mThirdPartyUtil && RequireThirdPartyCheck()) {
    mThirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID);
    NS_ABORT_IF_FALSE(mThirdPartyUtil, "require ThirdPartyUtil service");
  }
}

/******************************************************************************
 * nsICookieManager impl:
 * nsICookieManager
 ******************************************************************************/

NS_IMETHODIMP
nsCookieService::RemoveAll()
{
  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return NS_ERROR_NOT_AVAILABLE;
  }

  RemoveAllFromMemory();

  // clear the cookie file
  if (mDBState->dbConn) {
    NS_ASSERTION(mDBState == mDefaultDBState, "not in default DB state");

    // Cancel any pending read. No further results will be received by our
    // read listener.
    if (mDefaultDBState->pendingRead) {
      CancelAsyncRead(true);
    }

    nsCOMPtr<mozIStorageAsyncStatement> stmt;
    nsresult rv = mDefaultDBState->dbConn->CreateAsyncStatement(NS_LITERAL_CSTRING(
      "DELETE FROM moz_cookies"), getter_AddRefs(stmt));
    if (NS_SUCCEEDED(rv)) {
      nsCOMPtr<mozIStoragePendingStatement> handle;
      rv = stmt->ExecuteAsync(mDefaultDBState->removeListener,
        getter_AddRefs(handle));
      NS_ASSERT_SUCCESS(rv);
    } else {
      // Recreate the database.
      COOKIE_LOGSTRING(PR_LOG_DEBUG,
        ("RemoveAll(): corruption detected with rv 0x%x", rv));
      HandleCorruptDB(mDefaultDBState);
    }
  }

  NotifyChanged(nullptr, NS_LITERAL_STRING("cleared").get());
  return NS_OK;
}

static PLDHashOperator
COMArrayCallback(nsCookieEntry *aEntry,
                 void          *aArg)
{
  nsCOMArray<nsICookie> *data = static_cast<nsCOMArray<nsICookie> *>(aArg);

  const nsCookieEntry::ArrayType &cookies = aEntry->GetCookies();
  for (nsCookieEntry::IndexType i = 0; i < cookies.Length(); ++i) {
    data->AppendObject(cookies[i]);
  }

  return PL_DHASH_NEXT;
}

NS_IMETHODIMP
nsCookieService::GetEnumerator(nsISimpleEnumerator **aEnumerator)
{
  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return NS_ERROR_NOT_AVAILABLE;
  }

  EnsureReadComplete();

  nsCOMArray<nsICookie> cookieList(mDBState->cookieCount);
  mDBState->hostTable.EnumerateEntries(COMArrayCallback, &cookieList);

  return NS_NewArrayEnumerator(aEnumerator, cookieList);
}

NS_IMETHODIMP
nsCookieService::Add(const nsACString &aHost,
                     const nsACString &aPath,
                     const nsACString &aName,
                     const nsACString &aValue,
                     bool              aIsSecure,
                     bool              aIsHttpOnly,
                     bool              aIsSession,
                     int64_t           aExpiry)
{
  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return NS_ERROR_NOT_AVAILABLE;
  }

  // first, normalize the hostname, and fail if it contains illegal characters.
  nsCAutoString host(aHost);
  nsresult rv = NormalizeHost(host);
  NS_ENSURE_SUCCESS(rv, rv);

  // get the base domain for the host URI.
  // e.g. for "www.bbc.co.uk", this would be "bbc.co.uk".
  nsCAutoString baseDomain;
  rv = GetBaseDomainFromHost(host, baseDomain);
  NS_ENSURE_SUCCESS(rv, rv);

  int64_t currentTimeInUsec = PR_Now();

  nsRefPtr<nsCookie> cookie =
    nsCookie::Create(aName, aValue, host, aPath,
                     aExpiry,
                     currentTimeInUsec,
                     nsCookie::GenerateUniqueCreationTime(currentTimeInUsec),
                     aIsSession,
                     aIsSecure,
                     aIsHttpOnly);
  if (!cookie) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  AddInternal(baseDomain, cookie, currentTimeInUsec, nullptr, nullptr, true);
  return NS_OK;
}

NS_IMETHODIMP
nsCookieService::Remove(const nsACString &aHost,
                        const nsACString &aName,
                        const nsACString &aPath,
                        bool             aBlocked)
{
  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return NS_ERROR_NOT_AVAILABLE;
  }

  // first, normalize the hostname, and fail if it contains illegal characters.
  nsCAutoString host(aHost);
  nsresult rv = NormalizeHost(host);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString baseDomain;
  rv = GetBaseDomainFromHost(host, baseDomain);
  NS_ENSURE_SUCCESS(rv, rv);

  nsListIter matchIter;
  nsRefPtr<nsCookie> cookie;
  if (FindCookie(baseDomain,
                 host,
                 PromiseFlatCString(aName),
                 PromiseFlatCString(aPath),
                 matchIter)) {
    cookie = matchIter.Cookie();
    RemoveCookieFromList(matchIter);
  }

  // check if we need to add the host to the permissions blacklist.
  if (aBlocked && mPermissionService) {
    // strip off the domain dot, if necessary
    if (!host.IsEmpty() && host.First() == '.')
      host.Cut(0, 1);

    host.Insert(NS_LITERAL_CSTRING("http://"), 0);

    nsCOMPtr<nsIURI> uri;
    NS_NewURI(getter_AddRefs(uri), host);

    if (uri)
      mPermissionService->SetAccess(uri, nsICookiePermission::ACCESS_DENY);
  }

  if (cookie) {
    // Everything's done. Notify observers.
    NotifyChanged(cookie, NS_LITERAL_STRING("deleted").get());
  }

  return NS_OK;
}

/******************************************************************************
 * nsCookieService impl:
 * private file I/O functions
 ******************************************************************************/

// Begin an asynchronous read from the database.
OpenDBResult
nsCookieService::Read()
{
  // Set up a statement for the read. Note that our query specifies that
  // 'baseDomain' not be NULL -- see below for why.
  nsCOMPtr<mozIStorageAsyncStatement> stmtRead;
  nsresult rv = mDefaultDBState->dbConn->CreateAsyncStatement(NS_LITERAL_CSTRING(
    "SELECT "
      "name, "
      "value, "
      "host, "
      "path, "
      "expiry, "
      "lastAccessed, "
      "creationTime, "
      "isSecure, "
      "isHttpOnly, "
      "baseDomain "
    "FROM moz_cookies "
    "WHERE baseDomain NOTNULL"), getter_AddRefs(stmtRead));
  NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  // Set up a statement to delete any rows with a NULL 'baseDomain'
  // column. This takes care of any cookies set by browsers that don't
  // understand the 'baseDomain' column, where the database schema version
  // is from one that does. (This would occur when downgrading.)
  nsCOMPtr<mozIStorageAsyncStatement> stmtDeleteNull;
  rv = mDefaultDBState->dbConn->CreateAsyncStatement(NS_LITERAL_CSTRING(
    "DELETE FROM moz_cookies WHERE baseDomain ISNULL"),
    getter_AddRefs(stmtDeleteNull));
  NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  // Start a new connection for sync reads, to reduce contention with the
  // background thread. We need to do this before we kick off write statements,
  // since they can lock the database and prevent connections from being opened.
  rv = mStorageService->OpenUnsharedDatabase(mDefaultDBState->cookieFile,
    getter_AddRefs(mDefaultDBState->syncConn));
  NS_ENSURE_SUCCESS(rv, RESULT_RETRY);

  // Init our readSet hash and execute the statements. Note that, after this
  // point, we cannot fail without altering the cleanup code in InitDBStates()
  // to handle closing of the now-asynchronous connection.
  mDefaultDBState->readSet.Init();
  mDefaultDBState->hostArray.SetCapacity(kMaxNumberOfCookies);

  mDefaultDBState->readListener = new ReadCookieDBListener(mDefaultDBState);
  rv = stmtRead->ExecuteAsync(mDefaultDBState->readListener,
    getter_AddRefs(mDefaultDBState->pendingRead));
  NS_ASSERT_SUCCESS(rv);

  nsCOMPtr<mozIStoragePendingStatement> handle;
  rv = stmtDeleteNull->ExecuteAsync(mDefaultDBState->removeListener,
    getter_AddRefs(handle));
  NS_ASSERT_SUCCESS(rv);

  return RESULT_OK;
}

// Extract data from a single result row and create an nsCookie.
// This is templated since 'T' is different for sync vs async results.
template<class T> nsCookie*
nsCookieService::GetCookieFromRow(T &aRow)
{
  // Skip reading 'baseDomain' -- up to the caller.
  nsCString name, value, host, path;
  nsresult rv = aRow->GetUTF8String(0, name);
  NS_ASSERT_SUCCESS(rv);
  rv = aRow->GetUTF8String(1, value);
  NS_ASSERT_SUCCESS(rv);
  rv = aRow->GetUTF8String(2, host);
  NS_ASSERT_SUCCESS(rv);
  rv = aRow->GetUTF8String(3, path);
  NS_ASSERT_SUCCESS(rv);

  int64_t expiry = aRow->AsInt64(4);
  int64_t lastAccessed = aRow->AsInt64(5);
  int64_t creationTime = aRow->AsInt64(6);
  bool isSecure = 0 != aRow->AsInt32(7);
  bool isHttpOnly = 0 != aRow->AsInt32(8);

  // Create a new nsCookie and assign the data.
  return nsCookie::Create(name, value, host, path,
                          expiry,
                          lastAccessed,
                          creationTime,
                          false,
                          isSecure,
                          isHttpOnly);
}

void
nsCookieService::AsyncReadComplete()
{
  // We may be in the private browsing DB state, with a pending read on the
  // default DB state. (This would occur if we started up in private browsing
  // mode.) As long as we do all our operations on the default state, we're OK.
  NS_ASSERTION(mDefaultDBState, "no default DBState");
  NS_ASSERTION(mDefaultDBState->pendingRead, "no pending read");
  NS_ASSERTION(mDefaultDBState->readListener, "no read listener");

  // Merge the data read on the background thread with the data synchronously
  // read on the main thread. Note that transactions on the cookie table may
  // have occurred on the main thread since, making the background data stale.
  for (uint32_t i = 0; i < mDefaultDBState->hostArray.Length(); ++i) {
    const CookieDomainTuple &tuple = mDefaultDBState->hostArray[i];

    // Tiebreak: if the given base domain has already been read in, ignore
    // the background data. Note that readSet may contain domains that were
    // queried but found not to be in the db -- that's harmless.
    if (mDefaultDBState->readSet.GetEntry(tuple.baseDomain))
      continue;

    AddCookieToList(tuple.baseDomain, tuple.cookie, mDefaultDBState, NULL,
      false);
  }

  mDefaultDBState->stmtReadDomain = nullptr;
  mDefaultDBState->pendingRead = nullptr;
  mDefaultDBState->readListener = nullptr;
  mDefaultDBState->syncConn = nullptr;
  mDefaultDBState->hostArray.Clear();
  mDefaultDBState->readSet.Clear();

  COOKIE_LOGSTRING(PR_LOG_DEBUG, ("Read(): %ld cookies read",
                                  mDefaultDBState->cookieCount));

  mObserverService->NotifyObservers(nullptr, "cookie-db-read", nullptr);
}

void
nsCookieService::CancelAsyncRead(bool aPurgeReadSet)
{
  // We may be in the private browsing DB state, with a pending read on the
  // default DB state. (This would occur if we started up in private browsing
  // mode.) As long as we do all our operations on the default state, we're OK.
  NS_ASSERTION(mDefaultDBState, "no default DBState");
  NS_ASSERTION(mDefaultDBState->pendingRead, "no pending read");
  NS_ASSERTION(mDefaultDBState->readListener, "no read listener");

  // Cancel the pending read, kill the read listener, and empty the array
  // of data already read in on the background thread.
  mDefaultDBState->readListener->Cancel();
  mozilla::DebugOnly<nsresult> rv = mDefaultDBState->pendingRead->Cancel();
  NS_ASSERT_SUCCESS(rv);

  mDefaultDBState->stmtReadDomain = nullptr;
  mDefaultDBState->pendingRead = nullptr;
  mDefaultDBState->readListener = nullptr;
  mDefaultDBState->hostArray.Clear();

  // Only clear the 'readSet' table if we no longer need to know what set of
  // data is already accounted for.
  if (aPurgeReadSet)
    mDefaultDBState->readSet.Clear();
}

void
nsCookieService::EnsureReadDomain(const nsCString &aBaseDomain)
{
  NS_ASSERTION(!mDBState->dbConn || mDBState == mDefaultDBState,
    "not in default db state");

  // Fast path 1: nothing to read, or we've already finished reading.
  if (NS_LIKELY(!mDBState->dbConn || !mDefaultDBState->pendingRead))
    return;

  // Fast path 2: already read in this particular domain.
  if (NS_LIKELY(mDefaultDBState->readSet.GetEntry(aBaseDomain)))
    return;

  // Read in the data synchronously.
  nsresult rv;
  if (!mDefaultDBState->stmtReadDomain) {
    // Cache the statement, since it's likely to be used again.
    rv = mDefaultDBState->syncConn->CreateStatement(NS_LITERAL_CSTRING(
      "SELECT "
        "name, "
        "value, "
        "host, "
        "path, "
        "expiry, "
        "lastAccessed, "
        "creationTime, "
        "isSecure, "
        "isHttpOnly "
      "FROM moz_cookies "
      "WHERE baseDomain = :baseDomain"),
      getter_AddRefs(mDefaultDBState->stmtReadDomain));

    if (NS_FAILED(rv)) {
      // Recreate the database.
      COOKIE_LOGSTRING(PR_LOG_DEBUG,
        ("EnsureReadDomain(): corruption detected when creating statement "
         "with rv 0x%x", rv));
      HandleCorruptDB(mDefaultDBState);
      return;
    }
  }

  NS_ASSERTION(mDefaultDBState->syncConn, "should have a sync db connection");

  mozStorageStatementScoper scoper(mDefaultDBState->stmtReadDomain);

  rv = mDefaultDBState->stmtReadDomain->BindUTF8StringByName(
    NS_LITERAL_CSTRING("baseDomain"), aBaseDomain);
  NS_ASSERT_SUCCESS(rv);

  bool hasResult;
  nsCString name, value, host, path;
  nsAutoTArray<nsRefPtr<nsCookie>, kMaxCookiesPerHost> array;
  while (1) {
    rv = mDefaultDBState->stmtReadDomain->ExecuteStep(&hasResult);
    if (NS_FAILED(rv)) {
      // Recreate the database.
      COOKIE_LOGSTRING(PR_LOG_DEBUG,
        ("EnsureReadDomain(): corruption detected when reading result "
         "with rv 0x%x", rv));
      HandleCorruptDB(mDefaultDBState);
      return;
    }

    if (!hasResult)
      break;

    array.AppendElement(GetCookieFromRow(mDefaultDBState->stmtReadDomain));
  }

  // Add the cookies to the table in a single operation. This makes sure that
  // either all the cookies get added, or in the case of corruption, none.
  for (uint32_t i = 0; i < array.Length(); ++i) {
    AddCookieToList(aBaseDomain, array[i], mDefaultDBState, NULL, false);
  }

  // Add it to the hashset of read entries, so we don't read it again.
  mDefaultDBState->readSet.PutEntry(aBaseDomain);

  COOKIE_LOGSTRING(PR_LOG_DEBUG,
    ("EnsureReadDomain(): %ld cookies read for base domain %s",
     array.Length(), aBaseDomain.get()));
}

void
nsCookieService::EnsureReadComplete()
{
  NS_ASSERTION(!mDBState->dbConn || mDBState == mDefaultDBState,
    "not in default db state");

  // Fast path 1: nothing to read, or we've already finished reading.
  if (NS_LIKELY(!mDBState->dbConn || !mDefaultDBState->pendingRead))
    return;

  // Cancel the pending read, so we don't get any more results.
  CancelAsyncRead(false);

  // Read in the data synchronously.
  nsCOMPtr<mozIStorageStatement> stmt;
  nsresult rv = mDefaultDBState->syncConn->CreateStatement(NS_LITERAL_CSTRING(
    "SELECT "
      "name, "
      "value, "
      "host, "
      "path, "
      "expiry, "
      "lastAccessed, "
      "creationTime, "
      "isSecure, "
      "isHttpOnly, "
      "baseDomain "
    "FROM moz_cookies "
    "WHERE baseDomain NOTNULL"), getter_AddRefs(stmt));

  if (NS_FAILED(rv)) {
    // Recreate the database.
    COOKIE_LOGSTRING(PR_LOG_DEBUG,
      ("EnsureReadComplete(): corruption detected when creating statement "
       "with rv 0x%x", rv));
    HandleCorruptDB(mDefaultDBState);
    return;
  }

  nsCString baseDomain, name, value, host, path;
  bool hasResult;
  nsAutoTArray<CookieDomainTuple, kMaxNumberOfCookies> array;
  while (1) {
    rv = stmt->ExecuteStep(&hasResult);
    if (NS_FAILED(rv)) {
      // Recreate the database.
      COOKIE_LOGSTRING(PR_LOG_DEBUG,
        ("EnsureReadComplete(): corruption detected when reading result "
         "with rv 0x%x", rv));
      HandleCorruptDB(mDefaultDBState);
      return;
    }

    if (!hasResult)
      break;

    // Make sure we haven't already read the data.
    stmt->GetUTF8String(9, baseDomain);
    if (mDefaultDBState->readSet.GetEntry(baseDomain))
      continue;

    CookieDomainTuple* tuple = array.AppendElement();
    tuple->baseDomain = baseDomain;
    tuple->cookie = GetCookieFromRow(stmt);
  }

  // Add the cookies to the table in a single operation. This makes sure that
  // either all the cookies get added, or in the case of corruption, none.
  for (uint32_t i = 0; i < array.Length(); ++i) {
    CookieDomainTuple& tuple = array[i];
    AddCookieToList(tuple.baseDomain, tuple.cookie, mDefaultDBState, NULL,
      false);
  }

  mDefaultDBState->syncConn = nullptr;
  mDefaultDBState->readSet.Clear();

  COOKIE_LOGSTRING(PR_LOG_DEBUG,
    ("EnsureReadComplete(): %ld cookies read", array.Length()));
}

NS_IMETHODIMP
nsCookieService::ImportCookies(nsIFile *aCookieFile)
{
  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return NS_ERROR_NOT_AVAILABLE;
  }

  // Make sure we're in the default DB state. We don't want people importing
  // cookies into a private browsing session!
  if (mDBState != mDefaultDBState) {
    NS_WARNING("Trying to import cookies in a private browsing session!");
    return NS_ERROR_NOT_AVAILABLE;
  }

  nsresult rv;
  nsCOMPtr<nsIInputStream> fileInputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), aCookieFile);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(fileInputStream, &rv);
  if (NS_FAILED(rv)) return rv;

  // First, ensure we've read in everything from the database, if we have one.
  EnsureReadComplete();

  static const char kTrue[] = "TRUE";

  nsCAutoString buffer, baseDomain;
  bool isMore = true;
  int32_t hostIndex, isDomainIndex, pathIndex, secureIndex, expiresIndex, nameIndex, cookieIndex;
  nsASingleFragmentCString::char_iterator iter;
  int32_t numInts;
  int64_t expires;
  bool isDomain, isHttpOnly = false;
  uint32_t originalCookieCount = mDefaultDBState->cookieCount;

  int64_t currentTimeInUsec = PR_Now();
  int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC;
  // we use lastAccessedCounter to keep cookies in recently-used order,
  // so we start by initializing to currentTime (somewhat arbitrary)
  int64_t lastAccessedCounter = currentTimeInUsec;

  /* file format is:
   *
   * host \t isDomain \t path \t secure \t expires \t name \t cookie
   *
   * if this format isn't respected we move onto the next line in the file.
   * isDomain is "TRUE" or "FALSE" (default to "FALSE")
   * isSecure is "TRUE" or "FALSE" (default to "TRUE")
   * expires is a int64_t integer
   * note 1: cookie can contain tabs.
   * note 2: cookies will be stored in order of lastAccessed time:
   *         most-recently used come first; least-recently-used come last.
   */

  /*
   * ...but due to bug 178933, we hide HttpOnly cookies from older code
   * in a comment, so they don't expose HttpOnly cookies to JS.
   *
   * The format for HttpOnly cookies is
   *
   * #HttpOnly_host \t isDomain \t path \t secure \t expires \t name \t cookie
   *
   */

  // We will likely be adding a bunch of cookies to the DB, so we use async
  // batching with storage to make this super fast.
  nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
  if (originalCookieCount == 0 && mDefaultDBState->dbConn) {
    mDefaultDBState->stmtInsert->NewBindingParamsArray(getter_AddRefs(paramsArray));
  }

  while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
    if (StringBeginsWith(buffer, NS_LITERAL_CSTRING(kHttpOnlyPrefix))) {
      isHttpOnly = true;
      hostIndex = sizeof(kHttpOnlyPrefix) - 1;
    } else if (buffer.IsEmpty() || buffer.First() == '#') {
      continue;
    } else {
      isHttpOnly = false;
      hostIndex = 0;
    }

    // this is a cheap, cheesy way of parsing a tab-delimited line into
    // string indexes, which can be lopped off into substrings. just for
    // purposes of obfuscation, it also checks that each token was found.
    // todo: use iterators?
    if ((isDomainIndex = buffer.FindChar('\t', hostIndex)     + 1) == 0 ||
        (pathIndex     = buffer.FindChar('\t', isDomainIndex) + 1) == 0 ||
        (secureIndex   = buffer.FindChar('\t', pathIndex)     + 1) == 0 ||
        (expiresIndex  = buffer.FindChar('\t', secureIndex)   + 1) == 0 ||
        (nameIndex     = buffer.FindChar('\t', expiresIndex)  + 1) == 0 ||
        (cookieIndex   = buffer.FindChar('\t', nameIndex)     + 1) == 0) {
      continue;
    }

    // check the expirytime first - if it's expired, ignore
    // nullstomp the trailing tab, to avoid copying the string
    buffer.BeginWriting(iter);
    *(iter += nameIndex - 1) = char(0);
    numInts = PR_sscanf(buffer.get() + expiresIndex, "%lld", &expires);
    if (numInts != 1 || expires < currentTime) {
      continue;
    }

    isDomain = Substring(buffer, isDomainIndex, pathIndex - isDomainIndex - 1).EqualsLiteral(kTrue);
    const nsASingleFragmentCString &host = Substring(buffer, hostIndex, isDomainIndex - hostIndex - 1);
    // check for bad legacy cookies (domain not starting with a dot, or containing a port),
    // and discard
    if ((isDomain && !host.IsEmpty() && host.First() != '.') ||
        host.FindChar(':') != kNotFound) {
      continue;
    }

    // compute the baseDomain from the host
    rv = GetBaseDomainFromHost(host, baseDomain);
    if (NS_FAILED(rv))
      continue;

    // Create a new nsCookie and assign the data. We don't know the cookie
    // creation time, so just use the current time to generate a unique one.
    nsRefPtr<nsCookie> newCookie =
      nsCookie::Create(Substring(buffer, nameIndex, cookieIndex - nameIndex - 1),
                       Substring(buffer, cookieIndex, buffer.Length() - cookieIndex),
                       host,
                       Substring(buffer, pathIndex, secureIndex - pathIndex - 1),
                       expires,
                       lastAccessedCounter,
                       nsCookie::GenerateUniqueCreationTime(currentTimeInUsec),
                       false,
                       Substring(buffer, secureIndex, expiresIndex - secureIndex - 1).EqualsLiteral(kTrue),
                       isHttpOnly);
    if (!newCookie) {
      return NS_ERROR_OUT_OF_MEMORY;
    }
    
    // trick: preserve the most-recently-used cookie ordering,
    // by successively decrementing the lastAccessed time
    lastAccessedCounter--;

    if (originalCookieCount == 0) {
      AddCookieToList(baseDomain, newCookie, mDefaultDBState, paramsArray);
    }
    else {
      AddInternal(baseDomain, newCookie, currentTimeInUsec, NULL, NULL, true);
    }
  }

  // If we need to write to disk, do so now.
  if (paramsArray) {
    uint32_t length;
    paramsArray->GetLength(&length);
    if (length) {
      rv = mDefaultDBState->stmtInsert->BindParameters(paramsArray);
      NS_ASSERT_SUCCESS(rv);
      nsCOMPtr<mozIStoragePendingStatement> handle;
      rv = mDefaultDBState->stmtInsert->ExecuteAsync(
        mDefaultDBState->insertListener, getter_AddRefs(handle));
      NS_ASSERT_SUCCESS(rv);
    }
  }


  COOKIE_LOGSTRING(PR_LOG_DEBUG, ("ImportCookies(): %ld cookies imported",
    mDefaultDBState->cookieCount));

  return NS_OK;
}

/******************************************************************************
 * nsCookieService impl:
 * private GetCookie/SetCookie helpers
 ******************************************************************************/

// helper function for GetCookieList
static inline bool ispathdelimiter(char c) { return c == '/' || c == '?' || c == '#' || c == ';'; }

// Comparator class for sorting cookies before sending to a server.
class CompareCookiesForSending
{
public:
  bool Equals(const nsCookie* aCookie1, const nsCookie* aCookie2) const
  {
    return aCookie1->CreationTime() == aCookie2->CreationTime() &&
           aCookie2->Path().Length() == aCookie1->Path().Length();
  }

  bool LessThan(const nsCookie* aCookie1, const nsCookie* aCookie2) const
  {
    // compare by cookie path length in accordance with RFC2109
    int32_t result = aCookie2->Path().Length() - aCookie1->Path().Length();
    if (result != 0)
      return result < 0;

    // when path lengths match, older cookies should be listed first.  this is
    // required for backwards compatibility since some websites erroneously
    // depend on receiving cookies in the order in which they were sent to the
    // browser!  see bug 236772.
    return aCookie1->CreationTime() < aCookie2->CreationTime();
  }
};

void
nsCookieService::GetCookieStringInternal(nsIURI *aHostURI,
                                         bool aIsForeign,
                                         bool aHttpBound,
                                         nsCString &aCookieString)
{
  NS_ASSERTION(aHostURI, "null host!");

  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return;
  }

  // get the base domain, host, and path from the URI.
  // e.g. for "www.bbc.co.uk", the base domain would be "bbc.co.uk".
  // file:// URI's (i.e. with an empty host) are allowed, but any other
  // scheme must have a non-empty host. A trailing dot in the host
  // is acceptable.
  bool requireHostMatch;
  nsCAutoString baseDomain, hostFromURI, pathFromURI;
  nsresult rv = GetBaseDomain(aHostURI, baseDomain, requireHostMatch);
  if (NS_SUCCEEDED(rv))
    rv = aHostURI->GetAsciiHost(hostFromURI);
  if (NS_SUCCEEDED(rv))
    rv = aHostURI->GetPath(pathFromURI);
  if (NS_FAILED(rv)) {
    COOKIE_LOGFAILURE(GET_COOKIE, aHostURI, nullptr, "invalid host/path from URI");
    return;
  }

  // check default prefs
  CookieStatus cookieStatus = CheckPrefs(aHostURI, aIsForeign, baseDomain,
                                         requireHostMatch, nullptr);
  // for GetCookie(), we don't fire rejection notifications.
  switch (cookieStatus) {
  case STATUS_REJECTED:
  case STATUS_REJECTED_WITH_ERROR:
    return;
  default:
    break;
  }

  // check if aHostURI is using an https secure protocol.
  // if it isn't, then we can't send a secure cookie over the connection.
  // if SchemeIs fails, assume an insecure connection, to be on the safe side
  bool isSecure;
  if (NS_FAILED(aHostURI->SchemeIs("https", &isSecure))) {
    isSecure = false;
  }

  nsCookie *cookie;
  nsAutoTArray<nsCookie*, 8> foundCookieList;
  int64_t currentTimeInUsec = PR_Now();
  int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC;
  bool stale = false;

  EnsureReadDomain(baseDomain);

  // perform the hash lookup
  nsCookieEntry *entry = mDBState->hostTable.GetEntry(baseDomain);
  if (!entry)
    return;

  // iterate the cookies!
  const nsCookieEntry::ArrayType &cookies = entry->GetCookies();
  for (nsCookieEntry::IndexType i = 0; i < cookies.Length(); ++i) {
    cookie = cookies[i];

    // check the host, since the base domain lookup is conservative.
    // first, check for an exact host or domain cookie match, e.g. "google.com"
    // or ".google.com"; second a subdomain match, e.g.
    // host = "mail.google.com", cookie domain = ".google.com".
    if (cookie->RawHost() != hostFromURI &&
        !(cookie->IsDomain() && StringEndsWith(hostFromURI, cookie->Host())))
      continue;

    // if the cookie is secure and the host scheme isn't, we can't send it
    if (cookie->IsSecure() && !isSecure)
      continue;

    // if the cookie is httpOnly and it's not going directly to the HTTP
    // connection, don't send it
    if (cookie->IsHttpOnly() && !aHttpBound)
      continue;

    // calculate cookie path length, excluding trailing '/'
    uint32_t cookiePathLen = cookie->Path().Length();
    if (cookiePathLen > 0 && cookie->Path().Last() == '/')
      --cookiePathLen;

    // if the nsIURI path is shorter than the cookie path, don't send it back
    if (!StringBeginsWith(pathFromURI, Substring(cookie->Path(), 0, cookiePathLen)))
      continue;

    if (pathFromURI.Length() > cookiePathLen &&
        !ispathdelimiter(pathFromURI.CharAt(cookiePathLen))) {
      /*
       * |ispathdelimiter| tests four cases: '/', '?', '#', and ';'.
       * '/' is the "standard" case; the '?' test allows a site at host/abc?def
       * to receive a cookie that has a path attribute of abc.  this seems
       * strange but at least one major site (citibank, bug 156725) depends
       * on it.  The test for # and ; are put in to proactively avoid problems
       * with other sites - these are the only other chars allowed in the path.
       */
      continue;
    }

    // check if the cookie has expired
    if (cookie->Expiry() <= currentTime) {
      continue;
    }

    // all checks passed - add to list and check if lastAccessed stamp needs updating
    foundCookieList.AppendElement(cookie);
    if (currentTimeInUsec - cookie->LastAccessed() > kCookieStaleThreshold)
      stale = true;
  }

  int32_t count = foundCookieList.Length();
  if (count == 0)
    return;

  // update lastAccessed timestamps. we only do this if the timestamp is stale
  // by a certain amount, to avoid thrashing the db during pageload.
  if (stale) {
    // Create an array of parameters to bind to our update statement. Batching
    // is OK here since we're updating cookies with no interleaved operations.
    nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
    mozIStorageAsyncStatement* stmt = mDBState->stmtUpdate;
    if (mDBState->dbConn) {
      stmt->NewBindingParamsArray(getter_AddRefs(paramsArray));
    }

    for (int32_t i = 0; i < count; ++i) {
      cookie = foundCookieList.ElementAt(i);

      if (currentTimeInUsec - cookie->LastAccessed() > kCookieStaleThreshold)
        UpdateCookieInList(cookie, currentTimeInUsec, paramsArray);
    }
    // Update the database now if necessary.
    if (paramsArray) {
      uint32_t length;
      paramsArray->GetLength(&length);
      if (length) {
        nsresult rv = stmt->BindParameters(paramsArray);
        NS_ASSERT_SUCCESS(rv);
        nsCOMPtr<mozIStoragePendingStatement> handle;
        rv = stmt->ExecuteAsync(mDBState->updateListener,
          getter_AddRefs(handle));
        NS_ASSERT_SUCCESS(rv);
      }
    }
  }

  // return cookies in order of path length; longest to shortest.
  // this is required per RFC2109.  if cookies match in length,
  // then sort by creation time (see bug 236772).
  foundCookieList.Sort(CompareCookiesForSending());

  for (int32_t i = 0; i < count; ++i) {
    cookie = foundCookieList.ElementAt(i);

    // check if we have anything to write
    if (!cookie->Name().IsEmpty() || !cookie->Value().IsEmpty()) {
      // if we've already added a cookie to the return list, append a "; " so
      // that subsequent cookies are delimited in the final list.
      if (!aCookieString.IsEmpty()) {
        aCookieString.AppendLiteral("; ");
      }

      if (!cookie->Name().IsEmpty()) {
        // we have a name and value - write both
        aCookieString += cookie->Name() + NS_LITERAL_CSTRING("=") + cookie->Value();
      } else {
        // just write value
        aCookieString += cookie->Value();
      }
    }
  }

  if (!aCookieString.IsEmpty())
    COOKIE_LOGSUCCESS(GET_COOKIE, aHostURI, aCookieString, nullptr, nullptr);
}

// processes a single cookie, and returns true if there are more cookies
// to be processed
bool
nsCookieService::SetCookieInternal(nsIURI                        *aHostURI,
                                   const nsCString               &aBaseDomain,
                                   bool                           aRequireHostMatch,
                                   CookieStatus                   aStatus,
                                   nsDependentCString            &aCookieHeader,
                                   int64_t                        aServerTime,
                                   bool                           aFromHttp)
{
  NS_ASSERTION(aHostURI, "null host!");

  // create a stack-based nsCookieAttributes, to store all the
  // attributes parsed from the cookie
  nsCookieAttributes cookieAttributes;

  // init expiryTime such that session cookies won't prematurely expire
  cookieAttributes.expiryTime = LL_MAXINT;

  // aCookieHeader is an in/out param to point to the next cookie, if
  // there is one. Save the present value for logging purposes
  nsDependentCString savedCookieHeader(aCookieHeader);

  // newCookie says whether there are multiple cookies in the header;
  // so we can handle them separately.
  bool newCookie = ParseAttributes(aCookieHeader, cookieAttributes);

  int64_t currentTimeInUsec = PR_Now();

  // calculate expiry time of cookie.
  cookieAttributes.isSession = GetExpiry(cookieAttributes, aServerTime,
                                         currentTimeInUsec / PR_USEC_PER_SEC);
  if (aStatus == STATUS_ACCEPT_SESSION) {
    // force lifetime to session. note that the expiration time, if set above,
    // will still apply.
    cookieAttributes.isSession = true;
  }

  // reject cookie if it's over the size limit, per RFC2109
  if ((cookieAttributes.name.Length() + cookieAttributes.value.Length()) > kMaxBytesPerCookie) {
    COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, savedCookieHeader, "cookie too big (> 4kb)");
    return newCookie;
  }

  if (cookieAttributes.name.FindChar('\t') != kNotFound) {
    COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, savedCookieHeader, "invalid name character");
    return newCookie;
  }

  // domain & path checks
  if (!CheckDomain(cookieAttributes, aHostURI, aBaseDomain, aRequireHostMatch)) {
    COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, savedCookieHeader, "failed the domain tests");
    return newCookie;
  }
  if (!CheckPath(cookieAttributes, aHostURI)) {
    COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, savedCookieHeader, "failed the path tests");
    return newCookie;
  }

  // create a new nsCookie and copy attributes
  nsRefPtr<nsCookie> cookie =
    nsCookie::Create(cookieAttributes.name,
                     cookieAttributes.value,
                     cookieAttributes.host,
                     cookieAttributes.path,
                     cookieAttributes.expiryTime,
                     currentTimeInUsec,
                     nsCookie::GenerateUniqueCreationTime(currentTimeInUsec),
                     cookieAttributes.isSession,
                     cookieAttributes.isSecure,
                     cookieAttributes.isHttpOnly);
  if (!cookie)
    return newCookie;

  // check permissions from site permission list, or ask the user,
  // to determine if we can set the cookie
  if (mPermissionService) {
    bool permission;
    // Not passing an nsIChannel here means CanSetCookie will use the currently
    // active window to display the prompt. This isn't exactly ideal, but this
    // code is going away. See bug 546746.
    mPermissionService->CanSetCookie(aHostURI,
                                     nullptr,
                                     static_cast<nsICookie2*>(static_cast<nsCookie*>(cookie)),
                                     &cookieAttributes.isSession,
                                     &cookieAttributes.expiryTime,
                                     &permission);
    if (!permission) {
      COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, savedCookieHeader, "cookie rejected by permission manager");
      NotifyRejected(aHostURI);
      return newCookie;
    }

    // update isSession and expiry attributes, in case they changed
    cookie->SetIsSession(cookieAttributes.isSession);
    cookie->SetExpiry(cookieAttributes.expiryTime);
  }

  // add the cookie to the list. AddInternal() takes care of logging.
  // we get the current time again here, since it may have changed during prompting
  AddInternal(aBaseDomain, cookie, PR_Now(), aHostURI, savedCookieHeader.get(),
              aFromHttp);
  return newCookie;
}

// this is a backend function for adding a cookie to the list, via SetCookie.
// also used in the cookie manager, for profile migration from IE.
// it either replaces an existing cookie; or adds the cookie to the hashtable,
// and deletes a cookie (if maximum number of cookies has been
// reached). also performs list maintenance by removing expired cookies.
void
nsCookieService::AddInternal(const nsCString               &aBaseDomain,
                             nsCookie                      *aCookie,
                             int64_t                        aCurrentTimeInUsec,
                             nsIURI                        *aHostURI,
                             const char                    *aCookieHeader,
                             bool                           aFromHttp)
{
  int64_t currentTime = aCurrentTimeInUsec / PR_USEC_PER_SEC;

  // if the new cookie is httponly, make sure we're not coming from script
  if (!aFromHttp && aCookie->IsHttpOnly()) {
    COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
      "cookie is httponly; coming from script");
    return;
  }

  nsListIter matchIter;
  bool foundCookie = FindCookie(aBaseDomain, aCookie->Host(),
    aCookie->Name(), aCookie->Path(), matchIter);

  nsRefPtr<nsCookie> oldCookie;
  nsCOMPtr<nsIArray> purgedList;
  if (foundCookie) {
    oldCookie = matchIter.Cookie();

    // Check if the old cookie is stale (i.e. has already expired). If so, we
    // need to be careful about the semantics of removing it and adding the new
    // cookie: we want the behavior wrt adding the new cookie to be the same as
    // if it didn't exist, but we still want to fire a removal notification.
    if (oldCookie->Expiry() <= currentTime) {
      if (aCookie->Expiry() <= currentTime) {
        // The new cookie has expired and the old one is stale. Nothing to do.
        COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
          "cookie has already expired");
        return;
      }

      // Remove the stale cookie. We save notification for later, once all list
      // modifications are complete.
      RemoveCookieFromList(matchIter);
      COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
        "stale cookie was purged");
      purgedList = CreatePurgeList(oldCookie);

      // We've done all we need to wrt removing and notifying the stale cookie.
      // From here on out, we pretend pretend it didn't exist, so that we
      // preserve expected notification semantics when adding the new cookie.
      foundCookie = false;

    } else {
      // If the old cookie is httponly, make sure we're not coming from script.
      if (!aFromHttp && oldCookie->IsHttpOnly()) {
        COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
          "previously stored cookie is httponly; coming from script");
        return;
      }

      // Remove the old cookie.
      RemoveCookieFromList(matchIter);

      // If the new cookie has expired -- i.e. the intent was simply to delete
      // the old cookie -- then we're done.
      if (aCookie->Expiry() <= currentTime) {
        COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
          "previously stored cookie was deleted");
        NotifyChanged(oldCookie, NS_LITERAL_STRING("deleted").get());
        return;
      }

      // Preserve creation time of cookie for ordering purposes.
      aCookie->SetCreationTime(oldCookie->CreationTime());
    }

  } else {
    // check if cookie has already expired
    if (aCookie->Expiry() <= currentTime) {
      COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
        "cookie has already expired");
      return;
    }

    // check if we have to delete an old cookie.
    nsCookieEntry *entry = mDBState->hostTable.GetEntry(aBaseDomain);
    if (entry && entry->GetCookies().Length() >= mMaxCookiesPerHost) {
      nsListIter iter;
      FindStaleCookie(entry, currentTime, iter);
      oldCookie = iter.Cookie();

      // remove the oldest cookie from the domain
      RemoveCookieFromList(iter);
      COOKIE_LOGEVICTED(oldCookie, "Too many cookies for this domain");
      purgedList = CreatePurgeList(oldCookie);

    } else if (mDBState->cookieCount >= ADD_TEN_PERCENT(mMaxNumberOfCookies)) {
      int64_t maxAge = aCurrentTimeInUsec - mDBState->cookieOldestTime;
      int64_t purgeAge = ADD_TEN_PERCENT(mCookiePurgeAge);
      if (maxAge >= purgeAge) {
        // we're over both size and age limits by 10%; time to purge the table!
        // do this by:
        // 1) removing expired cookies;
        // 2) evicting the balance of old cookies until we reach the size limit.
        // note that the cookieOldestTime indicator can be pessimistic - if it's
        // older than the actual oldest cookie, we'll just purge more eagerly.
        purgedList = PurgeCookies(aCurrentTimeInUsec);
      }
    }
  }

  // Add the cookie to the db. We do not supply a params array for batching
  // because this might result in removals and additions being out of order.
  AddCookieToList(aBaseDomain, aCookie, mDBState, NULL);
  COOKIE_LOGSUCCESS(SET_COOKIE, aHostURI, aCookieHeader, aCookie, foundCookie);

  // Now that list mutations are complete, notify observers. We do it here
  // because observers may themselves attempt to mutate the list.
  if (purgedList) {
    NotifyChanged(purgedList, NS_LITERAL_STRING("batch-deleted").get());
  }

  NotifyChanged(aCookie, foundCookie ? NS_LITERAL_STRING("changed").get()
                                     : NS_LITERAL_STRING("added").get());
}

/******************************************************************************
 * nsCookieService impl:
 * private cookie header parsing functions
 ******************************************************************************/

// The following comment block elucidates the function of ParseAttributes.
/******************************************************************************
 ** Augmented BNF, modified from RFC2109 Section 4.2.2 and RFC2616 Section 2.1
 ** please note: this BNF deviates from both specifications, and reflects this
 ** implementation. <bnf> indicates a reference to the defined grammar "bnf".

 ** Differences from RFC2109/2616 and explanations:
    1. implied *LWS
         The grammar described by this specification is word-based. Except
         where noted otherwise, linear white space (<LWS>) can be included
         between any two adjacent words (token or quoted-string), and
         between adjacent words and separators, without changing the
         interpretation of a field.
       <LWS> according to spec is SP|HT|CR|LF, but here, we allow only SP | HT.

    2. We use CR | LF as cookie separators, not ',' per spec, since ',' is in
       common use inside values.

    3. tokens and values have looser restrictions on allowed characters than
       spec. This is also due to certain characters being in common use inside
       values. We allow only '=' to separate token/value pairs, and ';' to
       terminate tokens or values. <LWS> is allowed within tokens and values
       (see bug 206022).

    4. where appropriate, full <OCTET>s are allowed, where the spec dictates to
       reject control chars or non-ASCII chars. This is erring on the loose
       side, since there's probably no good reason to enforce this strictness.

    5. cookie <NAME> is optional, where spec requires it. This is a fairly
       trivial case, but allows the flexibility of setting only a cookie <VALUE>
       with a blank <NAME> and is required by some sites (see bug 169091).
       
    6. Attribute "HttpOnly", not covered in the RFCs, is supported
       (see bug 178993).

 ** Begin BNF:
    token         = 1*<any allowed-chars except separators>
    value         = 1*<any allowed-chars except value-sep>
    separators    = ";" | "="
    value-sep     = ";"
    cookie-sep    = CR | LF
    allowed-chars = <any OCTET except NUL or cookie-sep>
    OCTET         = <any 8-bit sequence of data>
    LWS           = SP | HT
    NUL           = <US-ASCII NUL, null control character (0)>
    CR            = <US-ASCII CR, carriage return (13)>
    LF            = <US-ASCII LF, linefeed (10)>
    SP            = <US-ASCII SP, space (32)>
    HT            = <US-ASCII HT, horizontal-tab (9)>

    set-cookie    = "Set-Cookie:" cookies
    cookies       = cookie *( cookie-sep cookie )
    cookie        = [NAME "="] VALUE *(";" cookie-av)    ; cookie NAME/VALUE must come first
    NAME          = token                                ; cookie name
    VALUE         = value                                ; cookie value
    cookie-av     = token ["=" value]

    valid values for cookie-av (checked post-parsing) are:
    cookie-av     = "Path"    "=" value
                  | "Domain"  "=" value
                  | "Expires" "=" value
                  | "Max-Age" "=" value
                  | "Comment" "=" value
                  | "Version" "=" value
                  | "Secure"
                  | "HttpOnly"

******************************************************************************/

// helper functions for GetTokenValue
static inline bool iswhitespace     (char c) { return c == ' '  || c == '\t'; }
static inline bool isterminator     (char c) { return c == '\n' || c == '\r'; }
static inline bool isvalueseparator (char c) { return isterminator(c) || c == ';'; }
static inline bool istokenseparator (char c) { return isvalueseparator(c) || c == '='; }

// Parse a single token/value pair.
// Returns true if a cookie terminator is found, so caller can parse new cookie.
bool
nsCookieService::GetTokenValue(nsASingleFragmentCString::const_char_iterator &aIter,
                               nsASingleFragmentCString::const_char_iterator &aEndIter,
                               nsDependentCSubstring                         &aTokenString,
                               nsDependentCSubstring                         &aTokenValue,
                               bool                                          &aEqualsFound)
{
  nsASingleFragmentCString::const_char_iterator start, lastSpace;
  // initialize value string to clear garbage
  aTokenValue.Rebind(aIter, aIter);

  // find <token>, including any <LWS> between the end-of-token and the
  // token separator. we'll remove trailing <LWS> next
  while (aIter != aEndIter && iswhitespace(*aIter))
    ++aIter;
  start = aIter;
  while (aIter != aEndIter && !istokenseparator(*aIter))
    ++aIter;

  // remove trailing <LWS>; first check we're not at the beginning
  lastSpace = aIter;
  if (lastSpace != start) {
    while (--lastSpace != start && iswhitespace(*lastSpace));
    ++lastSpace;
  }
  aTokenString.Rebind(start, lastSpace);

  aEqualsFound = (*aIter == '=');
  if (aEqualsFound) {
    // find <value>
    while (++aIter != aEndIter && iswhitespace(*aIter));

    start = aIter;

    // process <token>
    // just look for ';' to terminate ('=' allowed)
    while (aIter != aEndIter && !isvalueseparator(*aIter))
      ++aIter;

    // remove trailing <LWS>; first check we're not at the beginning
    if (aIter != start) {
      lastSpace = aIter;
      while (--lastSpace != start && iswhitespace(*lastSpace));
      aTokenValue.Rebind(start, ++lastSpace);
    }
  }

  // aIter is on ';', or terminator, or EOS
  if (aIter != aEndIter) {
    // if on terminator, increment past & return true to process new cookie
    if (isterminator(*aIter)) {
      ++aIter;
      return true;
    }
    // fall-through: aIter is on ';', increment and return false
    ++aIter;
  }
  return false;
}

// Parses attributes from cookie header. expires/max-age attributes aren't folded into the
// cookie struct here, because we don't know which one to use until we've parsed the header.
bool
nsCookieService::ParseAttributes(nsDependentCString &aCookieHeader,
                                 nsCookieAttributes &aCookieAttributes)
{
  static const char kPath[]    = "path";
  static const char kDomain[]  = "domain";
  static const char kExpires[] = "expires";
  static const char kMaxage[]  = "max-age";
  static const char kSecure[]  = "secure";
  static const char kHttpOnly[]  = "httponly";

  nsASingleFragmentCString::const_char_iterator tempBegin, tempEnd;
  nsASingleFragmentCString::const_char_iterator cookieStart, cookieEnd;
  aCookieHeader.BeginReading(cookieStart);
  aCookieHeader.EndReading(cookieEnd);

  aCookieAttributes.isSecure = false;
  aCookieAttributes.isHttpOnly = false;
  
  nsDependentCSubstring tokenString(cookieStart, cookieStart);
  nsDependentCSubstring tokenValue (cookieStart, cookieStart);
  bool newCookie, equalsFound;

  // extract cookie <NAME> & <VALUE> (first attribute), and copy the strings.
  // if we find multiple cookies, return for processing
  // note: if there's no '=', we assume token is <VALUE>. this is required by
  //       some sites (see bug 169091).
  // XXX fix the parser to parse according to <VALUE> grammar for this case
  newCookie = GetTokenValue(cookieStart, cookieEnd, tokenString, tokenValue, equalsFound);
  if (equalsFound) {
    aCookieAttributes.name = tokenString;
    aCookieAttributes.value = tokenValue;
  } else {
    aCookieAttributes.value = tokenString;
  }

  // extract remaining attributes
  while (cookieStart != cookieEnd && !newCookie) {
    newCookie = GetTokenValue(cookieStart, cookieEnd, tokenString, tokenValue, equalsFound);

    if (!tokenValue.IsEmpty()) {
      tokenValue.BeginReading(tempBegin);
      tokenValue.EndReading(tempEnd);
    }

    // decide which attribute we have, and copy the string
    if (tokenString.LowerCaseEqualsLiteral(kPath))
      aCookieAttributes.path = tokenValue;

    else if (tokenString.LowerCaseEqualsLiteral(kDomain))
      aCookieAttributes.host = tokenValue;

    else if (tokenString.LowerCaseEqualsLiteral(kExpires))
      aCookieAttributes.expires = tokenValue;

    else if (tokenString.LowerCaseEqualsLiteral(kMaxage))
      aCookieAttributes.maxage = tokenValue;

    // ignore any tokenValue for isSecure; just set the boolean
    else if (tokenString.LowerCaseEqualsLiteral(kSecure))
      aCookieAttributes.isSecure = true;
      
    // ignore any tokenValue for isHttpOnly (see bug 178993);
    // just set the boolean
    else if (tokenString.LowerCaseEqualsLiteral(kHttpOnly))
      aCookieAttributes.isHttpOnly = true;
  }

  // rebind aCookieHeader, in case we need to process another cookie
  aCookieHeader.Rebind(cookieStart, cookieEnd);
  return newCookie;
}

/******************************************************************************
 * nsCookieService impl:
 * private domain & permission compliance enforcement functions
 ******************************************************************************/

// Get the base domain for aHostURI; e.g. for "www.bbc.co.uk", this would be
// "bbc.co.uk". Only properly-formed URI's are tolerated, though a trailing
// dot may be present. If aHostURI is an IP address, an alias such as
// 'localhost', an eTLD such as 'co.uk', or the empty string, aBaseDomain will
// be the exact host, and aRequireHostMatch will be true to indicate that
// substring matches should not be performed.
nsresult
nsCookieService::GetBaseDomain(nsIURI    *aHostURI,
                               nsCString &aBaseDomain,
                               bool      &aRequireHostMatch)
{
  // get the base domain. this will fail if the host contains a leading dot,
  // more than one trailing dot, or is otherwise malformed.
  nsresult rv = mTLDService->GetBaseDomain(aHostURI, 0, aBaseDomain);
  aRequireHostMatch = rv == NS_ERROR_HOST_IS_IP_ADDRESS ||
                      rv == NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS;
  if (aRequireHostMatch) {
    // aHostURI is either an IP address, an alias such as 'localhost', an eTLD
    // such as 'co.uk', or the empty string. use the host as a key in such
    // cases.
    rv = aHostURI->GetAsciiHost(aBaseDomain);
  }
  NS_ENSURE_SUCCESS(rv, rv);

  // aHost (and thus aBaseDomain) may be the string '.'. If so, fail.
  if (aBaseDomain.Length() == 1 && aBaseDomain.Last() == '.')
    return NS_ERROR_INVALID_ARG;

  // block any URIs without a host that aren't file:// URIs.
  if (aBaseDomain.IsEmpty()) {
    bool isFileURI = false;
    aHostURI->SchemeIs("file", &isFileURI);
    if (!isFileURI)
      return NS_ERROR_INVALID_ARG;
  }

  return NS_OK;
}

// Get the base domain for aHost; e.g. for "www.bbc.co.uk", this would be
// "bbc.co.uk". This is done differently than GetBaseDomain(): it is assumed
// that aHost is already normalized, and it may contain a leading dot
// (indicating that it represents a domain). A trailing dot may be present.
// If aHost is an IP address, an alias such as 'localhost', an eTLD such as
// 'co.uk', or the empty string, aBaseDomain will be the exact host, and a
// leading dot will be treated as an error.
nsresult
nsCookieService::GetBaseDomainFromHost(const nsACString &aHost,
                                       nsCString        &aBaseDomain)
{
  // aHost must not be the string '.'.
  if (aHost.Length() == 1 && aHost.Last() == '.')
    return NS_ERROR_INVALID_ARG;

  // aHost may contain a leading dot; if so, strip it now.
  bool domain = !aHost.IsEmpty() && aHost.First() == '.';

  // get the base domain. this will fail if the host contains a leading dot,
  // more than one trailing dot, or is otherwise malformed.
  nsresult rv = mTLDService->GetBaseDomainFromHost(Substring(aHost, domain), 0, aBaseDomain);
  if (rv == NS_ERROR_HOST_IS_IP_ADDRESS ||
      rv == NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
    // aHost is either an IP address, an alias such as 'localhost', an eTLD
    // such as 'co.uk', or the empty string. use the host as a key in such
    // cases; however, we reject any such hosts with a leading dot, since it
    // doesn't make sense for them to be domain cookies.
    if (domain)
      return NS_ERROR_INVALID_ARG;

    aBaseDomain = aHost;
    return NS_OK;
  }
  return rv;
}

// Normalizes the given hostname, component by component. ASCII/ACE
// components are lower-cased, and UTF-8 components are normalized per
// RFC 3454 and converted to ACE.
nsresult
nsCookieService::NormalizeHost(nsCString &aHost)
{
  if (!IsASCII(aHost)) {
    nsCAutoString host;
    nsresult rv = mIDNService->ConvertUTF8toACE(aHost, host);
    if (NS_FAILED(rv))
      return rv;

    aHost = host;
  }

  ToLowerCase(aHost);
  return NS_OK;
}

// returns true if 'a' is equal to or a subdomain of 'b',
// assuming no leading dots are present.
static inline bool IsSubdomainOf(const nsCString &a, const nsCString &b)
{
  if (a == b)
    return true;
  if (a.Length() > b.Length())
    return a[a.Length() - b.Length() - 1] == '.' && StringEndsWith(a, b);
  return false;
}

bool
nsCookieService::RequireThirdPartyCheck()
{
  // 'true' iff we need to perform a third party test.
  return mCookieBehavior == BEHAVIOR_REJECTFOREIGN || mThirdPartySession;
}

CookieStatus
nsCookieService::CheckPrefs(nsIURI          *aHostURI,
                            bool             aIsForeign,
                            const nsCString &aBaseDomain,
                            bool             aRequireHostMatch,
                            const char      *aCookieHeader)
{
  nsresult rv;

  // don't let ftp sites get/set cookies (could be a security issue)
  bool ftp;
  if (NS_SUCCEEDED(aHostURI->SchemeIs("ftp", &ftp)) && ftp) {
    COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI, aCookieHeader, "ftp sites cannot read cookies");
    return STATUS_REJECTED_WITH_ERROR;
  }

  // check the permission list first; if we find an entry, it overrides
  // default prefs. see bug 184059.
  if (mPermissionService) {
    nsCookieAccess access;
    // Not passing an nsIChannel here is probably OK; our implementation
    // doesn't do anything with it anyway.
    rv = mPermissionService->CanAccess(aHostURI, nullptr, &access);

    // if we found an entry, use it
    if (NS_SUCCEEDED(rv)) {
      switch (access) {
      case nsICookiePermission::ACCESS_DENY:
        COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI, aCookieHeader, "cookies are blocked for this site");
        return STATUS_REJECTED;

      case nsICookiePermission::ACCESS_ALLOW:
        return STATUS_ACCEPTED;
      }
    }
  }

  // check default prefs
  if (mCookieBehavior == BEHAVIOR_REJECT) {
    COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI, aCookieHeader, "cookies are disabled");
    return STATUS_REJECTED;
  }

  if (RequireThirdPartyCheck() && aIsForeign) {
    // check if cookie is foreign
    if (mCookieBehavior == BEHAVIOR_ACCEPT && mThirdPartySession)
      return STATUS_ACCEPT_SESSION;

    COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI, aCookieHeader, "context is third party");
    return STATUS_REJECTED;
  }

  // if nothing has complained, accept cookie
  return STATUS_ACCEPTED;
}

// processes domain attribute, and returns true if host has permission to set for this domain.
bool
nsCookieService::CheckDomain(nsCookieAttributes &aCookieAttributes,
                             nsIURI             *aHostURI,
                             const nsCString    &aBaseDomain,
                             bool                aRequireHostMatch)
{
  // get host from aHostURI
  nsCAutoString hostFromURI;
  aHostURI->GetAsciiHost(hostFromURI);

  // if a domain is given, check the host has permission
  if (!aCookieAttributes.host.IsEmpty()) {
    // Tolerate leading '.' characters, but not if it's otherwise an empty host.
    if (aCookieAttributes.host.Length() > 1 &&
        aCookieAttributes.host.First() == '.') {
      aCookieAttributes.host.Cut(0, 1);
    }

    // switch to lowercase now, to avoid case-insensitive compares everywhere
    ToLowerCase(aCookieAttributes.host);

    // check whether the host is either an IP address, an alias such as
    // 'localhost', an eTLD such as 'co.uk', or the empty string. in these
    // cases, require an exact string match for the domain, and leave the cookie
    // as a non-domain one. bug 105917 originally noted the requirement to deal
    // with IP addresses.
    if (aRequireHostMatch)
      return hostFromURI.Equals(aCookieAttributes.host);

    // ensure the proposed domain is derived from the base domain; and also
    // that the host domain is derived from the proposed domain (per RFC2109).
    if (IsSubdomainOf(aCookieAttributes.host, aBaseDomain) &&
        IsSubdomainOf(hostFromURI, aCookieAttributes.host)) {
      // prepend a dot to indicate a domain cookie
      aCookieAttributes.host.Insert(NS_LITERAL_CSTRING("."), 0);
      return true;
    }

    /*
     * note: RFC2109 section 4.3.2 requires that we check the following:
     * that the portion of host not in domain does not contain a dot.
     * this prevents hosts of the form x.y.co.nz from setting cookies in the
     * entire .co.nz domain. however, it's only a only a partial solution and
     * it breaks sites (IE doesn't enforce it), so we don't perform this check.
     */
    return false;
  }

  // no domain specified, use hostFromURI
  aCookieAttributes.host = hostFromURI;
  return true;
}

bool
nsCookieService::CheckPath(nsCookieAttributes &aCookieAttributes,
                           nsIURI             *aHostURI)
{
  // if a path is given, check the host has permission
  if (aCookieAttributes.path.IsEmpty() || aCookieAttributes.path.First() != '/') {
    // strip down everything after the last slash to get the path,
    // ignoring slashes in the query string part.
    // if we can QI to nsIURL, that'll take care of the query string portion.
    // otherwise, it's not an nsIURL and can't have a query string, so just find the last slash.
    nsCOMPtr<nsIURL> hostURL = do_QueryInterface(aHostURI);
    if (hostURL) {
      hostURL->GetDirectory(aCookieAttributes.path);
    } else {
      aHostURI->GetPath(aCookieAttributes.path);
      int32_t slash = aCookieAttributes.path.RFindChar('/');
      if (slash != kNotFound) {
        aCookieAttributes.path.Truncate(slash + 1);
      }
    }

#if 0
  } else {
    /**
     * The following test is part of the RFC2109 spec.  Loosely speaking, it says that a site
     * cannot set a cookie for a path that it is not on.  See bug 155083.  However this patch
     * broke several sites -- nordea (bug 155768) and citibank (bug 156725).  So this test has
     * been disabled, unless we can evangelize these sites.
     */
    // get path from aHostURI
    nsCAutoString pathFromURI;
    if (NS_FAILED(aHostURI->GetPath(pathFromURI)) ||
        !StringBeginsWith(pathFromURI, aCookieAttributes.path)) {
      return false;
    }
#endif
  }

  if (aCookieAttributes.path.Length() > kMaxBytesPerPath ||
      aCookieAttributes.path.FindChar('\t') != kNotFound )
    return false;

  return true;
}

bool
nsCookieService::GetExpiry(nsCookieAttributes &aCookieAttributes,
                           int64_t             aServerTime,
                           int64_t             aCurrentTime)
{
  /* Determine when the cookie should expire. This is done by taking the difference between 
   * the server time and the time the server wants the cookie to expire, and adding that 
   * difference to the client time. This localizes the client time regardless of whether or
   * not the TZ environment variable was set on the client.
   *
   * Note: We need to consider accounting for network lag here, per RFC.
   */
  int64_t delta;

  // check for max-age attribute first; this overrides expires attribute
  if (!aCookieAttributes.maxage.IsEmpty()) {
    // obtain numeric value of maxageAttribute
    int64_t maxage;
    int32_t numInts = PR_sscanf(aCookieAttributes.maxage.get(), "%lld", &maxage);

    // default to session cookie if the conversion failed
    if (numInts != 1) {
      return true;
    }

    delta = maxage;

  // check for expires attribute
  } else if (!aCookieAttributes.expires.IsEmpty()) {
    PRTime expires;

    // parse expiry time
    if (PR_ParseTimeString(aCookieAttributes.expires.get(), true, &expires) != PR_SUCCESS) {
      return true;
    }

    delta = expires / int64_t(PR_USEC_PER_SEC) - aServerTime;

  // default to session cookie if no attributes found
  } else {
    return true;
  }

  // if this addition overflows, expiryTime will be less than currentTime
  // and the cookie will be expired - that's okay.
  aCookieAttributes.expiryTime = aCurrentTime + delta;

  return false;
}

/******************************************************************************
 * nsCookieService impl:
 * private cookielist management functions
 ******************************************************************************/

void
nsCookieService::RemoveAllFromMemory()
{
  // clearing the hashtable will call each nsCookieEntry's dtor,
  // which releases all their respective children.
  mDBState->hostTable.Clear();
  mDBState->cookieCount = 0;
  mDBState->cookieOldestTime = LL_MAXINT;
}

// stores temporary data for enumerating over the hash entries,
// since enumeration is done using callback functions
struct nsPurgeData
{
  typedef nsTArray<nsListIter> ArrayType;

  nsPurgeData(int64_t aCurrentTime,
              int64_t aPurgeTime,
              ArrayType &aPurgeList,
              nsIMutableArray *aRemovedList,
              mozIStorageBindingParamsArray *aParamsArray)
   : currentTime(aCurrentTime)
   , purgeTime(aPurgeTime)
   , oldestTime(LL_MAXINT)
   , purgeList(aPurgeList)
   , removedList(aRemovedList)
   , paramsArray(aParamsArray)
  {
  }

  // the current time, in seconds
  int64_t currentTime;

  // lastAccessed time older than which cookies are eligible for purge
  int64_t purgeTime;

  // lastAccessed time of the oldest cookie found during purge, to update our indicator
  int64_t oldestTime;

  // list of cookies over the age limit, for purging
  ArrayType &purgeList;

  // list of all cookies we've removed, for notification
  nsIMutableArray *removedList;

  // The array of parameters to be bound to the statement for deletion later.
  mozIStorageBindingParamsArray *paramsArray;
};

// comparator class for lastaccessed times of cookies.
class CompareCookiesByAge {
public:
  bool Equals(const nsListIter &a, const nsListIter &b) const
  {
    return a.Cookie()->LastAccessed() == b.Cookie()->LastAccessed() &&
           a.Cookie()->CreationTime() == b.Cookie()->CreationTime();
  }

  bool LessThan(const nsListIter &a, const nsListIter &b) const
  {
    // compare by lastAccessed time, and tiebreak by creationTime.
    int64_t result = a.Cookie()->LastAccessed() - b.Cookie()->LastAccessed();
    if (result != 0)
      return result < 0;

    return a.Cookie()->CreationTime() < b.Cookie()->CreationTime();
  }
};

// comparator class for sorting cookies by entry and index.
class CompareCookiesByIndex {
public:
  bool Equals(const nsListIter &a, const nsListIter &b) const
  {
    NS_ASSERTION(a.entry != b.entry || a.index != b.index,
      "cookie indexes should never be equal");
    return false;
  }

  bool LessThan(const nsListIter &a, const nsListIter &b) const
  {
    // compare by entryclass pointer, then by index.
    if (a.entry != b.entry)
      return a.entry < b.entry;

    return a.index < b.index;
  }
};

PLDHashOperator
purgeCookiesCallback(nsCookieEntry *aEntry,
                     void          *aArg)
{
  nsPurgeData &data = *static_cast<nsPurgeData*>(aArg);

  const nsCookieEntry::ArrayType &cookies = aEntry->GetCookies();
  mozIStorageBindingParamsArray *array = data.paramsArray;
  for (nsCookieEntry::IndexType i = 0; i < cookies.Length(); ) {
    nsListIter iter(aEntry, i);
    nsCookie *cookie = cookies[i];

    // check if the cookie has expired
    if (cookie->Expiry() <= data.currentTime) {
      data.removedList->AppendElement(cookie, false);
      COOKIE_LOGEVICTED(cookie, "Cookie expired");

      // remove from list; do not increment our iterator
      gCookieService->RemoveCookieFromList(iter, array);

    } else {
      // check if the cookie is over the age limit
      if (cookie->LastAccessed() <= data.purgeTime) {
        data.purgeList.AppendElement(iter);

      } else if (cookie->LastAccessed() < data.oldestTime) {
        // reset our indicator
        data.oldestTime = cookie->LastAccessed();
      }

      ++i;
    }
  }
  return PL_DHASH_NEXT;
}

// purges expired and old cookies in a batch operation.
already_AddRefed<nsIArray>
nsCookieService::PurgeCookies(int64_t aCurrentTimeInUsec)
{
  NS_ASSERTION(mDBState->hostTable.Count() > 0, "table is empty");
  EnsureReadComplete();

#ifdef PR_LOGGING
  uint32_t initialCookieCount = mDBState->cookieCount;
  COOKIE_LOGSTRING(PR_LOG_DEBUG,
    ("PurgeCookies(): beginning purge with %ld cookies and %lld oldest age",
     mDBState->cookieCount, aCurrentTimeInUsec - mDBState->cookieOldestTime));
#endif

  nsAutoTArray<nsListIter, kMaxNumberOfCookies> purgeList;

  nsCOMPtr<nsIMutableArray> removedList = do_CreateInstance(NS_ARRAY_CONTRACTID);

  // Create a params array to batch the removals. This is OK here because
  // all the removals are in order, and there are no interleaved additions.
  mozIStorageAsyncStatement *stmt = mDBState->stmtDelete;
  nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
  if (mDBState->dbConn) {
    stmt->NewBindingParamsArray(getter_AddRefs(paramsArray));
  }

  nsPurgeData data(aCurrentTimeInUsec / PR_USEC_PER_SEC,
    aCurrentTimeInUsec - mCookiePurgeAge, purgeList, removedList, paramsArray);
  mDBState->hostTable.EnumerateEntries(purgeCookiesCallback, &data);

#ifdef PR_LOGGING
  uint32_t postExpiryCookieCount = mDBState->cookieCount;
#endif

  // now we have a list of iterators for cookies over the age limit.
  // sort them by age, and then we'll see how many to remove...
  purgeList.Sort(CompareCookiesByAge());

  // only remove old cookies until we reach the max cookie limit, no more.
  uint32_t excess = mDBState->cookieCount > mMaxNumberOfCookies ?
    mDBState->cookieCount - mMaxNumberOfCookies : 0;
  if (purgeList.Length() > excess) {
    // We're not purging everything in the list, so update our indicator.
    data.oldestTime = purgeList[excess].Cookie()->LastAccessed();

    purgeList.SetLength(excess);
  }

  // sort the list again, this time grouping cookies with a common entryclass
  // together, and with ascending index. this allows us to iterate backwards
  // over the list removing cookies, without having to adjust indexes as we go.
  purgeList.Sort(CompareCookiesByIndex());
  for (nsPurgeData::ArrayType::index_type i = purgeList.Length(); i--; ) {
    nsCookie *cookie = purgeList[i].Cookie();
    removedList->AppendElement(cookie, false);
    COOKIE_LOGEVICTED(cookie, "Cookie too old");

    RemoveCookieFromList(purgeList[i], paramsArray);
  }

  // Update the database if we have entries to purge.
  if (paramsArray) {
    uint32_t length;
    paramsArray->GetLength(&length);
    if (length) {
      nsresult rv = stmt->BindParameters(paramsArray);
      NS_ASSERT_SUCCESS(rv);
      nsCOMPtr<mozIStoragePendingStatement> handle;
      rv = stmt->ExecuteAsync(mDBState->removeListener, getter_AddRefs(handle));
      NS_ASSERT_SUCCESS(rv);
    }
  }

  // reset the oldest time indicator
  mDBState->cookieOldestTime = data.oldestTime;

  COOKIE_LOGSTRING(PR_LOG_DEBUG,
    ("PurgeCookies(): %ld expired; %ld purged; %ld remain; %lld oldest age",
     initialCookieCount - postExpiryCookieCount,
     postExpiryCookieCount - mDBState->cookieCount,
     mDBState->cookieCount,
     aCurrentTimeInUsec - mDBState->cookieOldestTime));

  return removedList.forget();
}

// find whether a given cookie has been previously set. this is provided by the
// nsICookieManager2 interface.
NS_IMETHODIMP
nsCookieService::CookieExists(nsICookie2 *aCookie,
                              bool       *aFoundCookie)
{
  NS_ENSURE_ARG_POINTER(aCookie);

  if (!mDBState) {
    NS_WARNING("No DBState! Profile already closed?");
    return NS_ERROR_NOT_AVAILABLE;
  }

  nsCAutoString host, name, path;
  nsresult rv = aCookie->GetHost(host);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = aCookie->GetName(name);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = aCookie->GetPath(path);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString baseDomain;
  rv = GetBaseDomainFromHost(host, baseDomain);
  NS_ENSURE_SUCCESS(rv, rv);

  nsListIter iter;
  *aFoundCookie = FindCookie(baseDomain, host, name, path, iter);
  return NS_OK;
}

// For a given base domain, find either an expired cookie or the oldest cookie
// by lastAccessed time.
void
nsCookieService::FindStaleCookie(nsCookieEntry *aEntry,
                                 int64_t aCurrentTime,
                                 nsListIter &aIter)
{
  aIter.entry = NULL;

  int64_t oldestTime = 0;
  const nsCookieEntry::ArrayType &cookies = aEntry->GetCookies();
  for (nsCookieEntry::IndexType i = 0; i < cookies.Length(); ++i) {
    nsCookie *cookie = cookies[i];

    // If we found an expired cookie, we're done.
    if (cookie->Expiry() <= aCurrentTime) {
      aIter.entry = aEntry;
      aIter.index = i;
      return;
    }

    // Check if we've found the oldest cookie so far.
    if (!aIter.entry || oldestTime > cookie->LastAccessed()) {
      oldestTime = cookie->LastAccessed();
      aIter.entry = aEntry;
      aIter.index = i;
    }
  }
}

// count the number of cookies stored by a particular host. this is provided by the
// nsICookieManager2 interface.