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
|
/* -*- 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/. */
#include "Cookie.h"
#include "CookieCommons.h"
#include "CookieLogging.h"
#include "CookiePersistentStorage.h"
#include "CookieService.h"
#include "CookieValidation.h"
#include "mozilla/FileUtils.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/glean/NetwerkMetrics.h"
#include "mozilla/ScopeExit.h"
#include "mozIStorageAsyncStatement.h"
#include "mozIStorageError.h"
#include "mozIStorageFunction.h"
#include "mozIStorageService.h"
#include "mozStorageHelper.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsICookieNotification.h"
#include "nsIEffectiveTLDService.h"
#include "nsILineInputStream.h"
#include "nsIURIMutator.h"
#include "nsNetUtil.h"
#include "nsVariant.h"
#include "prprf.h"
constexpr auto COOKIES_SCHEMA_VERSION = 17;
// parameter indexes; see |Read|
constexpr auto IDX_NAME = 0;
constexpr auto IDX_VALUE = 1;
constexpr auto IDX_HOST = 2;
constexpr auto IDX_PATH = 3;
constexpr auto IDX_EXPIRY_INMSEC = 4;
constexpr auto IDX_LAST_ACCESSED_INUSEC = 5;
constexpr auto IDX_CREATION_TIME_INUSEC = 6;
constexpr auto IDX_SECURE = 7;
constexpr auto IDX_HTTPONLY = 8;
constexpr auto IDX_ORIGIN_ATTRIBUTES = 9;
constexpr auto IDX_SAME_SITE = 10;
constexpr auto IDX_SCHEME_MAP = 11;
constexpr auto IDX_PARTITIONED_ATTRIBUTE_SET = 12;
constexpr auto IDX_UPDATE_TIME_INUSEC = 13;
#define COOKIES_FILE "cookies.sqlite"
namespace mozilla {
namespace net {
namespace {
void BindCookieParameters(mozIStorageBindingParamsArray* aParamsArray,
const CookieKey& aKey, const Cookie* aCookie) {
NS_ASSERTION(aParamsArray,
"Null params array passed to BindCookieParameters!");
NS_ASSERTION(aCookie, "Null cookie passed to BindCookieParameters!");
// Use the asynchronous binding methods to ensure that we do not acquire the
// database lock.
nsCOMPtr<mozIStorageBindingParams> params;
DebugOnly<nsresult> rv =
aParamsArray->NewBindingParams(getter_AddRefs(params));
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsAutoCString suffix;
aKey.mOriginAttributes.CreateSuffix(suffix);
rv = params->BindUTF8StringByName("originAttributes"_ns, suffix);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("name"_ns, aCookie->Name());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("value"_ns, aCookie->Value());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("host"_ns, aCookie->Host());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("path"_ns, aCookie->Path());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindInt64ByName("expiry"_ns, aCookie->ExpiryInMSec());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv =
params->BindInt64ByName("lastAccessed"_ns, aCookie->LastAccessedInUSec());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv =
params->BindInt64ByName("creationTime"_ns, aCookie->CreationTimeInUSec());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindInt32ByName("isSecure"_ns, aCookie->IsSecure());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindInt32ByName("isHttpOnly"_ns, aCookie->IsHttpOnly());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindInt32ByName("sameSite"_ns, aCookie->SameSite());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindInt32ByName("schemeMap"_ns, aCookie->SchemeMap());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindInt32ByName("isPartitionedAttributeSet"_ns,
aCookie->RawIsPartitioned());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindInt64ByName("updateTime"_ns, aCookie->UpdateTimeInUSec());
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Bind the params to the array.
rv = aParamsArray->AddParams(params);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
class ConvertAppIdToOriginAttrsSQLFunction final : public mozIStorageFunction {
~ConvertAppIdToOriginAttrsSQLFunction() = default;
NS_DECL_ISUPPORTS
NS_DECL_MOZISTORAGEFUNCTION
};
NS_IMPL_ISUPPORTS(ConvertAppIdToOriginAttrsSQLFunction, mozIStorageFunction);
NS_IMETHODIMP
ConvertAppIdToOriginAttrsSQLFunction::OnFunctionCall(
mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult) {
nsresult rv;
OriginAttributes attrs;
nsAutoCString suffix;
attrs.CreateSuffix(suffix);
RefPtr<nsVariant> outVar(new nsVariant());
rv = outVar->SetAsAUTF8String(suffix);
NS_ENSURE_SUCCESS(rv, rv);
outVar.forget(aResult);
return NS_OK;
}
class SetAppIdFromOriginAttributesSQLFunction final
: public mozIStorageFunction {
~SetAppIdFromOriginAttributesSQLFunction() = default;
NS_DECL_ISUPPORTS
NS_DECL_MOZISTORAGEFUNCTION
};
NS_IMPL_ISUPPORTS(SetAppIdFromOriginAttributesSQLFunction, mozIStorageFunction);
NS_IMETHODIMP
SetAppIdFromOriginAttributesSQLFunction::OnFunctionCall(
mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult) {
nsresult rv;
nsAutoCString suffix;
OriginAttributes attrs;
rv = aFunctionArguments->GetUTF8String(0, suffix);
NS_ENSURE_SUCCESS(rv, rv);
bool success = attrs.PopulateFromSuffix(suffix);
NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
RefPtr<nsVariant> outVar(new nsVariant());
rv = outVar->SetAsInt32(0); // deprecated appId!
NS_ENSURE_SUCCESS(rv, rv);
outVar.forget(aResult);
return NS_OK;
}
class SetInBrowserFromOriginAttributesSQLFunction final
: public mozIStorageFunction {
~SetInBrowserFromOriginAttributesSQLFunction() = default;
NS_DECL_ISUPPORTS
NS_DECL_MOZISTORAGEFUNCTION
};
NS_IMPL_ISUPPORTS(SetInBrowserFromOriginAttributesSQLFunction,
mozIStorageFunction);
NS_IMETHODIMP
SetInBrowserFromOriginAttributesSQLFunction::OnFunctionCall(
mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult) {
nsresult rv;
nsAutoCString suffix;
OriginAttributes attrs;
rv = aFunctionArguments->GetUTF8String(0, suffix);
NS_ENSURE_SUCCESS(rv, rv);
bool success = attrs.PopulateFromSuffix(suffix);
NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
RefPtr<nsVariant> outVar(new nsVariant());
rv = outVar->SetAsInt32(false);
NS_ENSURE_SUCCESS(rv, rv);
outVar.forget(aResult);
return NS_OK;
}
class FetchPartitionKeyFromOAsSQLFunction final : public mozIStorageFunction {
~FetchPartitionKeyFromOAsSQLFunction() = default;
NS_DECL_ISUPPORTS
NS_DECL_MOZISTORAGEFUNCTION
};
NS_IMPL_ISUPPORTS(FetchPartitionKeyFromOAsSQLFunction, mozIStorageFunction);
NS_IMETHODIMP
FetchPartitionKeyFromOAsSQLFunction::OnFunctionCall(
mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult) {
nsresult rv;
nsAutoCString suffix;
rv = aFunctionArguments->GetUTF8String(0, suffix);
NS_ENSURE_SUCCESS(rv, rv);
OriginAttributes attrsFromSuffix;
bool success = attrsFromSuffix.PopulateFromSuffix(suffix);
NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
RefPtr<nsVariant> outVar(new nsVariant());
rv = outVar->SetAsAString(attrsFromSuffix.mPartitionKey);
NS_ENSURE_SUCCESS(rv, rv);
outVar.forget(aResult);
return NS_OK;
}
class UpdateOAsWithPartitionHostSQLFunction final : public mozIStorageFunction {
~UpdateOAsWithPartitionHostSQLFunction() = default;
NS_DECL_ISUPPORTS
NS_DECL_MOZISTORAGEFUNCTION
};
NS_IMPL_ISUPPORTS(UpdateOAsWithPartitionHostSQLFunction, mozIStorageFunction);
NS_IMETHODIMP
UpdateOAsWithPartitionHostSQLFunction::OnFunctionCall(
mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult) {
nsresult rv;
nsAutoCString formattedOriginAttributes;
rv = aFunctionArguments->GetUTF8String(0, formattedOriginAttributes);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString partitionKeyHost;
rv = aFunctionArguments->GetUTF8String(1, partitionKeyHost);
NS_ENSURE_SUCCESS(rv, rv);
OriginAttributes attrsFromSuffix;
bool success = attrsFromSuffix.PopulateFromSuffix(formattedOriginAttributes);
// On failure, do not alter the OA.
if (!success) {
RefPtr<nsVariant> outVar(new nsVariant());
rv = outVar->SetAsACString(formattedOriginAttributes);
NS_ENSURE_SUCCESS(rv, rv);
outVar.forget(aResult);
return NS_OK;
}
// This is a bit hacky. However, CHIPS cookies can only be set in secure
// contexts. So, the scheme has to be https.
nsAutoCString schemeHost;
schemeHost.AssignLiteral("https://");
if (*partitionKeyHost.get() == '.') {
schemeHost.Append(nsDependentCSubstring(partitionKeyHost, 1));
} else {
schemeHost.Append(partitionKeyHost);
}
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), schemeHost);
// On failure, do not alter the OA.
if (NS_FAILED(rv)) {
RefPtr<nsVariant> outVar(new nsVariant());
rv = outVar->SetAsACString(formattedOriginAttributes);
NS_ENSURE_SUCCESS(rv, rv);
outVar.forget(aResult);
return NS_OK;
}
attrsFromSuffix.SetPartitionKey(uri, false);
attrsFromSuffix.CreateSuffix(formattedOriginAttributes);
RefPtr<nsVariant> outVar(new nsVariant());
rv = outVar->SetAsACString(formattedOriginAttributes);
NS_ENSURE_SUCCESS(rv, rv);
outVar.forget(aResult);
return NS_OK;
}
/******************************************************************************
* DBListenerErrorHandler impl:
* Parent class for our async storage listeners that handles the logging of
* errors.
******************************************************************************/
class DBListenerErrorHandler : public mozIStorageStatementCallback {
protected:
explicit DBListenerErrorHandler(CookiePersistentStorage* dbState)
: mStorage(dbState) {}
RefPtr<CookiePersistentStorage> mStorage;
virtual const char* GetOpType() = 0;
public:
NS_IMETHOD HandleError(mozIStorageError* aError) override {
if (MOZ_LOG_TEST(gCookieLog, LogLevel::Warning)) {
int32_t result = -1;
aError->GetResult(&result);
nsAutoCString message;
aError->GetMessage(message);
COOKIE_LOGSTRING(
LogLevel::Warning,
("DBListenerErrorHandler::HandleError(): Error %d occurred while "
"performing operation '%s' with message '%s'; rebuilding database.",
result, GetOpType(), message.get()));
}
// Rebuild the database.
mStorage->HandleCorruptDB();
return NS_OK;
}
};
/******************************************************************************
* InsertCookieDBListener impl:
* mozIStorageStatementCallback used to track asynchronous insertion operations.
******************************************************************************/
class InsertCookieDBListener final : public DBListenerErrorHandler {
private:
const char* GetOpType() override { return "INSERT"; }
~InsertCookieDBListener() = default;
public:
NS_DECL_ISUPPORTS
explicit InsertCookieDBListener(CookiePersistentStorage* dbState)
: DBListenerErrorHandler(dbState) {}
NS_IMETHOD HandleResult(mozIStorageResultSet* /*aResultSet*/) override {
MOZ_ASSERT_UNREACHABLE(
"Unexpected call to "
"InsertCookieDBListener::HandleResult");
return NS_OK;
}
NS_IMETHOD HandleCompletion(uint16_t aReason) override {
// If we were rebuilding the db and we succeeded, make our mCorruptFlag say
// so.
if (mStorage->GetCorruptFlag() == CookiePersistentStorage::REBUILDING &&
aReason == mozIStorageStatementCallback::REASON_FINISHED) {
COOKIE_LOGSTRING(
LogLevel::Debug,
("InsertCookieDBListener::HandleCompletion(): rebuild complete"));
mStorage->SetCorruptFlag(CookiePersistentStorage::OK);
}
// This notification is just for testing.
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (os) {
os->NotifyObservers(nullptr, "cookie-saved-on-disk", nullptr);
}
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(InsertCookieDBListener, mozIStorageStatementCallback)
/******************************************************************************
* UpdateCookieDBListener impl:
* mozIStorageStatementCallback used to track asynchronous update operations.
******************************************************************************/
class UpdateCookieDBListener final : public DBListenerErrorHandler {
private:
const char* GetOpType() override { return "UPDATE"; }
~UpdateCookieDBListener() = default;
public:
NS_DECL_ISUPPORTS
explicit UpdateCookieDBListener(CookiePersistentStorage* dbState)
: DBListenerErrorHandler(dbState) {}
NS_IMETHOD HandleResult(mozIStorageResultSet* /*aResultSet*/) override {
MOZ_ASSERT_UNREACHABLE(
"Unexpected call to "
"UpdateCookieDBListener::HandleResult");
return NS_OK;
}
NS_IMETHOD HandleCompletion(uint16_t /*aReason*/) override { return NS_OK; }
};
NS_IMPL_ISUPPORTS(UpdateCookieDBListener, mozIStorageStatementCallback)
/******************************************************************************
* RemoveCookieDBListener impl:
* mozIStorageStatementCallback used to track asynchronous removal operations.
******************************************************************************/
class RemoveCookieDBListener final : public DBListenerErrorHandler {
private:
const char* GetOpType() override { return "REMOVE"; }
~RemoveCookieDBListener() = default;
public:
NS_DECL_ISUPPORTS
explicit RemoveCookieDBListener(CookiePersistentStorage* dbState)
: DBListenerErrorHandler(dbState) {}
NS_IMETHOD HandleResult(mozIStorageResultSet* /*aResultSet*/) override {
MOZ_ASSERT_UNREACHABLE(
"Unexpected call to "
"RemoveCookieDBListener::HandleResult");
return NS_OK;
}
NS_IMETHOD HandleCompletion(uint16_t /*aReason*/) override { return NS_OK; }
};
NS_IMPL_ISUPPORTS(RemoveCookieDBListener, mozIStorageStatementCallback)
/******************************************************************************
* CloseCookieDBListener imp:
* Static mozIStorageCompletionCallback used to notify when the database is
* successfully closed.
******************************************************************************/
class CloseCookieDBListener final : public mozIStorageCompletionCallback {
~CloseCookieDBListener() = default;
public:
explicit CloseCookieDBListener(CookiePersistentStorage* dbState)
: mStorage(dbState) {}
RefPtr<CookiePersistentStorage> mStorage;
NS_DECL_ISUPPORTS
NS_IMETHOD Complete(nsresult /*status*/, nsISupports* /*value*/) override {
mStorage->HandleDBClosed();
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(CloseCookieDBListener, mozIStorageCompletionCallback)
static nsLiteralCString ValidationErrorToLabel(
nsICookieValidation::ValidationError aError) {
switch (aError) {
case nsICookieValidation::eOK:
return "eOK"_ns;
case nsICookieValidation::eRejectedEmptyNameAndValue:
return "eRejectedEmptyNameAndValue"_ns;
case nsICookieValidation::eRejectedNameValueOversize:
return "eRejectedNameValueOversize"_ns;
case nsICookieValidation::eRejectedInvalidCharName:
return "eRejectedInvalidCharName"_ns;
case nsICookieValidation::eRejectedInvalidCharValue:
return "eRejectedInvalidCharValue"_ns;
case nsICookieValidation::eRejectedInvalidPath:
return "eRejectedInvalidPath"_ns;
case nsICookieValidation::eRejectedInvalidDomain:
return "eRejectedInvalidDomain"_ns;
case nsICookieValidation::eRejectedInvalidPrefix:
return "eRejectedInvalidPrefix"_ns;
case nsICookieValidation::eRejectedNoneRequiresSecure:
return "eRejectedNoneRequiresSecure"_ns;
case nsICookieValidation::eRejectedPartitionedRequiresSecure:
return "eRejectedPartitionedRequiresSecure"_ns;
case nsICookieValidation::eRejectedHttpOnlyButFromScript:
return "eRejectedHttpOnlyButFromScript"_ns;
case nsICookieValidation::eRejectedSecureButNonHttps:
return "eRejectedSecureButNonHttps"_ns;
case nsICookieValidation::eRejectedForNonSameSiteness:
return "eRejectedForNonSameSiteness"_ns;
case nsICookieValidation::eRejectedAttributePathOversize:
return "eRejectedAttributePathOversize"_ns;
case nsICookieValidation::eRejectedAttributeDomainOversize:
return "eRejectedAttributeDomainOversize"_ns;
case nsICookieValidation::eRejectedAttributeExpiryOversize:
return "eRejectedAttributeExpiryOversize"_ns;
default:
return "eOK"_ns;
}
}
} // namespace
// static
already_AddRefed<CookiePersistentStorage> CookiePersistentStorage::Create() {
RefPtr<CookiePersistentStorage> storage = new CookiePersistentStorage();
storage->Init();
storage->Activate();
return storage.forget();
}
CookiePersistentStorage::CookiePersistentStorage()
: mMonitor("CookiePersistentStorage"),
mInitialized(false),
mCorruptFlag(OK) {}
void CookiePersistentStorage::NotifyChangedInternal(
nsICookieNotification* aNotification, bool aOldCookieIsSession) {
MOZ_ASSERT(aNotification);
// Notify for topic "session-cookie-changed" to update the copy of session
// cookies in session restore component.
nsICookieNotification::Action action = aNotification->GetAction();
// Filter out notifications for individual non-session cookies.
if (action == nsICookieNotification::COOKIE_CHANGED ||
action == nsICookieNotification::COOKIE_DELETED ||
action == nsICookieNotification::COOKIE_ADDED) {
nsCOMPtr<nsICookie> xpcCookie;
DebugOnly<nsresult> rv =
aNotification->GetCookie(getter_AddRefs(xpcCookie));
MOZ_ASSERT(NS_SUCCEEDED(rv) && xpcCookie);
const Cookie& cookie = xpcCookie->AsCookie();
if (!cookie.IsSession() && !aOldCookieIsSession) {
return;
}
}
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (os) {
os->NotifyObservers(aNotification, "session-cookie-changed", u"");
}
}
void CookiePersistentStorage::RemoveAllInternal() {
// clear the cookie file
if (mDBConn) {
nsCOMPtr<mozIStorageAsyncStatement> stmt;
nsresult rv = mDBConn->CreateAsyncStatement("DELETE FROM moz_cookies"_ns,
getter_AddRefs(stmt));
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<mozIStoragePendingStatement> handle;
rv = stmt->ExecuteAsync(mRemoveListener, getter_AddRefs(handle));
MOZ_ASSERT(NS_SUCCEEDED(rv));
} else {
// Recreate the database.
COOKIE_LOGSTRING(LogLevel::Debug,
("RemoveAll(): corruption detected with rv 0x%" PRIx32,
static_cast<uint32_t>(rv)));
HandleCorruptDB();
}
}
}
void CookiePersistentStorage::HandleCorruptDB() {
COOKIE_LOGSTRING(LogLevel::Debug,
("HandleCorruptDB(): CookieStorage %p has mCorruptFlag %u",
this, mCorruptFlag));
// Mark the database corrupt, so the close listener can begin reconstructing
// it.
switch (mCorruptFlag) {
case OK: {
// Move to 'closing' state.
mCorruptFlag = CLOSING_FOR_REBUILD;
CleanupCachedStatements();
mDBConn->AsyncClose(mCloseListener);
CleanupDBConnection();
break;
}
case CLOSING_FOR_REBUILD: {
// We had an error while waiting for close completion. That's OK, just
// ignore it -- we're rebuilding anyway.
return;
}
case 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.
CleanupCachedStatements();
if (mDBConn) {
mDBConn->AsyncClose(mCloseListener);
}
CleanupDBConnection();
break;
}
}
}
void CookiePersistentStorage::RemoveCookiesWithOriginAttributes(
const OriginAttributesPattern& aPattern, const nsACString& aBaseDomain) {
mozStorageTransaction transaction(mDBConn, false);
// XXX Handle the error, bug 1696130.
(void)NS_WARN_IF(NS_FAILED(transaction.Start()));
CookieStorage::RemoveCookiesWithOriginAttributes(aPattern, aBaseDomain);
DebugOnly<nsresult> rv = transaction.Commit();
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
void CookiePersistentStorage::RemoveCookiesFromExactHost(
const nsACString& aHost, const nsACString& aBaseDomain,
const OriginAttributesPattern& aPattern) {
mozStorageTransaction transaction(mDBConn, false);
// XXX Handle the error, bug 1696130.
(void)NS_WARN_IF(NS_FAILED(transaction.Start()));
CookieStorage::RemoveCookiesFromExactHost(aHost, aBaseDomain, aPattern);
DebugOnly<nsresult> rv = transaction.Commit();
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
void CookiePersistentStorage::RemoveCookieFromDB(const Cookie& aCookie) {
// if it's a non-session cookie, remove it from the db
if (aCookie.IsSession() || !mDBConn) {
return;
}
nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
mStmtDelete->NewBindingParamsArray(getter_AddRefs(paramsArray));
PrepareCookieRemoval(aCookie, paramsArray);
DebugOnly<nsresult> rv = mStmtDelete->BindParameters(paramsArray);
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsCOMPtr<mozIStoragePendingStatement> handle;
rv = mStmtDelete->ExecuteAsync(mRemoveListener, getter_AddRefs(handle));
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
void CookiePersistentStorage::PrepareCookieRemoval(
const Cookie& aCookie, mozIStorageBindingParamsArray* aParamsArray) {
// if it's a non-session cookie, remove it from the db
if (aCookie.IsSession() || !mDBConn) {
return;
}
nsCOMPtr<mozIStorageBindingParams> params;
aParamsArray->NewBindingParams(getter_AddRefs(params));
DebugOnly<nsresult> rv =
params->BindUTF8StringByName("name"_ns, aCookie.Name());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("host"_ns, aCookie.Host());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("path"_ns, aCookie.Path());
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsAutoCString suffix;
aCookie.OriginAttributesRef().CreateSuffix(suffix);
rv = params->BindUTF8StringByName("originAttributes"_ns, suffix);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = aParamsArray->AddParams(params);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
// Null out the statements.
// This must be done before closing the connection.
void CookiePersistentStorage::CleanupCachedStatements() {
mStmtInsert = nullptr;
mStmtDelete = nullptr;
mStmtUpdate = nullptr;
}
// Null out the listeners, and the database connection itself. This
// will not null out the statements, cancel a pending read or
// asynchronously close the connection -- these must be done
// beforehand if necessary.
void CookiePersistentStorage::CleanupDBConnection() {
MOZ_ASSERT(!mStmtInsert, "mStmtInsert has been cleaned up");
MOZ_ASSERT(!mStmtDelete, "mStmtDelete has been cleaned up");
MOZ_ASSERT(!mStmtUpdate, "mStmtUpdate has been cleaned up");
// Null out the database connections. If 'mDBConn' 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.
mDBConn = nullptr;
// Manually null out our listeners. This is necessary because they hold a
// strong ref to the CookieStorage itself. They'll stay alive until whatever
// statements are still executing complete.
mInsertListener = nullptr;
mUpdateListener = nullptr;
mRemoveListener = nullptr;
mCloseListener = nullptr;
}
void CookiePersistentStorage::Close() {
if (mThread) {
mThread->Shutdown();
mThread = nullptr;
}
// Cleanup cached statements before we can close anything.
CleanupCachedStatements();
if (mDBConn) {
// Asynchronously close the connection. We will null it below.
mDBConn->AsyncClose(mCloseListener);
}
CleanupDBConnection();
mInitialized = false;
mInitializedDBConn = false;
}
void CookiePersistentStorage::StoreCookie(
const nsACString& aBaseDomain, const OriginAttributes& aOriginAttributes,
Cookie* aCookie) {
// if it's a non-session cookie and hasn't just been read from the db, write
// it out.
if (aCookie->IsSession() || !mDBConn) {
return;
}
nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
mStmtInsert->NewBindingParamsArray(getter_AddRefs(paramsArray));
CookieKey key(aBaseDomain, aOriginAttributes);
BindCookieParameters(paramsArray, key, aCookie);
MaybeStoreCookiesToDB(paramsArray);
}
void CookiePersistentStorage::MaybeStoreCookiesToDB(
mozIStorageBindingParamsArray* aParamsArray) {
if (!aParamsArray) {
return;
}
uint32_t length;
aParamsArray->GetLength(&length);
if (!length) {
return;
}
DebugOnly<nsresult> rv = mStmtInsert->BindParameters(aParamsArray);
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsCOMPtr<mozIStoragePendingStatement> handle;
rv = mStmtInsert->ExecuteAsync(mInsertListener, getter_AddRefs(handle));
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
void CookiePersistentStorage::StaleCookies(
const nsTArray<RefPtr<Cookie>>& aCookieList, int64_t aCurrentTimeInUsec) {
// 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 = mStmtUpdate;
if (mDBConn) {
stmt->NewBindingParamsArray(getter_AddRefs(paramsArray));
}
int32_t count = aCookieList.Length();
for (int32_t i = 0; i < count; ++i) {
Cookie* cookie = aCookieList.ElementAt(i);
if (cookie->IsStale()) {
UpdateCookieInList(cookie, aCurrentTimeInUsec, paramsArray);
}
}
// Update the database now if necessary.
if (paramsArray) {
uint32_t length;
paramsArray->GetLength(&length);
if (length) {
DebugOnly<nsresult> rv = stmt->BindParameters(paramsArray);
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsCOMPtr<mozIStoragePendingStatement> handle;
rv = stmt->ExecuteAsync(mUpdateListener, getter_AddRefs(handle));
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
}
void CookiePersistentStorage::UpdateCookieInList(
Cookie* aCookie, int64_t aLastAccessedInUSec,
mozIStorageBindingParamsArray* aParamsArray) {
MOZ_ASSERT(aCookie);
// udpate the lastAccessedInUSec timestamp
aCookie->SetLastAccessedInUSec(aLastAccessedInUSec);
// if it's a non-session cookie, update it in the db too
if (!aCookie->IsSession() && aParamsArray) {
// Create our params holder.
nsCOMPtr<mozIStorageBindingParams> params;
aParamsArray->NewBindingParams(getter_AddRefs(params));
// Bind our parameters.
DebugOnly<nsresult> rv =
params->BindInt64ByName("lastAccessed"_ns, aLastAccessedInUSec);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("name"_ns, aCookie->Name());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("host"_ns, aCookie->Host());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = params->BindUTF8StringByName("path"_ns, aCookie->Path());
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsAutoCString suffix;
aCookie->OriginAttributesRef().CreateSuffix(suffix);
rv = params->BindUTF8StringByName("originAttributes"_ns, suffix);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Add our bound parameters to the array.
rv = aParamsArray->AddParams(params);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
void CookiePersistentStorage::DeleteFromDB(
mozIStorageBindingParamsArray* aParamsArray) {
uint32_t length;
aParamsArray->GetLength(&length);
if (length) {
DebugOnly<nsresult> rv = mStmtDelete->BindParameters(aParamsArray);
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsCOMPtr<mozIStoragePendingStatement> handle;
rv = mStmtDelete->ExecuteAsync(mRemoveListener, getter_AddRefs(handle));
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
void CookiePersistentStorage::Activate() {
MOZ_ASSERT(!mThread, "already have a cookie thread");
mStorageService = do_GetService("@mozilla.org/storage/service;1");
MOZ_ASSERT(mStorageService);
mTLDService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
MOZ_ASSERT(mTLDService);
// Get our cookie file.
nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
getter_AddRefs(mCookieFile));
if (NS_FAILED(rv)) {
// We've already set up our CookieStorages appropriately; nothing more to
// do.
COOKIE_LOGSTRING(LogLevel::Warning,
("InitCookieStorages(): couldn't get cookie file"));
mInitializedDBConn = true;
mInitialized = true;
return;
}
mCookieFile->AppendNative(nsLiteralCString(COOKIES_FILE));
NS_ENSURE_SUCCESS_VOID(NS_NewNamedThread("Cookie", getter_AddRefs(mThread)));
RefPtr<CookiePersistentStorage> self = this;
nsCOMPtr<nsIRunnable> runnable =
NS_NewRunnableFunction("CookiePersistentStorage::Activate", [self] {
MonitorAutoLock lock(self->mMonitor);
// Attempt to open and read the database. If TryInitDB() returns
// RESULT_RETRY, do so.
OpenDBResult result = self->TryInitDB(false);
if (result == RESULT_RETRY) {
// Database may be corrupt. Synchronously close the connection, clean
// up the default CookieStorage, and try again.
COOKIE_LOGSTRING(LogLevel::Warning,
("InitCookieStorages(): retrying TryInitDB()"));
self->CleanupCachedStatements();
self->CleanupDBConnection();
result = self->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(
LogLevel::Warning,
("InitCookieStorages(): 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.
self->CleanupCachedStatements();
self->CleanupDBConnection();
// No need to initialize mDBConn
self->mInitializedDBConn = true;
}
self->mInitialized = true;
NS_DispatchToMainThread(
NS_NewRunnableFunction("CookiePersistentStorage::InitDBConn",
[self] { self->InitDBConn(); }));
self->mMonitor.Notify();
});
mThread->Dispatch(runnable, NS_DISPATCH_NORMAL);
}
/* 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 CookieStorage.
*/
CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB(
bool aRecreateDB) {
NS_ASSERTION(!mDBConn, "nonnull mDBConn");
NS_ASSERTION(!mStmtInsert, "nonnull mStmtInsert");
NS_ASSERTION(!mInsertListener, "nonnull mInsertListener");
NS_ASSERTION(!mSyncConn, "nonnull mSyncConn");
NS_ASSERTION(NS_GetCurrentThread() == mThread, "non cookie thread");
// 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;
mCookieFile->Clone(getter_AddRefs(backupFile));
rv = backupFile->MoveToNative(nullptr,
nsLiteralCString(COOKIES_FILE ".bak"));
NS_ENSURE_SUCCESS(rv, RESULT_FAILURE);
}
// This block provides scope for the Telemetry AutoTimer
{
auto timer = glean::network_cookies::sqlite_open_readahead.Measure();
ReadAheadFile(mCookieFile);
// 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(
mCookieFile, mozIStorageService::CONNECTION_DEFAULT,
getter_AddRefs(mSyncConn));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
auto guard = MakeScopeExit([&] { mSyncConn = nullptr; });
bool tableExists = false;
mSyncConn->TableExists("moz_cookies"_ns, &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 = mSyncConn->GetSchemaVersion(&dbSchemaVersion);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Start a transaction for the whole migration block.
mozStorageTransaction transaction(mSyncConn, true);
// XXX Handle the error, bug 1696130.
(void)NS_WARN_IF(NS_FAILED(transaction.Start()));
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 = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies ADD lastAccessed INTEGER"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Fall through to the next upgrade.
[[fallthrough]];
case 2: {
// Add the baseDomain column and index to the table.
rv = mSyncConn->ExecuteSimpleSQL(
"ALTER TABLE moz_cookies ADD baseDomain TEXT"_ns);
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.
const int64_t SCHEMA2_IDX_ID = 0;
const int64_t SCHEMA2_IDX_HOST = 1;
nsCOMPtr<mozIStorageStatement> select;
rv = mSyncConn->CreateStatement("SELECT id, host FROM moz_cookies"_ns,
getter_AddRefs(select));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
nsCOMPtr<mozIStorageStatement> update;
rv = mSyncConn->CreateStatement(
nsLiteralCString("UPDATE moz_cookies SET baseDomain = "
":baseDomain WHERE id = :id"),
getter_AddRefs(update));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
nsCString baseDomain;
nsCString host;
bool hasResult;
while (true) {
rv = select->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
if (!hasResult) {
break;
}
int64_t id = select->AsInt64(SCHEMA2_IDX_ID);
select->GetUTF8String(SCHEMA2_IDX_HOST, host);
rv = CookieCommons::GetBaseDomainFromHost(mTLDService, host,
baseDomain);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
mozStorageStatementScoper scoper(update);
rv = update->BindUTF8StringByName("baseDomain"_ns, baseDomain);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = update->BindInt64ByName("id"_ns, id);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = update->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Create an index on baseDomain.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Fall through to the next upgrade.
[[fallthrough]];
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.
const int64_t SCHEMA3_IDX_ID = 0;
const int64_t SCHEMA3_IDX_NAME = 1;
const int64_t SCHEMA3_IDX_HOST = 2;
const int64_t SCHEMA3_IDX_PATH = 3;
nsCOMPtr<mozIStorageStatement> select;
rv = mSyncConn->CreateStatement(
nsLiteralCString(
"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 = mSyncConn->CreateStatement(
"DELETE FROM moz_cookies WHERE id = :id"_ns,
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;
nsCString host1;
nsCString path1;
int64_t id1 = select->AsInt64(SCHEMA3_IDX_ID);
select->GetUTF8String(SCHEMA3_IDX_NAME, name1);
select->GetUTF8String(SCHEMA3_IDX_HOST, host1);
select->GetUTF8String(SCHEMA3_IDX_PATH, path1);
nsCString name2;
nsCString host2;
nsCString path2;
while (true) {
// Read the second row.
rv = select->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
if (!hasResult) {
break;
}
int64_t id2 = select->AsInt64(SCHEMA3_IDX_ID);
select->GetUTF8String(SCHEMA3_IDX_NAME, name2);
select->GetUTF8String(SCHEMA3_IDX_HOST, host2);
select->GetUTF8String(SCHEMA3_IDX_PATH, 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("id"_ns, id1);
MOZ_ASSERT(NS_SUCCEEDED(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 = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"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 = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("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 = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("CREATE UNIQUE INDEX moz_uniqueid "
"ON moz_cookies (name, host, path)"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Fall through to the next upgrade.
[[fallthrough]];
case 4: {
// We need to add appId/inBrowserElement, plus change a constraint on
// the table (unique entries now include appId/inBrowserElement):
// this requires creating a new table and copying the data to it. We
// then rename the new table to the old name.
//
// Why we made this change: appId/inBrowserElement allow "cookie jars"
// for Firefox OS. We create a separate cookie namespace per {appId,
// inBrowserElement}. When upgrading, we convert existing cookies
// (which imply we're on desktop/mobile) to use {0, false}, as that is
// the only namespace used by a non-Firefox-OS implementation.
// Rename existing table
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies RENAME TO moz_cookies_old"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Drop existing index (CreateTable will create new one for new table)
rv = mSyncConn->ExecuteSimpleSQL("DROP INDEX moz_basedomain"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Create new table (with new fields and new unique constraint)
rv = CreateTableForSchemaVersion5();
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Copy data from old table, using appId/inBrowser=0 for existing rows
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"INSERT INTO moz_cookies "
"(baseDomain, appId, inBrowserElement, name, value, host, path, "
"expiry,"
" lastAccessed, creationTime, isSecure, isHttpOnly) "
"SELECT baseDomain, 0, 0, name, value, host, path, expiry,"
" lastAccessed, creationTime, isSecure, isHttpOnly "
"FROM moz_cookies_old"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Drop old table
rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies_old"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 5"));
}
// Fall through to the next upgrade.
[[fallthrough]];
case 5: {
// Change in the version: Replace the columns |appId| and
// |inBrowserElement| by a single column |originAttributes|.
//
// Why we made this change: FxOS new security model (NSec) encapsulates
// "appId/inIsolatedMozBrowser" in nsIPrincipal::originAttributes to
// make it easier to modify the contents of this structure in the
// future.
//
// We do the migration in several steps:
// 1. Rename the old table.
// 2. Create a new table.
// 3. Copy data from the old table to the new table; convert appId and
// inBrowserElement to originAttributes in the meantime.
// Rename existing table.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies RENAME TO moz_cookies_old"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Drop existing index (CreateTable will create new one for new table).
rv = mSyncConn->ExecuteSimpleSQL("DROP INDEX moz_basedomain"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Create new table with new fields and new unique constraint.
rv = CreateTableForSchemaVersion6();
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Copy data from old table without the two deprecated columns appId and
// inBrowserElement.
nsCOMPtr<mozIStorageFunction> convertToOriginAttrs(
new ConvertAppIdToOriginAttrsSQLFunction());
NS_ENSURE_TRUE(convertToOriginAttrs, RESULT_RETRY);
constexpr auto convertToOriginAttrsName =
"CONVERT_TO_ORIGIN_ATTRIBUTES"_ns;
rv = mSyncConn->CreateFunction(convertToOriginAttrsName, 2,
convertToOriginAttrs);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"INSERT INTO moz_cookies "
"(baseDomain, originAttributes, name, value, host, path, expiry,"
" lastAccessed, creationTime, isSecure, isHttpOnly) "
"SELECT baseDomain, "
" CONVERT_TO_ORIGIN_ATTRIBUTES(appId, inBrowserElement),"
" name, value, host, path, expiry, lastAccessed, creationTime, "
" isSecure, isHttpOnly "
"FROM moz_cookies_old"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = mSyncConn->RemoveFunction(convertToOriginAttrsName);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Drop old table
rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies_old"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 6"));
}
[[fallthrough]];
case 6: {
// We made a mistake in schema version 6. We cannot remove expected
// columns of any version (checked in the default case) from cookie
// database, because doing this would destroy the possibility of
// downgrading database.
//
// This version simply restores appId and inBrowserElement columns in
// order to fix downgrading issue even though these two columns are no
// longer used in the latest schema.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies ADD appId INTEGER DEFAULT 0;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies ADD inBrowserElement INTEGER DEFAULT 0;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Compute and populate the values of appId and inBrwoserElement from
// originAttributes.
nsCOMPtr<mozIStorageFunction> setAppId(
new SetAppIdFromOriginAttributesSQLFunction());
NS_ENSURE_TRUE(setAppId, RESULT_RETRY);
constexpr auto setAppIdName = "SET_APP_ID"_ns;
rv = mSyncConn->CreateFunction(setAppIdName, 1, setAppId);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
nsCOMPtr<mozIStorageFunction> setInBrowser(
new SetInBrowserFromOriginAttributesSQLFunction());
NS_ENSURE_TRUE(setInBrowser, RESULT_RETRY);
constexpr auto setInBrowserName = "SET_IN_BROWSER"_ns;
rv = mSyncConn->CreateFunction(setInBrowserName, 1, setInBrowser);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"UPDATE moz_cookies SET appId = SET_APP_ID(originAttributes), "
"inBrowserElement = SET_IN_BROWSER(originAttributes);"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = mSyncConn->RemoveFunction(setAppIdName);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = mSyncConn->RemoveFunction(setInBrowserName);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 7"));
}
[[fallthrough]];
case 7: {
// Remove the appId field from moz_cookies.
//
// Unfortunately sqlite doesn't support dropping columns using ALTER
// TABLE, so we need to go through the procedure documented in
// https://www.sqlite.org/lang_altertable.html.
// Drop existing index
rv = mSyncConn->ExecuteSimpleSQL("DROP INDEX moz_basedomain"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Create a new_moz_cookies table without the appId field.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("CREATE TABLE new_moz_cookies("
"id INTEGER PRIMARY KEY, "
"baseDomain TEXT, "
"originAttributes TEXT NOT NULL DEFAULT '', "
"name TEXT, "
"value TEXT, "
"host TEXT, "
"path TEXT, "
"expiry INTEGER, "
"lastAccessed INTEGER, "
"creationTime INTEGER, "
"isSecure INTEGER, "
"isHttpOnly INTEGER, "
"inBrowserElement INTEGER DEFAULT 0, "
"CONSTRAINT moz_uniqueid UNIQUE (name, host, "
"path, originAttributes)"
")"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Move the data over.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("INSERT INTO new_moz_cookies ("
"id, "
"baseDomain, "
"originAttributes, "
"name, "
"value, "
"host, "
"path, "
"expiry, "
"lastAccessed, "
"creationTime, "
"isSecure, "
"isHttpOnly, "
"inBrowserElement "
") SELECT "
"id, "
"baseDomain, "
"originAttributes, "
"name, "
"value, "
"host, "
"path, "
"expiry, "
"lastAccessed, "
"creationTime, "
"isSecure, "
"isHttpOnly, "
"inBrowserElement "
"FROM moz_cookies;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Drop the old table
rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies;"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Rename new_moz_cookies to moz_cookies.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE new_moz_cookies RENAME TO moz_cookies;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Recreate our index.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("CREATE INDEX moz_basedomain ON moz_cookies "
"(baseDomain, originAttributes)"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 8"));
}
[[fallthrough]];
case 8: {
// Add the sameSite column to the table.
rv = mSyncConn->ExecuteSimpleSQL(
"ALTER TABLE moz_cookies ADD sameSite INTEGER"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 9"));
}
[[fallthrough]];
case 9: {
// Add the rawSameSite column to the table.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies ADD rawSameSite INTEGER"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Copy the current sameSite value into rawSameSite.
rv = mSyncConn->ExecuteSimpleSQL(
"UPDATE moz_cookies SET rawSameSite = sameSite"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 10"));
}
[[fallthrough]];
case 10: {
// Rename existing table
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies RENAME TO moz_cookies_old"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Create a new moz_cookies table without the baseDomain field.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("CREATE TABLE moz_cookies("
"id INTEGER PRIMARY KEY, "
"originAttributes TEXT NOT NULL DEFAULT '', "
"name TEXT, "
"value TEXT, "
"host TEXT, "
"path TEXT, "
"expiry INTEGER, "
"lastAccessed INTEGER, "
"creationTime INTEGER, "
"isSecure INTEGER, "
"isHttpOnly INTEGER, "
"inBrowserElement INTEGER DEFAULT 0, "
"sameSite INTEGER DEFAULT 0, "
"rawSameSite INTEGER DEFAULT 0, "
"CONSTRAINT moz_uniqueid UNIQUE (name, host, "
"path, originAttributes)"
")"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Move the data over.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("INSERT INTO moz_cookies ("
"id, "
"originAttributes, "
"name, "
"value, "
"host, "
"path, "
"expiry, "
"lastAccessed, "
"creationTime, "
"isSecure, "
"isHttpOnly, "
"inBrowserElement, "
"sameSite, "
"rawSameSite "
") SELECT "
"id, "
"originAttributes, "
"name, "
"value, "
"host, "
"path, "
"expiry, "
"lastAccessed, "
"creationTime, "
"isSecure, "
"isHttpOnly, "
"inBrowserElement, "
"sameSite, "
"rawSameSite "
"FROM moz_cookies_old "
"WHERE baseDomain NOTNULL;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Drop the old table
rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies_old;"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Drop the moz_basedomain index from the database (if it hasn't been
// removed already by removing the table).
rv = mSyncConn->ExecuteSimpleSQL(
"DROP INDEX IF EXISTS moz_basedomain;"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 11"));
}
[[fallthrough]];
case 11: {
// Add the schemeMap column to the table.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies ADD schemeMap INTEGER DEFAULT 0;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 12"));
}
[[fallthrough]];
case 12: {
// Add the isPartitionedAttributeSet column to the table.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("ALTER TABLE moz_cookies ADD "
"isPartitionedAttributeSet INTEGER DEFAULT 0;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
COOKIE_LOGSTRING(LogLevel::Debug,
("Upgraded database to schema version 13"));
[[fallthrough]];
}
case 13: {
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("UPDATE moz_cookies SET expiry = unixepoch() + "
"34560000 WHERE expiry > unixepoch() + 34560000"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
[[fallthrough]];
}
case 14: {
nsCOMPtr<mozIStorageStatement> update;
rv = mSyncConn->CreateStatement(
nsLiteralCString("UPDATE moz_cookies SET sameSite = "
":unsetValue WHERE sameSite = :laxValue AND "
"rawSameSite = :noneValue"),
getter_AddRefs(update));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
mozStorageStatementScoper scoper(update);
rv =
update->BindInt32ByName("unsetValue"_ns, nsICookie::SAMESITE_UNSET);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = update->BindInt32ByName("laxValue"_ns, nsICookie::SAMESITE_LAX);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = update->BindInt32ByName("noneValue"_ns, nsICookie::SAMESITE_NONE);
MOZ_ASSERT(NS_SUCCEEDED(rv));
bool hasResult;
rv = update->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"ALTER TABLE moz_cookies DROP COLUMN rawSameSite;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
[[fallthrough]];
}
case 15: {
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("UPDATE moz_cookies SET expiry = expiry * 1000;"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
[[fallthrough]];
}
case 16: {
// Add the updateTime column to the table.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("ALTER TABLE moz_cookies ADD updateTime INTEGER"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// OK so... this is tricky because we have to guess the creationTime
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"UPDATE moz_cookies SET updateTime = CAST(strftime('%s','now') AS "
"INTEGER) * 1000000"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// No more upgrades. Update the schema version.
rv = mSyncConn->SetSchemaVersion(COOKIES_SCHEMA_VERSION);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
[[fallthrough]];
}
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 = mSyncConn->SetSchemaVersion(COOKIES_SCHEMA_VERSION);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// fall through to downgrade check
[[fallthrough]];
// 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 = mSyncConn->CreateStatement(
nsLiteralCString("SELECT "
"id, "
"originAttributes, "
"name, "
"value, "
"host, "
"path, "
"expiry, "
"lastAccessed, "
"creationTime, "
"isSecure, "
"isHttpOnly, "
"sameSite, "
"schemeMap, "
"isPartitionedAttributeSet "
"FROM moz_cookies"),
getter_AddRefs(stmt));
if (NS_SUCCEEDED(rv)) {
break;
}
// our columns aren't there - drop the table!
rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies"_ns);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
rv = CreateTable();
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
} break;
}
}
// if we deleted a corrupt db, don't attempt to import - return now
if (aRecreateDB) {
return RESULT_OK;
}
if (StaticPrefs::network_cookie_CHIPS_enabled() &&
StaticPrefs::network_cookie_CHIPS_lastMigrateDatabase() <
StaticPrefs::network_cookie_CHIPS_migrateDatabaseTarget()) {
CookiePersistentStorage::MoveUnpartitionedChipsCookies();
}
// check whether to import or just read in the db
if (tableExists) {
return Read();
}
return RESULT_OK;
}
void CookiePersistentStorage::MoveUnpartitionedChipsCookies() {
nsCOMPtr<mozIStorageFunction> fetchPartitionKeyFromOAs(
new FetchPartitionKeyFromOAsSQLFunction());
NS_ENSURE_TRUE_VOID(fetchPartitionKeyFromOAs);
constexpr auto fetchPartitionKeyFromOAsName =
"FETCH_PARTITIONKEY_FROM_OAS"_ns;
nsresult rv = mSyncConn->CreateFunction(fetchPartitionKeyFromOAsName, 1,
fetchPartitionKeyFromOAs);
NS_ENSURE_SUCCESS_VOID(rv);
nsCOMPtr<mozIStorageFunction> updateOAsWithPartitionHost(
new UpdateOAsWithPartitionHostSQLFunction());
NS_ENSURE_TRUE_VOID(updateOAsWithPartitionHost);
constexpr auto updateOAsWithPartitionHostName =
"UPDATE_OAS_WITH_PARTITION_HOST"_ns;
rv = mSyncConn->CreateFunction(updateOAsWithPartitionHostName, 2,
updateOAsWithPartitionHost);
NS_ENSURE_SUCCESS_VOID(rv);
// Move all cookies with the Partitioned attribute set into their first-party
// partitioned storage by updating the origin attributes. Overwrite any
// existing cookies that may already be there.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"UPDATE OR REPLACE moz_cookies "
"SET originAttributes = UPDATE_OAS_WITH_PARTITION_HOST(originAttributes, "
"host) "
"WHERE FETCH_PARTITIONKEY_FROM_OAS(originAttributes) = '' "
"AND isPartitionedAttributeSet = 1;"));
NS_ENSURE_SUCCESS_VOID(rv);
rv = mSyncConn->RemoveFunction(fetchPartitionKeyFromOAsName);
NS_ENSURE_SUCCESS_VOID(rv);
rv = mSyncConn->RemoveFunction(updateOAsWithPartitionHostName);
NS_ENSURE_SUCCESS_VOID(rv);
}
void CookiePersistentStorage::RebuildCorruptDB() {
NS_ASSERTION(!mDBConn, "shouldn't have an open db connection");
NS_ASSERTION(mCorruptFlag == CookiePersistentStorage::CLOSING_FOR_REBUILD,
"should be in CLOSING_FOR_REBUILD state");
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
mCorruptFlag = CookiePersistentStorage::REBUILDING;
COOKIE_LOGSTRING(LogLevel::Debug,
("RebuildCorruptDB(): creating new database"));
RefPtr<CookiePersistentStorage> self = this;
nsCOMPtr<nsIRunnable> runnable =
NS_NewRunnableFunction("RebuildCorruptDB.TryInitDB", [self] {
// The database has been closed, and we're ready to rebuild. Open a
// connection.
OpenDBResult result = self->TryInitDB(true);
nsCOMPtr<nsIRunnable> innerRunnable = NS_NewRunnableFunction(
"RebuildCorruptDB.TryInitDBComplete", [self, result] {
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (result != RESULT_OK) {
// We're done. Reset our DB connection and statements, and
// notify of closure.
COOKIE_LOGSTRING(
LogLevel::Warning,
("RebuildCorruptDB(): TryInitDB() failed with result %u",
result));
self->CleanupCachedStatements();
self->CleanupDBConnection();
self->mCorruptFlag = CookiePersistentStorage::OK;
if (os) {
os->NotifyObservers(nullptr, "cookie-db-closed", nullptr);
}
return;
}
// Notify observers that we're beginning the rebuild.
if (os) {
os->NotifyObservers(nullptr, "cookie-db-rebuilding", nullptr);
}
self->InitDBConnInternal();
// Enumerate the hash, and add cookies to the params array.
mozIStorageAsyncStatement* stmt = self->mStmtInsert;
nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
stmt->NewBindingParamsArray(getter_AddRefs(paramsArray));
for (auto iter = self->mHostTable.Iter(); !iter.Done();
iter.Next()) {
CookieEntry* entry = iter.Get();
const CookieEntry::ArrayType& cookies = entry->GetCookies();
for (CookieEntry::IndexType i = 0; i < cookies.Length(); ++i) {
Cookie* cookie = cookies[i];
if (!cookie->IsSession()) {
BindCookieParameters(paramsArray, CookieKey(entry), cookie);
}
}
}
// 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(
LogLevel::Debug,
("RebuildCorruptDB(): nothing to write, rebuild complete"));
self->mCorruptFlag = CookiePersistentStorage::OK;
return;
}
self->MaybeStoreCookiesToDB(paramsArray);
});
NS_DispatchToMainThread(innerRunnable);
});
mThread->Dispatch(runnable, NS_DISPATCH_NORMAL);
}
void CookiePersistentStorage::HandleDBClosed() {
COOKIE_LOGSTRING(LogLevel::Debug,
("HandleDBClosed(): CookieStorage %p closed", this));
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
switch (mCorruptFlag) {
case CookiePersistentStorage::OK: {
// Database is healthy. Notify of closure.
if (os) {
os->NotifyObservers(nullptr, "cookie-db-closed", nullptr);
}
break;
}
case CookiePersistentStorage::CLOSING_FOR_REBUILD: {
// Our close finished. Start the rebuild, and notify of db closure later.
RebuildCorruptDB();
break;
}
case CookiePersistentStorage::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;
mCookieFile->Clone(getter_AddRefs(backupFile));
nsresult rv = backupFile->MoveToNative(
nullptr, nsLiteralCString(COOKIES_FILE ".bak-rebuild"));
COOKIE_LOGSTRING(LogLevel::Warning,
("HandleDBClosed(): CookieStorage %p encountered error "
"rebuilding db; move to "
"'cookies.sqlite.bak-rebuild' gave rv 0x%" PRIx32,
this, static_cast<uint32_t>(rv)));
if (os) {
os->NotifyObservers(nullptr, "cookie-db-closed", nullptr);
}
break;
}
}
}
CookiePersistentStorage::OpenDBResult CookiePersistentStorage::Read() {
MOZ_ASSERT(NS_GetCurrentThread() == mThread);
// Read in the data synchronously.
// see IDX_NAME, etc. for parameter indexes
nsCOMPtr<mozIStorageStatement> stmt;
nsresult rv =
mSyncConn->CreateStatement(nsLiteralCString("SELECT "
"name, "
"value, "
"host, "
"path, "
"expiry, "
"lastAccessed, "
"creationTime, "
"isSecure, "
"isHttpOnly, "
"originAttributes, "
"sameSite, "
"schemeMap, "
"isPartitionedAttributeSet, "
"updateTime "
"FROM moz_cookies"),
getter_AddRefs(stmt));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
if (NS_WARN_IF(!mReadArray.IsEmpty())) {
mReadArray.Clear();
}
mReadArray.SetCapacity(kMaxNumberOfCookies);
nsCString baseDomain;
nsCString name;
nsCString value;
nsCString host;
nsCString path;
bool hasResult;
while (true) {
rv = stmt->ExecuteStep(&hasResult);
if (NS_WARN_IF(NS_FAILED(rv))) {
mReadArray.Clear();
return RESULT_RETRY;
}
if (!hasResult) {
break;
}
stmt->GetUTF8String(IDX_HOST, host);
rv = CookieCommons::GetBaseDomainFromHost(mTLDService, host, baseDomain);
if (NS_FAILED(rv)) {
COOKIE_LOGSTRING(LogLevel::Debug,
("Read(): Ignoring invalid host '%s'", host.get()));
continue;
}
nsAutoCString suffix;
OriginAttributes attrs;
stmt->GetUTF8String(IDX_ORIGIN_ATTRIBUTES, suffix);
// If PopulateFromSuffix failed we just ignore the OA attributes
// that we don't support
(void)attrs.PopulateFromSuffix(suffix);
CookieKey key(baseDomain, attrs);
CookieDomainTuple* tuple = mReadArray.AppendElement();
tuple->key = std::move(key);
tuple->originAttributes = attrs;
tuple->cookie = GetCookieFromRow(stmt);
}
COOKIE_LOGSTRING(LogLevel::Debug,
("Read(): %zu cookies read", mReadArray.Length()));
return RESULT_OK;
}
// Extract data from a single result row and create an Cookie.
UniquePtr<CookieStruct> CookiePersistentStorage::GetCookieFromRow(
mozIStorageStatement* aRow) {
nsCString name;
nsCString value;
nsCString host;
nsCString path;
DebugOnly<nsresult> rv = aRow->GetUTF8String(IDX_NAME, name);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = aRow->GetUTF8String(IDX_VALUE, value);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = aRow->GetUTF8String(IDX_HOST, host);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = aRow->GetUTF8String(IDX_PATH, path);
MOZ_ASSERT(NS_SUCCEEDED(rv));
int64_t expiryInMSec = aRow->AsInt64(IDX_EXPIRY_INMSEC);
int64_t lastAccessedInUSec = aRow->AsInt64(IDX_LAST_ACCESSED_INUSEC);
int64_t creationTimeInUSec = aRow->AsInt64(IDX_CREATION_TIME_INUSEC);
int64_t updateTimeInUSec = aRow->AsInt64(IDX_UPDATE_TIME_INUSEC);
bool isSecure = 0 != aRow->AsInt32(IDX_SECURE);
bool isHttpOnly = 0 != aRow->AsInt32(IDX_HTTPONLY);
int32_t sameSite = aRow->AsInt32(IDX_SAME_SITE);
int32_t schemeMap = aRow->AsInt32(IDX_SCHEME_MAP);
bool isPartitionedAttributeSet =
0 != aRow->AsInt32(IDX_PARTITIONED_ATTRIBUTE_SET);
// Create a new constCookie and assign the data.
return MakeUnique<CookieStruct>(
name, value, host, path, expiryInMSec, lastAccessedInUSec,
creationTimeInUSec, updateTimeInUSec, isHttpOnly, false, isSecure,
isPartitionedAttributeSet, sameSite,
static_cast<nsICookie::schemeType>(schemeMap));
}
void CookiePersistentStorage::EnsureInitialized() {
MOZ_ASSERT(NS_IsMainThread());
bool isAccumulated = false;
if (!mInitialized) {
#ifndef ANDROID
TimeStamp startBlockTime = TimeStamp::Now();
#endif
MonitorAutoLock lock(mMonitor);
while (!mInitialized) {
mMonitor.Wait();
}
#ifndef ANDROID
TimeStamp endBlockTime = TimeStamp::Now();
mozilla::glean::networking::sqlite_cookies_block_main_thread
.AccumulateRawDuration(endBlockTime - startBlockTime);
mozilla::glean::networking::sqlite_cookies_time_to_block_main_thread
.AccumulateRawDuration(TimeDuration::Zero());
#endif
isAccumulated = true;
} else if (!mEndInitDBConn.IsNull()) {
// We didn't block main thread, and here comes the first cookie request.
// Collect how close we're going to block main thread.
#ifndef ANDROID
TimeStamp now = TimeStamp::Now();
mozilla::glean::networking::sqlite_cookies_time_to_block_main_thread
.AccumulateRawDuration(now - mEndInitDBConn);
#endif
// Nullify the timestamp so wo don't accumulate this telemetry probe again.
mEndInitDBConn = TimeStamp();
isAccumulated = true;
} else if (!mInitializedDBConn) {
// A request comes while we finished cookie thread task and InitDBConn is
// on the way from cookie thread to main thread. We're very close to block
// main thread.
#ifndef ANDROID
mozilla::glean::networking::sqlite_cookies_time_to_block_main_thread
.AccumulateRawDuration(TimeDuration::Zero());
#endif
isAccumulated = true;
}
if (!mInitializedDBConn) {
InitDBConn();
if (isAccumulated) {
// Nullify the timestamp so wo don't accumulate this telemetry probe
// again.
mEndInitDBConn = TimeStamp();
}
}
}
void CookiePersistentStorage::InitDBConn() {
MOZ_ASSERT(NS_IsMainThread());
// We should skip InitDBConn if we close profile during initializing
// CookieStorages and then InitDBConn is called after we close the
// CookieStorages.
if (!mInitialized || mInitializedDBConn) {
return;
}
nsCOMPtr<nsIURI> dummyUri;
nsresult rv = NS_NewURI(getter_AddRefs(dummyUri), "https://example.com");
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsTArray<RefPtr<Cookie>> cleanupCookies;
for (uint32_t i = 0; i < mReadArray.Length(); ++i) {
CookieDomainTuple& tuple = mReadArray[i];
MOZ_ASSERT(!tuple.cookie->isSession());
// filter invalid non-ipv4 host ending in number from old db values
nsCOMPtr<nsIURIMutator> outMut;
nsCOMPtr<nsIURIMutator> dummyMut;
rv = dummyUri->Mutate(getter_AddRefs(dummyMut));
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = dummyMut->SetHost(tuple.cookie->host(), getter_AddRefs(outMut));
if (NS_FAILED(rv)) {
COOKIE_LOGSTRING(LogLevel::Debug, ("Removing cookie from db with "
"newly invalid hostname: '%s'",
tuple.cookie->host().get()));
RefPtr<Cookie> cookie =
Cookie::Create(*tuple.cookie, tuple.originAttributes);
cleanupCookies.AppendElement(cookie);
continue;
}
// CreateValidated fixes up the creation and lastAccessed times.
// If the DB is corrupted and the timestaps are far away in the future
// we don't want the creation timestamp to update gLastCreationTimeInUSec
// as that would contaminate all the next creation times.
// We fix up these dates to not be later than the current time.
// The downside is that if the user sets the date far away in the past
// then back to the current date, those cookies will be stale,
// but if we don't fix their dates, those cookies might never be
// evicted.
RefPtr<Cookie> cookie =
Cookie::CreateValidated(*tuple.cookie, tuple.originAttributes);
// Clean up the invalid first-party partitioned cookies that don't have
// the 'partitioned' cookie attribution. This will also ensure that we don't
// read the cookie into memory.
if (CookieCommons::IsFirstPartyPartitionedCookieWithoutCHIPS(
cookie, tuple.key.mBaseDomain, tuple.key.mOriginAttributes)) {
// We cannot directly use the cookie after validation because the
// timestamps could be different from the cookies in DB. So, we need to
// create one from the cookie struct.
RefPtr<Cookie> invalidCookie =
Cookie::Create(*tuple.cookie, tuple.originAttributes);
cleanupCookies.AppendElement(invalidCookie);
continue;
}
AddCookieToList(tuple.key.mBaseDomain, tuple.key.mOriginAttributes, cookie);
}
if (NS_FAILED(InitDBConnInternal())) {
COOKIE_LOGSTRING(LogLevel::Warning,
("InitDBConn(): retrying InitDBConnInternal()"));
CleanupCachedStatements();
CleanupDBConnection();
if (NS_FAILED(InitDBConnInternal())) {
COOKIE_LOGSTRING(
LogLevel::Warning,
("InitDBConn(): InitDBConnInternal() failed, closing connection"));
// Game over, clean the connections.
CleanupCachedStatements();
CleanupDBConnection();
}
}
mInitializedDBConn = true;
COOKIE_LOGSTRING(LogLevel::Debug,
("InitDBConn(): mInitializedDBConn = true"));
mEndInitDBConn = TimeStamp::Now();
for (const auto& cookie : cleanupCookies) {
RemoveCookieFromDB(*cookie);
}
// We will have migrated CHIPS cookies if the pref is set, and .unset it
// to prevent duplicated work. This has to happen in the main thread though,
// so we waited to this point.
if (StaticPrefs::network_cookie_CHIPS_enabled()) {
Preferences::SetUint(
"network.cookie.CHIPS.lastMigrateDatabase",
StaticPrefs::network_cookie_CHIPS_migrateDatabaseTarget());
}
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (os) {
os->NotifyObservers(nullptr, "cookie-db-read", nullptr);
mReadArray.Clear();
}
// Let's count the valid/invalid cookies when in idle.
nsCOMPtr<nsIRunnable> idleRunnable = NS_NewRunnableFunction(
"CookiePersistentStorage::RecordValidationTelemetry",
[self = RefPtr{this}]() { self->RecordValidationTelemetry(); });
(void)NS_DispatchToMainThreadQueue(do_AddRef(idleRunnable),
EventQueuePriority::Idle);
}
nsresult CookiePersistentStorage::InitDBConnInternal() {
MOZ_ASSERT(NS_IsMainThread());
nsresult rv = mStorageService->OpenUnsharedDatabase(
mCookieFile, mozIStorageService::CONNECTION_DEFAULT,
getter_AddRefs(mDBConn));
NS_ENSURE_SUCCESS(rv, rv);
// Set up our listeners.
mInsertListener = new InsertCookieDBListener(this);
mUpdateListener = new UpdateCookieDBListener(this);
mRemoveListener = new RemoveCookieDBListener(this);
mCloseListener = new CloseCookieDBListener(this);
// Grow cookie db in 512KB increments
mDBConn->SetGrowthIncrement(512 * 1024, ""_ns);
// make operations on the table asynchronous, for performance
mDBConn->ExecuteSimpleSQL("PRAGMA synchronous = OFF"_ns);
// Use write-ahead-logging for performance. We cap the autocheckpoint limit at
// 16 pages (around 500KB).
mDBConn->ExecuteSimpleSQL(nsLiteralCString(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA journal_mode = WAL"));
mDBConn->ExecuteSimpleSQL("PRAGMA wal_autocheckpoint = 16"_ns);
// cache frequently used statements (for insertion, deletion, and updating)
rv = mDBConn->CreateAsyncStatement(
nsLiteralCString("INSERT INTO moz_cookies ("
"originAttributes, "
"name, "
"value, "
"host, "
"path, "
"expiry, "
"lastAccessed, "
"creationTime, "
"isSecure, "
"isHttpOnly, "
"sameSite, "
"schemeMap, "
"isPartitionedAttributeSet, "
"updateTime "
") VALUES ("
":originAttributes, "
":name, "
":value, "
":host, "
":path, "
":expiry, "
":lastAccessed, "
":creationTime, "
":isSecure, "
":isHttpOnly, "
":sameSite, "
":schemeMap, "
":isPartitionedAttributeSet, "
":updateTime "
")"),
getter_AddRefs(mStmtInsert));
NS_ENSURE_SUCCESS(rv, rv);
rv = mDBConn->CreateAsyncStatement(
nsLiteralCString("DELETE FROM moz_cookies "
"WHERE name = :name AND host = :host AND path = :path "
"AND originAttributes = :originAttributes"),
getter_AddRefs(mStmtDelete));
NS_ENSURE_SUCCESS(rv, rv);
rv = mDBConn->CreateAsyncStatement(
nsLiteralCString("UPDATE moz_cookies SET lastAccessed = :lastAccessed "
"WHERE name = :name AND host = :host AND path = :path "
"AND originAttributes = :originAttributes"),
getter_AddRefs(mStmtUpdate));
return rv;
}
// Sets the schema version and creates the moz_cookies table.
nsresult CookiePersistentStorage::CreateTableWorker(const char* aName) {
// Create the table.
// We default originAttributes to empty string: this is so if users revert to
// an older Firefox version that doesn't know about this field, any cookies
// set will still work once they upgrade back.
nsAutoCString command("CREATE TABLE ");
command.Append(aName);
command.AppendLiteral(
" ("
"id INTEGER PRIMARY KEY, "
"originAttributes TEXT NOT NULL DEFAULT '', "
"name TEXT, "
"value TEXT, "
"host TEXT, "
"path TEXT, "
"expiry INTEGER, "
"lastAccessed INTEGER, "
"creationTime INTEGER, "
"isSecure INTEGER, "
"isHttpOnly INTEGER, "
"inBrowserElement INTEGER DEFAULT 0, "
"sameSite INTEGER DEFAULT 0, "
"schemeMap INTEGER DEFAULT 0, "
"isPartitionedAttributeSet INTEGER DEFAULT 0, "
"updateTime INTEGER, "
"CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes)"
")");
return mSyncConn->ExecuteSimpleSQL(command);
}
// Sets the schema version and creates the moz_cookies table.
nsresult CookiePersistentStorage::CreateTable() {
// Set the schema version, before creating the table.
nsresult rv = mSyncConn->SetSchemaVersion(COOKIES_SCHEMA_VERSION);
if (NS_FAILED(rv)) {
return rv;
}
rv = CreateTableWorker("moz_cookies");
if (NS_FAILED(rv)) {
return rv;
}
return NS_OK;
}
// Sets the schema version and creates the moz_cookies table.
nsresult CookiePersistentStorage::CreateTableForSchemaVersion6() {
// Set the schema version, before creating the table.
nsresult rv = mSyncConn->SetSchemaVersion(6);
if (NS_FAILED(rv)) {
return rv;
}
// Create the table.
// We default originAttributes to empty string: this is so if users revert to
// an older Firefox version that doesn't know about this field, any cookies
// set will still work once they upgrade back.
rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"CREATE TABLE moz_cookies ("
"id INTEGER PRIMARY KEY, "
"baseDomain TEXT, "
"originAttributes TEXT NOT NULL DEFAULT '', "
"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, originAttributes)"
")"));
if (NS_FAILED(rv)) {
return rv;
}
// Create an index on baseDomain.
return mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, "
"originAttributes)"));
}
// Sets the schema version and creates the moz_cookies table.
nsresult CookiePersistentStorage::CreateTableForSchemaVersion5() {
// Set the schema version, before creating the table.
nsresult rv = mSyncConn->SetSchemaVersion(5);
if (NS_FAILED(rv)) {
return rv;
}
// Create the table. We default appId/inBrowserElement to 0: this is so if
// users revert to an older Firefox version that doesn't know about these
// fields, any cookies set will still work once they upgrade back.
rv = mSyncConn->ExecuteSimpleSQL(
nsLiteralCString("CREATE TABLE moz_cookies ("
"id INTEGER PRIMARY KEY, "
"baseDomain TEXT, "
"appId INTEGER DEFAULT 0, "
"inBrowserElement INTEGER DEFAULT 0, "
"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, "
"appId, inBrowserElement)"
")"));
if (NS_FAILED(rv)) {
return rv;
}
// Create an index on baseDomain.
return mSyncConn->ExecuteSimpleSQL(nsLiteralCString(
"CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, "
"appId, "
"inBrowserElement)"));
}
nsresult CookiePersistentStorage::RunInTransaction(
nsICookieTransactionCallback* aCallback) {
if (NS_WARN_IF(!mDBConn)) {
return NS_ERROR_NOT_AVAILABLE;
}
mozStorageTransaction transaction(mDBConn, true);
// XXX Handle the error, bug 1696130.
(void)NS_WARN_IF(NS_FAILED(transaction.Start()));
if (NS_FAILED(aCallback->Callback())) {
(void)transaction.Rollback();
return NS_ERROR_FAILURE;
}
return NS_OK;
}
// purges expired and old cookies in a batch operation.
already_AddRefed<nsIArray> CookiePersistentStorage::PurgeCookies(
int64_t aCurrentTimeInUsec, uint16_t aMaxNumberOfCookies,
int64_t aCookiePurgeAge) {
// 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.
nsCOMPtr<mozIStorageBindingParamsArray> paramsArray;
if (mDBConn) {
mStmtDelete->NewBindingParamsArray(getter_AddRefs(paramsArray));
}
RefPtr<CookiePersistentStorage> self = this;
return PurgeCookiesWithCallbacks(
aCurrentTimeInUsec, aMaxNumberOfCookies, aCookiePurgeAge,
[paramsArray, self](const CookieListIter& aIter) {
self->PrepareCookieRemoval(*aIter.Cookie(), paramsArray);
self->RemoveCookieFromListInternal(aIter);
},
[paramsArray, self]() {
if (paramsArray) {
self->DeleteFromDB(paramsArray);
}
});
}
void CookiePersistentStorage::CollectCookieJarSizeData() {
COOKIE_LOGSTRING(LogLevel::Debug,
("CookiePersistentStorage::CollectCookieJarSizeData"));
uint32_t sumPartitioned = 0;
uint32_t sumUnpartitioned = 0;
for (const auto& cookieEntry : mHostTable) {
if (cookieEntry.IsPartitioned()) {
uint16_t cePartitioned = cookieEntry.GetCookies().Length();
sumPartitioned += cePartitioned;
mozilla::glean::networking::cookie_count_part_by_key
.AccumulateSingleSample(cePartitioned);
} else {
uint16_t ceUnpartitioned = cookieEntry.GetCookies().Length();
sumUnpartitioned += ceUnpartitioned;
mozilla::glean::networking::cookie_count_unpart_by_key
.AccumulateSingleSample(ceUnpartitioned);
}
}
mozilla::glean::networking::cookie_count_total.AccumulateSingleSample(
mCookieCount);
mozilla::glean::networking::cookie_count_partitioned.AccumulateSingleSample(
sumPartitioned);
mozilla::glean::networking::cookie_count_unpartitioned.AccumulateSingleSample(
sumUnpartitioned);
}
void CookiePersistentStorage::RecordValidationTelemetry() {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<CookieService> cs = CookieService::GetSingleton();
if (!cs) {
// We are shutting down, or something bad is happening.
return;
}
struct CookieToAddOrRemove {
nsCString mBaseDomain;
OriginAttributes mOriginAttributes;
RefPtr<Cookie> mCookie;
};
nsTArray<CookieToAddOrRemove> listToAdd;
nsTArray<CookieToAddOrRemove> listToRemove;
for (const auto& entry : mHostTable) {
const CookieEntry::ArrayType& cookies = entry.GetCookies();
for (CookieEntry::IndexType i = 0; i < cookies.Length(); ++i) {
Cookie* cookie = cookies[i];
RefPtr<CookieValidation> validation =
CookieValidation::Validate(cookie->ToIPC());
mozilla::glean::networking::cookie_db_validation
.Get(ValidationErrorToLabel(validation->Result()))
.Add(1);
// We are unable to recover from all the possible errors. Let's fix the
// most common ones.
switch (validation->Result()) {
case nsICookieValidation::eRejectedNoneRequiresSecure: {
RefPtr<Cookie> newCookie =
Cookie::Create(cookie->ToIPC(), entry.mOriginAttributes);
MOZ_ASSERT(newCookie);
newCookie->SetSameSite(nsICookie::SAMESITE_UNSET);
newCookie->SetCreationTimeInUSec(cookie->CreationTimeInUSec());
listToAdd.AppendElement(CookieToAddOrRemove{
entry.mBaseDomain, entry.mOriginAttributes, newCookie});
break;
}
case nsICookieValidation::eRejectedAttributeExpiryOversize: {
RefPtr<Cookie> newCookie =
Cookie::Create(cookie->ToIPC(), entry.mOriginAttributes);
MOZ_ASSERT(newCookie);
int64_t currentTimeInMSec = PR_Now() / PR_USEC_PER_MSEC;
newCookie->SetExpiryInMSec(CookieCommons::MaybeCapExpiry(
currentTimeInMSec, cookie->ExpiryInMSec()));
newCookie->SetCreationTimeInUSec(cookie->CreationTimeInUSec());
listToAdd.AppendElement(CookieToAddOrRemove{
entry.mBaseDomain, entry.mOriginAttributes, newCookie});
break;
}
case nsICookieValidation::eRejectedEmptyNameAndValue:
[[fallthrough]];
case nsICookieValidation::eRejectedInvalidCharName:
[[fallthrough]];
case nsICookieValidation::eRejectedInvalidCharValue:
listToRemove.AppendElement(CookieToAddOrRemove{
entry.mBaseDomain, entry.mOriginAttributes, cookie});
break;
default:
// Nothing to do here.
break;
}
}
}
for (CookieToAddOrRemove& data : listToAdd) {
AddCookie(nullptr, data.mBaseDomain, data.mOriginAttributes, data.mCookie,
data.mCookie->CreationTimeInUSec(), nullptr, VoidCString(), true,
!data.mOriginAttributes.mPartitionKey.IsEmpty(), nullptr,
nullptr);
}
for (CookieToAddOrRemove& data : listToRemove) {
RemoveCookie(data.mBaseDomain, data.mOriginAttributes, data.mCookie->Host(),
data.mCookie->Name(), data.mCookie->Path(),
/* is http: */ true, nullptr);
}
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (os) {
os->NotifyObservers(nullptr, "cookies-validated", nullptr);
}
}
} // namespace net
} // namespace mozilla
|