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
|
/*
* Copyright (C) 2021 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "NetworkStorageManager.h"
#include "BackgroundFetchChange.h"
#include "BackgroundFetchStoreManager.h"
#include "CacheStorageCache.h"
#include "CacheStorageDiskStore.h"
#include "CacheStorageManager.h"
#include "CacheStorageRegistry.h"
#include "FileSystemStorageHandleRegistry.h"
#include "FileSystemStorageManager.h"
#include "IDBStorageConnectionToClient.h"
#include "IDBStorageManager.h"
#include "IDBStorageRegistry.h"
#include "LocalStorageManager.h"
#include "Logging.h"
#include "NetworkConnectionToWebProcess.h"
#include "NetworkProcess.h"
#include "NetworkProcessProxyMessages.h"
#include "NetworkStorageManagerMessages.h"
#include "OriginQuotaManager.h"
#include "OriginStorageManager.h"
#include "ServiceWorkerStorageManager.h"
#include "SessionStorageManager.h"
#include "StorageAreaBase.h"
#include "StorageAreaMapMessages.h"
#include "StorageAreaRegistry.h"
#include "UnifiedOriginStorageLevel.h"
#include "WebsiteDataType.h"
#include <WebCore/DOMCacheEngine.h>
#include <WebCore/IDBRequestData.h>
#include <WebCore/SecurityOriginData.h>
#include <WebCore/ServiceWorkerContextData.h>
#include <WebCore/StorageUtilities.h>
#include <WebCore/UniqueIDBDatabaseConnection.h>
#include <WebCore/UniqueIDBDatabaseTransaction.h>
#include <pal/crypto/CryptoDigest.h>
#include <wtf/SuspendableWorkQueue.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/Base64.h>
#include <wtf/text/MakeString.h>
#define MESSAGE_CHECK(assertion, connection) MESSAGE_CHECK_BASE(assertion, connection)
#define MESSAGE_CHECK_COMPLETION(assertion, connection, completion) MESSAGE_CHECK_COMPLETION_BASE(assertion, connection, completion)
namespace WebKit {
#if PLATFORM(IOS_FAMILY)
static const Seconds defaultBackupExclusionPeriod { 24_h };
#endif
static constexpr double defaultThirdPartyOriginQuotaRatio = 0.1; // third-party_origin_quota / origin_quota
static constexpr uint64_t defaultVolumeCapacityUnit = 1 * GB;
static constexpr auto persistedFileName = "persisted"_s;
static constexpr Seconds originLastModificationTimeUpdateInterval = 30_s;
// FIXME: Remove this if rdar://104754030 is fixed.
static HashMap<String, ThreadSafeWeakPtr<NetworkStorageManager>>& activePaths()
{
static MainThreadNeverDestroyed<HashMap<String, ThreadSafeWeakPtr<NetworkStorageManager>>> pathToManagerMap;
return pathToManagerMap;
}
static String encode(const String& string, FileSystem::Salt salt)
{
auto crypto = PAL::CryptoDigest::create(PAL::CryptoDigest::Algorithm::SHA_256);
auto utf8String = string.utf8();
crypto->addBytes(byteCast<uint8_t>(utf8String.span()));
crypto->addBytes(salt);
return base64URLEncodeToString(crypto->computeHash());
}
static String originDirectoryPath(const String& rootPath, const WebCore::ClientOrigin& origin, FileSystem::Salt salt)
{
if (rootPath.isEmpty())
return emptyString();
auto encodedTopOrigin = encode(origin.topOrigin.toString(), salt);
auto encodedOpeningOrigin = encode(origin.clientOrigin.toString(), salt);
return FileSystem::pathByAppendingComponents(rootPath, { encodedTopOrigin, encodedOpeningOrigin });
}
static String originFilePath(const String& directory)
{
if (directory.isEmpty())
return emptyString();
return FileSystem::pathByAppendingComponent(directory, OriginStorageManager::originFileIdentifier());
}
static bool isEmptyOriginDirectory(const String& directory)
{
auto children = FileSystem::listDirectory(directory);
if (children.isEmpty())
return true;
if (children.size() >= 2)
return false;
HashSet<String> invalidFileNames {
OriginStorageManager::originFileIdentifier()
#if PLATFORM(COCOA)
, ".DS_Store"_s
#endif
};
return WTF::allOf(children, [&] (auto& child) {
return invalidFileNames.contains(child);
});
}
static void deleteEmptyOriginDirectory(const String& directory)
{
if (directory.isEmpty())
return;
if (isEmptyOriginDirectory(directory))
FileSystem::deleteFile(originFilePath(directory));
FileSystem::deleteEmptyDirectory(directory);
FileSystem::deleteEmptyDirectory(FileSystem::parentPath(directory));
}
WTF_MAKE_TZONE_ALLOCATED_IMPL(NetworkStorageManager);
String NetworkStorageManager::persistedFilePath(const WebCore::ClientOrigin& origin)
{
auto directory = originDirectoryPath(m_path, origin, m_salt);
if (directory.isEmpty())
return emptyString();
return FileSystem::pathByAppendingComponent(directory, persistedFileName);
}
Ref<NetworkStorageManager> NetworkStorageManager::create(NetworkProcess& process, PAL::SessionID sessionID, Markable<WTF::UUID> identifier, std::optional<IPC::Connection::UniqueID> connection, const String& path, const String& customLocalStoragePath, const String& customIDBStoragePath, const String& customCacheStoragePath, const String& customServiceWorkerStoragePath, uint64_t defaultOriginQuota, std::optional<double> originQuotaRatio, std::optional<double> totalQuotaRatio, std::optional<uint64_t> standardVolumeCapacity, std::optional<uint64_t> volumeCapacityOverride, UnifiedOriginStorageLevel level, bool storageSiteValidationEnabled)
{
return adoptRef(*new NetworkStorageManager(process, sessionID, identifier, connection, path, customLocalStoragePath, customIDBStoragePath, customCacheStoragePath, customServiceWorkerStoragePath, defaultOriginQuota, originQuotaRatio, totalQuotaRatio, standardVolumeCapacity, volumeCapacityOverride, level, storageSiteValidationEnabled));
}
static ASCIILiteral queueName(PAL::SessionID sessionID)
{
if (sessionID.isEphemeral())
return "com.apple.WebKit.Storage.ephemeral"_s;
return "com.apple.WebKit.Storage.persistent"_s;
}
NetworkStorageManager::NetworkStorageManager(NetworkProcess& process, PAL::SessionID sessionID, Markable<WTF::UUID> identifier, std::optional<IPC::Connection::UniqueID> connection, const String& path, const String& customLocalStoragePath, const String& customIDBStoragePath, const String& customCacheStoragePath, const String& customServiceWorkerStoragePath, uint64_t defaultOriginQuota, std::optional<double> originQuotaRatio, std::optional<double> totalQuotaRatio, std::optional<uint64_t> standardVolumeCapacity, std::optional<uint64_t> volumeCapacityOverride, UnifiedOriginStorageLevel level, bool storageSiteValidationEnabled)
: m_process(process)
, m_sessionID(sessionID)
, m_queue(SuspendableWorkQueue::create(queueName(sessionID), SuspendableWorkQueue::QOS::Default, SuspendableWorkQueue::ShouldLog::Yes))
, m_parentConnection(connection)
{
ASSERT(RunLoop::isMain());
if (!path.isEmpty()) {
auto addResult = activePaths().add(path, *this);
if (!addResult.isNewEntry) {
if (auto existingManager = addResult.iterator->value.get())
RELEASE_LOG_ERROR(Storage, "%p - NetworkStorageManager::NetworkStorageManager path for session %" PRIu64 " is already in use by session %" PRIu64, this, m_sessionID.toUInt64(), existingManager->sessionID().toUInt64());
else
addResult.iterator->value = *this;
}
}
m_pathNormalizedMainThread = FileSystem::lexicallyNormal(path);
m_customIDBStoragePathNormalizedMainThread = FileSystem::lexicallyNormal(customIDBStoragePath);
protectedWorkQueue()->dispatch([this, weakThis = ThreadSafeWeakPtr { *this }, path = path.isolatedCopy(), customLocalStoragePath = crossThreadCopy(customLocalStoragePath), customIDBStoragePath = crossThreadCopy(customIDBStoragePath), customCacheStoragePath = crossThreadCopy(customCacheStoragePath), customServiceWorkerStoragePath = crossThreadCopy(customServiceWorkerStoragePath), defaultOriginQuota, originQuotaRatio, totalQuotaRatio, standardVolumeCapacity, volumeCapacityOverride, level, storageSiteValidationEnabled]() mutable {
assertIsCurrent(workQueue());
auto protectedThis = weakThis.get();
if (!protectedThis)
return;
m_defaultOriginQuota = defaultOriginQuota;
m_originQuotaRatio = originQuotaRatio;
m_totalQuotaRatio = totalQuotaRatio;
m_standardVolumeCapacity = standardVolumeCapacity;
m_volumeCapacityOverride = volumeCapacityOverride;
#if PLATFORM(IOS_FAMILY)
m_backupExclusionPeriod = defaultBackupExclusionPeriod;
#endif
setStorageSiteValidationEnabledInternal(storageSiteValidationEnabled);
m_fileSystemStorageHandleRegistry = FileSystemStorageHandleRegistry::create();
m_storageAreaRegistry = makeUnique<StorageAreaRegistry>();
m_idbStorageRegistry = makeUnique<IDBStorageRegistry>();
m_cacheStorageRegistry = CacheStorageRegistry::create();
m_unifiedOriginStorageLevel = level;
m_path = path;
m_customLocalStoragePath = customLocalStoragePath;
m_customIDBStoragePath = customIDBStoragePath;
m_customCacheStoragePath = customCacheStoragePath;
m_customServiceWorkerStoragePath = customServiceWorkerStoragePath;
if (!m_path.isEmpty()) {
auto saltPath = FileSystem::pathByAppendingComponent(m_path, "salt"_s);
m_salt = valueOrDefault(FileSystem::readOrMakeSalt(saltPath));
}
if (shouldManageServiceWorkerRegistrationsByOrigin())
migrateServiceWorkerRegistrationsToOrigins();
else
m_sharedServiceWorkerStorageManager = makeUnique<ServiceWorkerStorageManager>(m_customServiceWorkerStoragePath);
#if PLATFORM(IOS_FAMILY)
// Exclude LocalStorage directory to reduce backup traffic. See https://webkit.org/b/168388.
if (m_unifiedOriginStorageLevel == UnifiedOriginStorageLevel::None && !m_customLocalStoragePath.isEmpty()) {
FileSystem::makeAllDirectories(m_customLocalStoragePath);
FileSystem::setExcludedFromBackup(m_customLocalStoragePath, true);
}
#endif
IDBStorageManager::createVersionDirectoryIfNeeded(m_customIDBStoragePath);
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis)] { });
});
}
NetworkStorageManager::~NetworkStorageManager()
{
ASSERT(RunLoop::isMain());
ASSERT(m_closed);
}
RefPtr<NetworkProcess> NetworkStorageManager::protectedProcess() const
{
return m_process.get();
}
bool NetworkStorageManager::canHandleTypes(OptionSet<WebsiteDataType> types)
{
return allManagedTypes().containsAny(types);
}
OptionSet<WebsiteDataType> NetworkStorageManager::allManagedTypes()
{
return {
WebsiteDataType::LocalStorage,
WebsiteDataType::SessionStorage,
WebsiteDataType::FileSystem,
WebsiteDataType::IndexedDBDatabases,
WebsiteDataType::DOMCache,
WebsiteDataType::ServiceWorkerRegistrations
};
}
void NetworkStorageManager::close(CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
m_closed = true;
m_connections.forEach([] (auto& connection) {
connection.removeWorkQueueMessageReceiver(Messages::NetworkStorageManager::messageReceiverName());
});
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
m_originStorageManagers.clear();
m_fileSystemStorageHandleRegistry = nullptr;
for (auto&& completionHandler : std::exchange(m_persistCompletionHandlers, { }))
completionHandler.second(false);
m_sharedServiceWorkerStorageManager = nullptr;
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler();
});
});
}
void NetworkStorageManager::startReceivingMessageFromConnection(IPC::Connection& connection, const Vector<WebCore::RegistrableDomain>& allowedSites, const SharedPreferencesForWebProcess& preferences)
{
ASSERT(RunLoop::isMain());
connection.addWorkQueueMessageReceiver(Messages::NetworkStorageManager::messageReceiverName(), m_queue.get(), *this);
m_connections.add(connection);
addAllowedSitesForConnection(connection.uniqueID(), allowedSites);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, connection = connection.uniqueID(), preferences]() mutable {
assertIsCurrent(workQueue());
ASSERT(!m_preferencesForConnections.contains(connection));
m_preferencesForConnections.add(connection, preferences);
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis)] { });
});
}
void NetworkStorageManager::stopReceivingMessageFromConnection(IPC::Connection& connection)
{
ASSERT(RunLoop::isMain());
if (!m_connections.remove(connection))
return;
connection.removeWorkQueueMessageReceiver(Messages::NetworkStorageManager::messageReceiverName());
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, connection = connection.uniqueID()]() mutable {
assertIsCurrent(workQueue());
m_idbStorageRegistry->removeConnectionToClient(connection);
m_originStorageManagers.removeIf([&](auto& entry) {
auto& manager = entry.value;
manager->connectionClosed(connection);
bool shouldRemove = !manager->isActive() && !manager->hasDataInMemory();
if (shouldRemove) {
manager->deleteEmptyDirectory();
deleteEmptyOriginDirectory(manager->path());
}
return shouldRemove;
});
m_temporaryBlobPathsByConnection.remove(connection);
if (m_allowedSitesForConnections)
m_allowedSitesForConnections->remove(connection);
ASSERT(m_preferencesForConnections.contains(connection));
m_preferencesForConnections.remove(connection);
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis)] { });
});
}
void NetworkStorageManager::updateSharedPreferencesForConnection(IPC::Connection& connection, const SharedPreferencesForWebProcess& preferences)
{
ASSERT(RunLoop::isMain());
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, connection = connection.uniqueID(), preferences]() mutable {
assertIsCurrent(workQueue());
if (auto iter = m_preferencesForConnections.find(connection); iter != m_preferencesForConnections.end())
iter->value = preferences;
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis)] { });
});
}
#if PLATFORM(IOS_FAMILY)
void NetworkStorageManager::includeOriginInBackupIfNecessary(OriginStorageManager& manager)
{
if (manager.includedInBackup())
return;
auto originFileCreationTimestamp = manager.originFileCreationTimestamp();
if (!originFileCreationTimestamp)
return;
if (WallTime::now() - originFileCreationTimestamp.value() < m_backupExclusionPeriod)
return;
FileSystem::setExcludedFromBackup(manager.path(), false);
manager.markIncludedInBackup();
}
#endif
void NetworkStorageManager::writeOriginToFileIfNecessary(const WebCore::ClientOrigin& origin, StorageAreaBase* storageArea)
{
assertIsCurrent(workQueue());
auto* manager = m_originStorageManagers.get(origin);
if (!manager)
return;
if (manager->originFileCreationTimestamp()) {
#if PLATFORM(IOS_FAMILY)
includeOriginInBackupIfNecessary(*manager);
#endif
return;
}
auto originDirectory = manager->path();
if (originDirectory.isEmpty())
return;
if (storageArea && isEmptyOriginDirectory(originDirectory))
return;
auto originFile = originFilePath(originDirectory);
bool didWrite = WebCore::StorageUtilities::writeOriginToFile(originFile, origin);
auto timestamp = FileSystem::fileCreationTime(originFile);
manager->setOriginFileCreationTimestamp(timestamp);
#if PLATFORM(IOS_FAMILY)
if (didWrite)
FileSystem::setExcludedFromBackup(originDirectory, true);
else
includeOriginInBackupIfNecessary(*manager);
#else
UNUSED_PARAM(didWrite);
#endif
}
void NetworkStorageManager::spaceGrantedForOrigin(const WebCore::ClientOrigin& origin, uint64_t amount)
{
assertIsCurrent(workQueue());
updateLastModificationTimeForOrigin(origin);
if (!m_totalQuotaRatio)
return;
if (!m_totalQuota) {
std::optional<uint64_t> volumeCapacity;
if (m_volumeCapacityOverride)
volumeCapacity = m_volumeCapacityOverride;
else if (auto capacity = FileSystem::volumeCapacity(m_path))
volumeCapacity = WTF::roundUpToMultipleOf(defaultVolumeCapacityUnit, *capacity);
if (volumeCapacity)
m_totalQuota = *m_totalQuotaRatio * *volumeCapacity;
else
return;
}
if (m_totalUsage)
m_totalUsage = *m_totalUsage + amount;
if (!m_totalUsage || *m_totalUsage > *m_totalQuota)
schedulePerformEviction();
}
void NetworkStorageManager::schedulePerformEviction()
{
assertIsCurrent(workQueue());
if (m_isEvictionScheduled)
return;
m_isEvictionScheduled = true;
prepareForEviction();
}
void NetworkStorageManager::prepareForEviction()
{
assertIsCurrent(workQueue());
RunLoop::protectedMain()->dispatch([this, weakThis = ThreadSafeWeakPtr { *this }]() mutable {
auto protectedThis = weakThis.get();
if (!protectedThis || m_closed || !m_process)
return;
protectedProcess()->registrableDomainsWithLastAccessedTime(m_sessionID, [this, weakThis = WTFMove(weakThis)](auto result) mutable {
auto protectedThis = weakThis.get();
if (!protectedThis || m_closed)
return;
protectedWorkQueue()->dispatch([weakThis = WTFMove(weakThis), result = crossThreadCopy(WTFMove(result))]() mutable {
if (auto protectedThis = weakThis.get()) {
protectedThis->donePrepareForEviction(WTFMove(result));
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis)] { });
}
});
});
});
}
WallTime NetworkStorageManager::lastModificationTimeForOrigin(const WebCore::ClientOrigin& origin, OriginStorageManager& manager) const
{
WallTime lastModificationTime;
switch (m_unifiedOriginStorageLevel) {
case UnifiedOriginStorageLevel::None: {
auto localStoragePath = LocalStorageManager::localStorageFilePath(m_customLocalStoragePath, origin);
auto localStorageModificationTime = valueOrDefault(FileSystem::fileModificationTime(localStoragePath));
lastModificationTime = std::max(localStorageModificationTime, lastModificationTime);
auto idbStoragePath = IDBStorageManager::idbStorageOriginDirectory(m_customIDBStoragePath, origin);
auto idbStorageModificationTime = valueOrDefault(FileSystem::fileModificationTime(idbStoragePath));
lastModificationTime = std::max(idbStorageModificationTime, lastModificationTime);
FALLTHROUGH;
}
case UnifiedOriginStorageLevel::Basic: {
auto cacheStoragePath = CacheStorageManager::cacheStorageOriginDirectory(m_customCacheStoragePath, origin);
auto cacheStorageModificationTime = valueOrDefault(FileSystem::fileModificationTime(cacheStoragePath));
lastModificationTime = std::max(cacheStorageModificationTime, lastModificationTime);
FALLTHROUGH;
}
case UnifiedOriginStorageLevel::Standard: {
auto originFile = originFilePath(manager.path());
auto originFileModificationTime = valueOrDefault(FileSystem::fileModificationTime(originFile));
lastModificationTime = std::max(originFileModificationTime, lastModificationTime);
}
}
return lastModificationTime;
}
void NetworkStorageManager::donePrepareForEviction(const std::optional<HashMap<WebCore::RegistrableDomain, WallTime>>& domainsWithLastAccessedTime)
{
assertIsCurrent(workQueue());
HashMap<WebCore::SecurityOriginData, AccessRecord> originRecords;
uint64_t totalUsage = 0;
for (auto& origin : getAllOrigins()) {
auto usage = checkedOriginStorageManager(origin)->protectedQuotaManager()->usage();
totalUsage += usage;
WallTime accessTime;
if (domainsWithLastAccessedTime)
accessTime = domainsWithLastAccessedTime->get(WebCore::RegistrableDomain { origin.topOrigin });
else
accessTime = lastModificationTimeForOrigin(origin, checkedOriginStorageManager(origin));
auto& record = originRecords.ensure(origin.topOrigin, [&] {
return AccessRecord { };
}).iterator->value;
record.usage += usage;
if (record.lastAccessTime < accessTime)
record.lastAccessTime = accessTime;
record.clientOrigins.append(origin.clientOrigin);
bool removed = removeOriginStorageManagerIfPossible(origin);
if (!removed)
record.isActive = true;
if (!record.isPersisted && persistedInternal(WebCore::ClientOrigin { origin.topOrigin, origin.topOrigin }))
record.isPersisted = true;
}
m_totalUsage = totalUsage;
performEviction(WTFMove(originRecords));
}
void NetworkStorageManager::performEviction(HashMap<WebCore::SecurityOriginData, AccessRecord>&& originRecords)
{
assertIsCurrent(workQueue());
m_isEvictionScheduled = false;
ASSERT(m_totalQuota);
if (!m_totalUsage || *m_totalUsage <= *m_totalQuota)
return;
Vector<std::pair<WebCore::SecurityOriginData, AccessRecord>> sortedOriginRecords;
for (auto&& [origin, record] : originRecords)
sortedOriginRecords.append({ WTFMove(origin), WTFMove(record) });
std::sort(sortedOriginRecords.begin(), sortedOriginRecords.end(), [&](const auto& a, const auto& b) {
return a.second.lastAccessTime > b.second.lastAccessTime;
});
uint64_t deletedOriginCount = 0;
while (!sortedOriginRecords.isEmpty() && *m_totalUsage > *m_totalQuota) {
auto [topOrigin, record] = sortedOriginRecords.takeLast();
if (record.isActive || valueOrDefault(record.isPersisted))
continue;
for (auto& clientOrigin : record.clientOrigins) {
auto origin = WebCore::ClientOrigin { topOrigin, clientOrigin };
checkedOriginStorageManager(origin)->deleteData(allManagedTypes(), -WallTime::infinity());
removeOriginStorageManagerIfPossible(origin);
}
m_totalUsage = *m_totalUsage - record.usage;
++deletedOriginCount;
}
UNUSED_PARAM(deletedOriginCount);
RELEASE_LOG(Storage, "%p - NetworkStorageManager::performEviction evicts %" PRIu64 " origins, current usage %" PRIu64 ", total quota %" PRIu64, this, deletedOriginCount, valueOrDefault(m_totalUsage), *m_totalQuota);
}
Ref<SuspendableWorkQueue> NetworkStorageManager::protectedWorkQueue() const
{
return m_queue;
}
OriginQuotaManager::Parameters NetworkStorageManager::originQuotaManagerParameters(const WebCore::ClientOrigin& origin)
{
OriginQuotaManager::IncreaseQuotaFunction increaseQuotaFunction = [sessionID = m_sessionID, origin, connection = m_parentConnection] (auto identifier, auto currentQuota, auto currentUsage, auto requestedIncrease) mutable {
if (connection)
IPC::Connection::send(*connection, Messages::NetworkProcessProxy::IncreaseQuota(sessionID, origin, identifier, currentQuota, currentUsage, requestedIncrease), 0);
};
// Use double for multiplication to preserve precision.
double quota = m_defaultOriginQuota;
double standardReportedQuota = m_standardVolumeCapacity ? *m_standardVolumeCapacity : 0.0;
if (m_originQuotaRatio && m_originQuotaRatioEnabled) {
std::optional<uint64_t> volumeCapacity;
if (m_volumeCapacityOverride)
volumeCapacity = m_volumeCapacityOverride;
else if (auto capacity = FileSystem::volumeCapacity(m_path))
volumeCapacity = WTF::roundUpToMultipleOf(defaultVolumeCapacityUnit, *capacity);
if (volumeCapacity) {
quota = m_originQuotaRatio.value() * volumeCapacity.value();
increaseQuotaFunction = { };
}
standardReportedQuota *= m_originQuotaRatio.value();
}
if (origin.topOrigin != origin.clientOrigin) {
quota *= defaultThirdPartyOriginQuotaRatio;
standardReportedQuota *= defaultThirdPartyOriginQuotaRatio;
}
OriginQuotaManager::NotifySpaceGrantedFunction notifySpaceGrantedFunction = [weakThis = ThreadSafeWeakPtr { *this }, origin](uint64_t spaceRequested) {
if (auto protectedThis = weakThis.get()) {
protectedThis->spaceGrantedForOrigin(origin, spaceRequested);
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis)] { });
}
};
// Use std::ceil instead of implicit conversion to make result more definitive.
uint64_t roundedQuota = std::ceil(quota);
uint64_t roundedStandardReportedQuota = std::ceil(standardReportedQuota);
return { roundedQuota, roundedStandardReportedQuota, WTFMove(increaseQuotaFunction), WTFMove(notifySpaceGrantedFunction) };
}
OriginStorageManager& NetworkStorageManager::originStorageManager(const WebCore::ClientOrigin& origin, ShouldWriteOriginFile shouldWriteOriginFile)
{
assertIsCurrent(workQueue());
auto& originStorageManager = *m_originStorageManagers.ensure(origin, [&] {
auto originDirectory = originDirectoryPath(m_path, origin, m_salt);
auto localStoragePath = LocalStorageManager::localStorageFilePath(m_customLocalStoragePath, origin);
auto idbStoragePath = IDBStorageManager::idbStorageOriginDirectory(m_customIDBStoragePath, origin);
auto cacheStoragePath = CacheStorageManager::cacheStorageOriginDirectory(m_customCacheStoragePath, origin);
CacheStorageManager::copySaltFileToOriginDirectory(m_customCacheStoragePath, cacheStoragePath);
OriginQuotaManager::IncreaseQuotaFunction increaseQuotaFunction = [sessionID = m_sessionID, origin, connection = m_parentConnection] (auto identifier, auto currentQuota, auto currentUsage, auto requestedIncrease) mutable {
if (connection)
IPC::Connection::send(*connection, Messages::NetworkProcessProxy::IncreaseQuota(sessionID, origin, identifier, currentQuota, currentUsage, requestedIncrease), 0);
};
return makeUnique<OriginStorageManager>(originQuotaManagerParameters(origin), WTFMove(originDirectory), WTFMove(localStoragePath), WTFMove(idbStoragePath), WTFMove(cacheStoragePath), m_unifiedOriginStorageLevel);
}).iterator->value;
if (shouldWriteOriginFile == ShouldWriteOriginFile::Yes)
writeOriginToFileIfNecessary(origin);
return originStorageManager;
}
bool NetworkStorageManager::removeOriginStorageManagerIfPossible(const WebCore::ClientOrigin& origin)
{
assertIsCurrent(workQueue());
auto iterator = m_originStorageManagers.find(origin);
if (iterator == m_originStorageManagers.end())
return true;
auto& manager = iterator->value;
if (manager->isActive() || manager->hasDataInMemory())
return false;
manager->deleteEmptyDirectory();
deleteEmptyOriginDirectory(manager->path());
m_originStorageManagers.remove(iterator);
return true;
}
void NetworkStorageManager::updateLastModificationTimeForOrigin(const WebCore::ClientOrigin& origin)
{
assertIsCurrent(workQueue());
auto currentTime = WallTime::now();
auto iterator = m_lastModificationTimes.find(origin);
if (iterator == m_lastModificationTimes.end())
m_lastModificationTimes.set(origin, currentTime);
else {
if (currentTime - iterator->value <= originLastModificationTimeUpdateInterval)
return;
iterator->value = currentTime;
}
m_lastModificationTimes.removeIf([¤tTime](auto& iterator) {
return currentTime - iterator.value > originLastModificationTimeUpdateInterval;
});
// This function must be called when origin is in use, i.e. OriginStorageManager exists.
auto* manager = m_originStorageManagers.get(origin);
ASSERT(manager);
auto originDirectory = manager->path();
if (!originDirectory)
return;
FileSystem::updateFileModificationTime(originFilePath(originDirectory));
if (m_unifiedOriginStorageLevel <= UnifiedOriginStorageLevel::Basic)
FileSystem::updateFileModificationTime(manager->resolvedPath(WebsiteDataType::DOMCache));
if (m_unifiedOriginStorageLevel == UnifiedOriginStorageLevel::None)
FileSystem::updateFileModificationTime(manager->resolvedPath(WebsiteDataType::IndexedDBDatabases));
}
bool NetworkStorageManager::persistedInternal(const WebCore::ClientOrigin& origin)
{
auto persistedFile = persistedFilePath(origin);
if (persistedFile.isEmpty())
return false;
return FileSystem::fileExists(persistedFile);
}
void NetworkStorageManager::persisted(const WebCore::ClientOrigin& origin, CompletionHandler<void(bool)>&& completionHandler)
{
assertIsCurrent(workQueue());
completionHandler(persistedInternal(origin));
}
void NetworkStorageManager::fetchRegistrableDomainsForPersist()
{
ASSERT(RunLoop::isMain());
if (!m_process)
return didFetchRegistrableDomainsForPersist({ });
protectedProcess()->registrableDomainsExemptFromWebsiteDataDeletion(m_sessionID, [weakThis = ThreadSafeWeakPtr { *this }](HashSet<WebCore::RegistrableDomain>&& domains) mutable {
if (RefPtr protectedThis = weakThis.get())
protectedThis->didFetchRegistrableDomainsForPersist(std::forward<decltype(domains)>(domains));
});
}
void NetworkStorageManager::didFetchRegistrableDomainsForPersist(HashSet<WebCore::RegistrableDomain>&& domains)
{
ASSERT(RunLoop::isMain());
if (m_closed)
return;
protectedWorkQueue()->dispatch([this, weakThis = ThreadSafeWeakPtr { *this }, domains = crossThreadCopy(WTFMove(domains))]() mutable {
assertIsCurrent(workQueue());
auto protectedThis = weakThis.get();
if (!protectedThis)
return;
m_domainsExemptFromEviction = WTFMove(domains);
for (auto&& [origin, completionHandler] : std::exchange(m_persistCompletionHandlers, { }))
completionHandler(persistOrigin(origin));
});
}
bool NetworkStorageManager::persistOrigin(const WebCore::ClientOrigin& origin)
{
assertIsCurrent(workQueue());
ASSERT(m_domainsExemptFromEviction);
if (!m_domainsExemptFromEviction->contains(origin.clientRegistrableDomain())) {
auto persistedFile = persistedFilePath(origin);
if (!persistedFile.isEmpty())
FileSystem::deleteFile(persistedFile);
return false;
}
FileSystem::overwriteEntireFile(persistedFilePath(origin), std::span<uint8_t> { });
return true;
}
void NetworkStorageManager::persist(const WebCore::ClientOrigin& origin, CompletionHandler<void(bool)>&& completionHandler)
{
assertIsCurrent(workQueue());
if (origin.topOrigin != origin.clientOrigin)
return completionHandler(false);
if (persistedFilePath(origin).isEmpty())
return completionHandler(false);
if (m_domainsExemptFromEviction)
return completionHandler(persistOrigin(origin));
m_persistCompletionHandlers.append({ origin, WTFMove(completionHandler) });
RunLoop::protectedMain()->dispatch([weakThis = ThreadSafeWeakPtr { *this }]() mutable {
if (auto protectedThis = weakThis.get())
protectedThis->fetchRegistrableDomainsForPersist();
});
}
void NetworkStorageManager::estimate(const WebCore::ClientOrigin& origin, CompletionHandler<void(std::optional<WebCore::StorageEstimate>)>&& completionHandler)
{
assertIsCurrent(workQueue());
completionHandler(originStorageManager(origin).estimate());
}
void NetworkStorageManager::resetStoragePersistedState(CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
for (auto& origin : getAllOrigins()) {
auto persistedFile = persistedFilePath(origin);
if (!persistedFile.isEmpty())
FileSystem::deleteFile(persistedFile);
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler();
});
});
}
void NetworkStorageManager::clearStorageForWebPage(WebPageProxyIdentifier pageIdentifier)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, pageIdentifier]() mutable {
assertIsCurrent(workQueue());
for (auto& manager : m_originStorageManagers.values()) {
if (auto* sessionStorageManager = manager->existingSessionStorageManager())
sessionStorageManager->removeNamespace(ObjectIdentifier<StorageNamespaceIdentifierType>(pageIdentifier.toUInt64()));
}
});
}
void NetworkStorageManager::cloneSessionStorageForWebPage(WebPageProxyIdentifier fromIdentifier, WebPageProxyIdentifier toIdentifier)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, fromIdentifier, toIdentifier]() mutable {
assertIsCurrent(workQueue());
cloneSessionStorageNamespace(ObjectIdentifier<StorageNamespaceIdentifierType>(fromIdentifier.toUInt64()), ObjectIdentifier<StorageNamespaceIdentifierType>(toIdentifier.toUInt64()));
});
}
void NetworkStorageManager::cloneSessionStorageNamespace(StorageNamespaceIdentifier fromIdentifier, StorageNamespaceIdentifier toIdentifier)
{
assertIsCurrent(workQueue());
for (auto& manager : m_originStorageManagers.values()) {
if (auto* sessionStorageManager = manager->existingSessionStorageManager())
sessionStorageManager->cloneStorageArea(fromIdentifier, toIdentifier);
}
}
void NetworkStorageManager::fetchSessionStorageForWebPage(WebPageProxyIdentifier pageIdentifier, CompletionHandler<void(HashMap<WebCore::ClientOrigin, HashMap<String, String>>&&)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, pageIdentifier, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
HashMap<WebCore::ClientOrigin, HashMap<String, String>> sessionStorageMap;
StorageNamespaceIdentifier storageNameSpaceIdentifier { pageIdentifier.toUInt64() };
for (auto& [origin, originStorageManager] : m_originStorageManagers) {
auto* sessionStorageManager = originStorageManager->existingSessionStorageManager();
if (!sessionStorageManager)
continue;
auto storageMap = sessionStorageManager->fetchStorageMap(storageNameSpaceIdentifier);
if (!storageMap.isEmpty())
sessionStorageMap.add(origin, WTFMove(storageMap));
}
RunLoop::protectedMain()->dispatch([completionHandler = WTFMove(completionHandler), sessionStorageMap = crossThreadCopy(WTFMove(sessionStorageMap))] mutable {
completionHandler(WTFMove(sessionStorageMap));
});
});
}
void NetworkStorageManager::restoreSessionStorageForWebPage(WebPageProxyIdentifier pageIdentifier, HashMap<WebCore::ClientOrigin, HashMap<String, String>>&& sessionStorageMap, CompletionHandler<void(bool)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, pageIdentifier, sessionStorageMap = crossThreadCopy(WTFMove(sessionStorageMap)), completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
bool succeeded = true;
StorageNamespaceIdentifier storageNameSpaceIdentifier { pageIdentifier.toUInt64() };
for (auto& [clientOrigin, storageMap] : sessionStorageMap) {
auto& sessionStorageManager = checkedOriginStorageManager(clientOrigin, ShouldWriteOriginFile::Yes)->sessionStorageManager(*m_storageAreaRegistry);
auto result = sessionStorageManager.setStorageMap(storageNameSpaceIdentifier, clientOrigin, WTFMove(storageMap));
if (!result)
succeeded = false;
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler), succeeded] mutable {
completionHandler(succeeded);
});
});
}
void NetworkStorageManager::didIncreaseQuota(WebCore::ClientOrigin&& origin, QuotaIncreaseRequestIdentifier identifier, std::optional<uint64_t> newQuota)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, origin = crossThreadCopy(WTFMove(origin)), identifier, newQuota]() mutable {
assertIsCurrent(workQueue());
if (CheckedPtr manager = m_originStorageManagers.get(origin))
manager->protectedQuotaManager()->didIncreaseQuota(identifier, newQuota);
});
}
void NetworkStorageManager::fileSystemGetDirectory(IPC::Connection& connection, WebCore::ClientOrigin&& origin, CompletionHandler<void(Expected<std::optional<WebCore::FileSystemHandleIdentifier>, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
Ref fileSystemStorageManager = checkedOriginStorageManager(origin)->fileSystemStorageManager(*protectedFileSystemStorageHandleRegistry());
auto result = fileSystemStorageManager->getDirectory(connection.uniqueID());
if (result)
completionHandler(std::optional { result.value() });
else
completionHandler(makeUnexpected(result.error()));
}
void NetworkStorageManager::closeHandle(WebCore::FileSystemHandleIdentifier identifier)
{
ASSERT(!RunLoop::isMain());
if (RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier))
handle->close();
}
void NetworkStorageManager::isSameEntry(WebCore::FileSystemHandleIdentifier identifier, WebCore::FileSystemHandleIdentifier targetIdentifier, CompletionHandler<void(bool)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(false);
completionHandler(handle->isSameEntry(targetIdentifier));
}
void NetworkStorageManager::move(WebCore::FileSystemHandleIdentifier identifier, WebCore::FileSystemHandleIdentifier destinationIdentifier, const String& newName, CompletionHandler<void(std::optional<FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(FileSystemStorageError::Unknown);
completionHandler(handle->move(destinationIdentifier, newName));
}
void NetworkStorageManager::getFileHandle(IPC::Connection& connection, WebCore::FileSystemHandleIdentifier identifier, String&& name, bool createIfNecessary, CompletionHandler<void(Expected<WebCore::FileSystemHandleIdentifier, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
completionHandler(handle->getFileHandle(connection.uniqueID(), WTFMove(name), createIfNecessary));
}
void NetworkStorageManager::getDirectoryHandle(IPC::Connection& connection, WebCore::FileSystemHandleIdentifier identifier, String&& name, bool createIfNecessary, CompletionHandler<void(Expected<WebCore::FileSystemHandleIdentifier, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
completionHandler(handle->getDirectoryHandle(connection.uniqueID(), WTFMove(name), createIfNecessary));
}
void NetworkStorageManager::removeEntry(WebCore::FileSystemHandleIdentifier identifier, const String& name, bool deleteRecursively, CompletionHandler<void(std::optional<FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(FileSystemStorageError::Unknown);
completionHandler(handle->removeEntry(name, deleteRecursively));
}
void NetworkStorageManager::resolve(WebCore::FileSystemHandleIdentifier identifier, WebCore::FileSystemHandleIdentifier targetIdentifier, CompletionHandler<void(Expected<Vector<String>, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
completionHandler(handle->resolve(targetIdentifier));
}
void NetworkStorageManager::getFile(WebCore::FileSystemHandleIdentifier identifier, CompletionHandler<void(Expected<String, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
completionHandler(handle->path());
}
void NetworkStorageManager::createSyncAccessHandle(WebCore::FileSystemHandleIdentifier identifier, CompletionHandler<void(Expected<FileSystemSyncAccessHandleInfo, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
completionHandler(handle->createSyncAccessHandle());
}
void NetworkStorageManager::closeSyncAccessHandle(WebCore::FileSystemHandleIdentifier identifier, WebCore::FileSystemSyncAccessHandleIdentifier accessHandleIdentifier, CompletionHandler<void()>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
if (RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier))
handle->closeSyncAccessHandle(accessHandleIdentifier);
completionHandler();
}
void NetworkStorageManager::requestNewCapacityForSyncAccessHandle(WebCore::FileSystemHandleIdentifier identifier, WebCore::FileSystemSyncAccessHandleIdentifier accessHandleIdentifier, uint64_t newCapacity, CompletionHandler<void(std::optional<uint64_t>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(std::nullopt);
handle->requestNewCapacityForSyncAccessHandle(accessHandleIdentifier, newCapacity, WTFMove(completionHandler));
}
void NetworkStorageManager::createWritable(WebCore::FileSystemHandleIdentifier identifier, bool keepExistingData, CompletionHandler<void(Expected<WebCore::FileSystemWritableFileStreamIdentifier, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
completionHandler(handle->createWritable(keepExistingData));
}
void NetworkStorageManager::closeWritable(WebCore::FileSystemHandleIdentifier identifier, WebCore::FileSystemWritableFileStreamIdentifier streamIdentifier, WebCore::FileSystemWriteCloseReason reason, CompletionHandler<void(std::optional<FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(FileSystemStorageError::Unknown);
completionHandler(handle->closeWritable(streamIdentifier, reason));
}
void NetworkStorageManager::executeCommandForWritable(WebCore::FileSystemHandleIdentifier identifier, WebCore::FileSystemWritableFileStreamIdentifier streamIdentifier, WebCore::FileSystemWriteCommandType type, std::optional<uint64_t> position, std::optional<uint64_t> size, std::span<const uint8_t> dataBytes, bool hasDataError, CompletionHandler<void(std::optional<FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(FileSystemStorageError::Unknown);
completionHandler(handle->executeCommandForWritable(streamIdentifier, type, position, size, dataBytes, hasDataError));
}
void NetworkStorageManager::getHandleNames(WebCore::FileSystemHandleIdentifier identifier, CompletionHandler<void(Expected<Vector<String>, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
completionHandler(handle->getHandleNames());
}
void NetworkStorageManager::getHandle(IPC::Connection& connection, WebCore::FileSystemHandleIdentifier identifier, String&& name, CompletionHandler<void(Expected<std::optional<std::pair<WebCore::FileSystemHandleIdentifier, bool>>, FileSystemStorageError>)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr handle = protectedFileSystemStorageHandleRegistry()->getHandle(identifier);
if (!handle)
return completionHandler(makeUnexpected(FileSystemStorageError::Unknown));
auto result = handle->getHandle(connection.uniqueID(), WTFMove(name));
if (result)
completionHandler(std::optional { result.value() });
else
completionHandler(makeUnexpected(result.error()));
}
void NetworkStorageManager::forEachOriginDirectory(NOESCAPE const Function<void(const String&)>& apply)
{
for (auto& topOrigin : FileSystem::listDirectory(m_path)) {
auto topOriginDirectory = FileSystem::pathByAppendingComponent(m_path, topOrigin);
auto openingOrigins = FileSystem::listDirectory(topOriginDirectory);
if (openingOrigins.isEmpty()) {
FileSystem::deleteEmptyDirectory(topOriginDirectory);
continue;
}
for (auto& openingOrigin : openingOrigins) {
if (openingOrigin.startsWith('.'))
continue;
auto openingOriginDirectory = FileSystem::pathByAppendingComponent(topOriginDirectory, openingOrigin);
apply(openingOriginDirectory);
}
}
}
HashSet<WebCore::ClientOrigin> NetworkStorageManager::getAllOrigins()
{
assertIsCurrent(workQueue());
HashSet<WebCore::ClientOrigin> allOrigins;
for (auto& origin : m_originStorageManagers.keys())
allOrigins.add(origin);
forEachOriginDirectory([&](auto directory) {
if (auto origin = WebCore::StorageUtilities::readOriginFromFile(originFilePath(directory)))
allOrigins.add(*origin);
});
for (auto& origin : LocalStorageManager::originsOfLocalStorageData(m_customLocalStoragePath))
allOrigins.add(WebCore::ClientOrigin { origin, origin });
for (auto& origin : IDBStorageManager::originsOfIDBStorageData(m_customIDBStoragePath))
allOrigins.add(origin);
for (auto& origin : CacheStorageManager::originsOfCacheStorageData(m_customCacheStoragePath))
allOrigins.add(origin);
return allOrigins;
}
static void updateOriginData(HashMap<WebCore::SecurityOriginData, OriginStorageManager::DataTypeSizeMap>& originTypes, const WebCore::SecurityOriginData& origin, const OriginStorageManager::DataTypeSizeMap& newTypeSizeMap)
{
auto& typeSizeMap = originTypes.add(origin, OriginStorageManager::DataTypeSizeMap { }).iterator->value;
for (auto [type, size] : newTypeSizeMap) {
auto& currentSize = typeSizeMap.add(type, 0).iterator->value;
currentSize += size;
}
}
Vector<WebsiteData::Entry> NetworkStorageManager::fetchDataFromDisk(OptionSet<WebsiteDataType> targetTypes, ShouldComputeSize shouldComputeSize)
{
ASSERT(!RunLoop::isMain());
HashMap<WebCore::SecurityOriginData, OriginStorageManager::DataTypeSizeMap> originTypes;
for (auto& origin : getAllOrigins()) {
auto typeSizeMap = checkedOriginStorageManager(origin)->fetchDataTypesInList(targetTypes, shouldComputeSize == ShouldComputeSize::Yes);
updateOriginData(originTypes, origin.clientOrigin, typeSizeMap);
if (origin.clientOrigin != origin.topOrigin)
updateOriginData(originTypes, origin.topOrigin, typeSizeMap);
removeOriginStorageManagerIfPossible(origin);
}
Vector<WebsiteData::Entry> entries;
for (auto [origin, types] : originTypes) {
for (auto [type, size] : types)
entries.append({ WebsiteData::Entry { origin, type, size } });
}
return entries;
}
void NetworkStorageManager::fetchData(OptionSet<WebsiteDataType> types, ShouldComputeSize shouldComputeSize, CompletionHandler<void(Vector<WebsiteData::Entry>&&)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, types, shouldComputeSize, completionHandler = WTFMove(completionHandler)]() mutable {
auto entries = fetchDataFromDisk(types, shouldComputeSize);
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler), entries = crossThreadCopy(WTFMove(entries))]() mutable {
completionHandler(WTFMove(entries));
});
});
}
HashSet<WebCore::ClientOrigin> NetworkStorageManager::deleteDataOnDisk(OptionSet<WebsiteDataType> types, WallTime modifiedSinceTime, NOESCAPE const Function<bool(const WebCore::ClientOrigin&)>& filter)
{
ASSERT(!RunLoop::isMain());
HashSet<WebCore::ClientOrigin> deletedOrigins;
for (auto& origin : getAllOrigins()) {
if (!filter(origin))
continue;
{
CheckedRef originStorageManager = this->originStorageManager(origin);
auto existingDataTypes = originStorageManager->fetchDataTypesInList(types, false);
if (!existingDataTypes.isEmpty()) {
deletedOrigins.add(origin);
originStorageManager->deleteData(types, modifiedSinceTime);
}
}
if (types.containsAll(allManagedTypes())) {
auto persistedFile = persistedFilePath(origin);
if (!persistedFile.isEmpty())
FileSystem::deleteFile(persistedFile);
}
removeOriginStorageManagerIfPossible(origin);
}
return deletedOrigins;
}
void NetworkStorageManager::deleteData(OptionSet<WebsiteDataType> types, const Vector<WebCore::SecurityOriginData>& origins, CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, types, origins = crossThreadCopy(origins), completionHandler = WTFMove(completionHandler)]() mutable {
HashSet<WebCore::SecurityOriginData> originSet;
originSet.reserveInitialCapacity(origins.size());
for (auto origin : origins)
originSet.add(WTFMove(origin));
deleteDataOnDisk(types, -WallTime::infinity(), [&originSet](auto origin) {
return originSet.contains(origin.topOrigin) || originSet.contains(origin.clientOrigin);
});
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler();
});
});
}
void NetworkStorageManager::deleteData(OptionSet<WebsiteDataType> types, const WebCore::ClientOrigin& origin, CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, types, originToDelete = origin.isolatedCopy(), completionHandler = WTFMove(completionHandler)]() mutable {
deleteDataOnDisk(types, -WallTime::infinity(), [originToDelete = WTFMove(originToDelete)](auto& origin) {
return origin == originToDelete;
});
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler();
});
});
}
void NetworkStorageManager::deleteDataModifiedSince(OptionSet<WebsiteDataType> types, WallTime modifiedSinceTime, CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, types, modifiedSinceTime, completionHandler = WTFMove(completionHandler)]() mutable {
deleteDataOnDisk(types, modifiedSinceTime, [](auto&) {
return true;
});
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler();
});
});
}
void NetworkStorageManager::deleteDataForRegistrableDomains(OptionSet<WebsiteDataType> types, const Vector<WebCore::RegistrableDomain>& domains, CompletionHandler<void(HashSet<WebCore::RegistrableDomain>&&)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, types, domains = crossThreadCopy(domains), completionHandler = WTFMove(completionHandler)]() mutable {
auto deletedOrigins = deleteDataOnDisk(types, -WallTime::infinity(), [&domains](auto& origin) {
auto domain = WebCore::RegistrableDomain::uncheckedCreateFromHost(origin.clientOrigin.host());
return domains.contains(domain);
});
HashSet<WebCore::RegistrableDomain> deletedDomains;
for (auto origin : deletedOrigins) {
auto domain = WebCore::RegistrableDomain::uncheckedCreateFromHost(origin.clientOrigin.host());
deletedDomains.add(domain);
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler), domains = crossThreadCopy(WTFMove(deletedDomains))]() mutable {
completionHandler(WTFMove(domains));
});
});
}
void NetworkStorageManager::moveData(OptionSet<WebsiteDataType> types, WebCore::SecurityOriginData&& source, WebCore::SecurityOriginData&& target, CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, types, source = crossThreadCopy(WTFMove(source)), target = crossThreadCopy(WTFMove(target)), completionHandler = WTFMove(completionHandler)]() mutable {
auto sourceOrigin = WebCore::ClientOrigin { source, source };
auto targetOrigin = WebCore::ClientOrigin { target, target };
{
CheckedRef targetOriginStorageManager = originStorageManager(targetOrigin);
// Clear existing data of target origin.
targetOriginStorageManager->deleteData(types, -WallTime::infinity());
// Move data from source origin to target origin.
checkedOriginStorageManager(sourceOrigin)->moveData(types, targetOriginStorageManager->resolvedPath(WebsiteDataType::LocalStorage), targetOriginStorageManager->resolvedPath(WebsiteDataType::IndexedDBDatabases));
}
removeOriginStorageManagerIfPossible(targetOrigin);
removeOriginStorageManagerIfPossible(sourceOrigin);
RunLoop::protectedMain()->dispatch(WTFMove(completionHandler));
});
}
void NetworkStorageManager::getOriginDirectory(WebCore::ClientOrigin&& origin, WebsiteDataType type, CompletionHandler<void(const String&)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, type, origin = crossThreadCopy(WTFMove(origin)), completionHandler = WTFMove(completionHandler)]() mutable {
RunLoop::protectedMain()->dispatch([completionHandler = WTFMove(completionHandler), directory = crossThreadCopy(checkedOriginStorageManager(origin)->resolvedPath(type))]() mutable {
completionHandler(WTFMove(directory));
});
removeOriginStorageManagerIfPossible(origin);
});
}
void NetworkStorageManager::suspend(CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
if (m_sessionID.isEphemeral())
return completionHandler();
RELEASE_LOG(ProcessSuspension, "%p - NetworkStorageManager::suspend()", this);
protectedWorkQueue()->suspend([this, protectedThis = Ref { *this }] {
assertIsCurrent(workQueue());
for (auto& manager : m_originStorageManagers.values()) {
if (auto localStorageManager = manager->existingLocalStorageManager())
localStorageManager->syncLocalStorage();
if (auto idbStorageManager = manager->existingIDBStorageManager())
idbStorageManager->stopDatabaseActivitiesForSuspend();
}
}, WTFMove(completionHandler));
}
void NetworkStorageManager::resume()
{
ASSERT(RunLoop::isMain());
if (m_sessionID.isEphemeral())
return;
RELEASE_LOG(ProcessSuspension, "%p - NetworkStorageManager::resume()", this);
protectedWorkQueue()->resume();
}
void NetworkStorageManager::handleLowMemoryWarning()
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }] {
assertIsCurrent(workQueue());
for (auto& manager : m_originStorageManagers.values()) {
if (auto localStorageManager = manager->existingLocalStorageManager())
localStorageManager->handleLowMemoryWarning();
if (auto idbStorageManager = manager->existingIDBStorageManager())
idbStorageManager->handleLowMemoryWarning();
}
});
}
void NetworkStorageManager::syncLocalStorage(CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
for (auto& manager : m_originStorageManagers.values()) {
if (auto localStorageManager = manager->existingLocalStorageManager())
localStorageManager->syncLocalStorage();
}
RunLoop::protectedMain()->dispatch(WTFMove(completionHandler));
});
}
void NetworkStorageManager::fetchLocalStorage(CompletionHandler<void(HashMap<WebCore::ClientOrigin, HashMap<String, String>>&&)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
HashMap<WebCore::ClientOrigin, HashMap<String, String>> localStorageMap;
for (auto& origin : getAllOrigins()) {
auto& localStorageManager = checkedOriginStorageManager(origin, ShouldWriteOriginFile::No)->localStorageManager(*m_storageAreaRegistry);
auto storageMap = localStorageManager.fetchStorageMap();
if (!storageMap.isEmpty())
localStorageMap.add(origin, WTFMove(storageMap));
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler), localStorageMap = crossThreadCopy(WTFMove(localStorageMap))] mutable {
completionHandler(WTFMove(localStorageMap));
});
});
}
void NetworkStorageManager::restoreLocalStorage(HashMap<WebCore::ClientOrigin, HashMap<String, String>>&& localStorageMap, CompletionHandler<void(bool)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, localStorageMap = crossThreadCopy(WTFMove(localStorageMap)), completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
bool succeeded = true;
for (auto& [clientOrigin, storageMap] : localStorageMap) {
auto& localStorageManager = checkedOriginStorageManager(clientOrigin, ShouldWriteOriginFile::Yes)->localStorageManager(*m_storageAreaRegistry);
auto result = localStorageManager.setStorageMap(clientOrigin, WTFMove(storageMap), protectedWorkQueue());
if (!result)
succeeded = false;
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler), succeeded] mutable {
completionHandler(succeeded);
});
});
}
void NetworkStorageManager::registerTemporaryBlobFilePaths(IPC::Connection& connection, const Vector<String>& filePaths)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, connectionID = connection.uniqueID(), filePaths = crossThreadCopy(filePaths)] {
assertIsCurrent(workQueue());
auto& temporaryBlobPaths = m_temporaryBlobPathsByConnection.ensure(connectionID, [] {
return HashSet<String> { };
}).iterator->value;
temporaryBlobPaths.add(filePaths.begin(), filePaths.end());
});
}
void NetworkStorageManager::requestSpace(const WebCore::ClientOrigin& origin, uint64_t size, CompletionHandler<void(bool)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, origin = crossThreadCopy(origin), size, completionHandler = WTFMove(completionHandler)]() mutable {
checkedOriginStorageManager(origin)->protectedQuotaManager()->requestSpace(size, [completionHandler = WTFMove(completionHandler)](auto decision) mutable {
RunLoop::protectedMain()->dispatch([completionHandler = WTFMove(completionHandler), decision]() mutable {
completionHandler(decision == OriginQuotaManager::Decision::Grant);
});
});
});
}
void NetworkStorageManager::resetQuotaForTesting(CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
for (auto& manager : m_originStorageManagers.values())
manager->protectedQuotaManager()->resetQuotaForTesting();
RunLoop::protectedMain()->dispatch(WTFMove(completionHandler));
});
}
void NetworkStorageManager::resetQuotaUpdatedBasedOnUsageForTesting(WebCore::ClientOrigin&& origin)
{
assertIsCurrent(workQueue());
if (auto manager = m_originStorageManagers.get(origin))
manager->protectedQuotaManager()->resetQuotaUpdatedBasedOnUsageForTesting();
}
void NetworkStorageManager::setOriginQuotaRatioEnabledForTesting(bool enabled, CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, enabled, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
if (m_originQuotaRatioEnabled != enabled) {
m_originQuotaRatioEnabled = enabled;
for (auto& [origin, manager] : m_originStorageManagers)
manager->protectedQuotaManager()->updateParametersForTesting(originQuotaManagerParameters(origin));
}
RunLoop::protectedMain()->dispatch(WTFMove(completionHandler));
});
}
#if PLATFORM(IOS_FAMILY)
void NetworkStorageManager::setBackupExclusionPeriodForTesting(Seconds period, CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
m_queue->dispatch([this, protectedThis = Ref { *this }, period, completionHandler = WTFMove(completionHandler)]() mutable {
m_backupExclusionPeriod = period;
RunLoop::protectedMain()->dispatch(WTFMove(completionHandler));
});
}
#endif
void NetworkStorageManager::setStorageSiteValidationEnabledInternal(bool enabled)
{
assertIsCurrent(workQueue());
auto currentEnabled = !!m_allowedSitesForConnections;
if (currentEnabled == enabled)
return;
if (enabled)
m_allowedSitesForConnections = ConnectionSitesMap { };
else
m_allowedSitesForConnections = std::nullopt;
}
void NetworkStorageManager::setStorageSiteValidationEnabled(bool enabled)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
protectedWorkQueue()->dispatch([weakThis = ThreadSafeWeakPtr { *this }, enabled]() mutable {
if (RefPtr protectedThis = weakThis.get())
protectedThis->setStorageSiteValidationEnabledInternal(enabled);
});
}
void NetworkStorageManager::addAllowedSitesForConnectionInternal(IPC::Connection::UniqueID connection, const Vector<WebCore::RegistrableDomain>& sites)
{
assertIsCurrent(workQueue());
if (!m_allowedSitesForConnections)
return;
auto& allowedSites = m_allowedSitesForConnections->add(connection, HashSet<WebCore::RegistrableDomain> { }).iterator->value;
for (auto& site : sites)
allowedSites.add(site);
}
void NetworkStorageManager::addAllowedSitesForConnection(IPC::Connection::UniqueID connection, const Vector<WebCore::RegistrableDomain>& sites)
{
ASSERT(RunLoop::isMain());
ASSERT(!m_closed);
if (sites.isEmpty())
return;
protectedWorkQueue()->dispatch([weakThis = ThreadSafeWeakPtr { *this }, connection, sites = crossThreadCopy(sites)]() mutable {
if (RefPtr protectedThis = weakThis.get())
protectedThis->addAllowedSitesForConnectionInternal(connection, sites);
});
}
bool NetworkStorageManager::isSiteAllowedForConnection(IPC::Connection::UniqueID connection, const WebCore::RegistrableDomain& site) const
{
assertIsCurrent(workQueue());
if (!m_allowedSitesForConnections)
return true;
auto iter = m_allowedSitesForConnections->find(connection);
if (iter == m_allowedSitesForConnections->end())
return false;
return iter->value.contains(site);
}
void NetworkStorageManager::connectToStorageArea(IPC::Connection& connection, WebCore::StorageType type, StorageAreaMapIdentifier sourceIdentifier, std::optional<StorageNamespaceIdentifier> namespaceIdentifier, const WebCore::ClientOrigin& origin, CompletionHandler<void(std::optional<StorageAreaIdentifier>, HashMap<String, String>, uint64_t)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
MESSAGE_CHECK_COMPLETION(isSiteAllowedForConnection(connection.uniqueID(), WebCore::RegistrableDomain { origin.topOrigin }), connection, completionHandler(std::nullopt, { }, StorageAreaBase::nextMessageIdentifier()));
auto connectionIdentifier = connection.uniqueID();
// StorageArea may be connected due to LocalStorage prewarming, so do not write origin file eagerly.
CheckedRef originStorageManager = this->originStorageManager(origin, ShouldWriteOriginFile::No);
std::optional<StorageAreaIdentifier> resultIdentifier;
switch (type) {
case WebCore::StorageType::Local:
resultIdentifier = originStorageManager->localStorageManager(*m_storageAreaRegistry).connectToLocalStorageArea(connectionIdentifier, sourceIdentifier, origin, m_queue.copyRef());
break;
case WebCore::StorageType::TransientLocal:
resultIdentifier = originStorageManager->localStorageManager(*m_storageAreaRegistry).connectToTransientLocalStorageArea(connectionIdentifier, sourceIdentifier, origin);
break;
case WebCore::StorageType::Session:
if (!namespaceIdentifier)
return completionHandler(std::nullopt, HashMap<String, String> { }, StorageAreaBase::nextMessageIdentifier());
resultIdentifier = originStorageManager->sessionStorageManager(*m_storageAreaRegistry).connectToSessionStorageArea(connectionIdentifier, sourceIdentifier, origin, *namespaceIdentifier);
}
if (!resultIdentifier)
return completionHandler(std::nullopt, HashMap<String, String> { }, StorageAreaBase::nextMessageIdentifier());
if (RefPtr storageArea = m_storageAreaRegistry->getStorageArea(*resultIdentifier)) {
completionHandler(*resultIdentifier, storageArea->allItems(), StorageAreaBase::nextMessageIdentifier());
writeOriginToFileIfNecessary(origin, storageArea.get());
return;
}
return completionHandler(*resultIdentifier, HashMap<String, String> { }, StorageAreaBase::nextMessageIdentifier());
}
void NetworkStorageManager::connectToStorageAreaSync(IPC::Connection& connection, WebCore::StorageType type, StorageAreaMapIdentifier sourceIdentifier, std::optional<StorageNamespaceIdentifier> namespaceIdentifier, const WebCore::ClientOrigin& origin, CompletionHandler<void(std::optional<StorageAreaIdentifier>, HashMap<String, String>, uint64_t)>&& completionHandler)
{
connectToStorageArea(connection, type, sourceIdentifier, namespaceIdentifier, origin, WTFMove(completionHandler));
}
void NetworkStorageManager::cancelConnectToStorageArea(IPC::Connection& connection, WebCore::StorageType type, std::optional<StorageNamespaceIdentifier> namespaceIdentifier, const WebCore::ClientOrigin& origin)
{
assertIsCurrent(workQueue());
MESSAGE_CHECK(isSiteAllowedForConnection(connection.uniqueID(), WebCore::RegistrableDomain { origin.topOrigin }), connection);
auto iterator = m_originStorageManagers.find(origin);
if (iterator == m_originStorageManagers.end())
return;
auto connectionIdentifier = connection.uniqueID();
switch (type) {
case WebCore::StorageType::Local:
if (auto localStorageManager = iterator->value->existingLocalStorageManager())
localStorageManager->cancelConnectToLocalStorageArea(connectionIdentifier);
break;
case WebCore::StorageType::TransientLocal:
if (auto localStorageManager = iterator->value->existingLocalStorageManager())
localStorageManager->cancelConnectToTransientLocalStorageArea(connectionIdentifier);
break;
case WebCore::StorageType::Session:
if (auto sessionStorageManager = iterator->value->existingSessionStorageManager()) {
if (!namespaceIdentifier)
return;
sessionStorageManager->cancelConnectToSessionStorageArea(connectionIdentifier, *namespaceIdentifier);
}
}
}
void NetworkStorageManager::disconnectFromStorageArea(IPC::Connection& connection, StorageAreaIdentifier identifier)
{
ASSERT(!RunLoop::isMain());
RefPtr storageArea = m_storageAreaRegistry->getStorageArea(identifier);
if (!storageArea)
return;
MESSAGE_CHECK(isSiteAllowedForConnection(connection.uniqueID(), WebCore::RegistrableDomain { storageArea->origin().topOrigin }), connection);
CheckedRef originStorageManager = this->originStorageManager(storageArea->origin());
if (storageArea->storageType() == StorageAreaBase::StorageType::Local)
originStorageManager->localStorageManager(*m_storageAreaRegistry).disconnectFromStorageArea(connection.uniqueID(), identifier);
else
originStorageManager->sessionStorageManager(*m_storageAreaRegistry).disconnectFromStorageArea(connection.uniqueID(), identifier);
}
void NetworkStorageManager::setItem(IPC::Connection& connection, StorageAreaIdentifier identifier, StorageAreaImplIdentifier implIdentifier, String&& key, String&& value, String&& urlString, CompletionHandler<void(bool, HashMap<String, String>&&)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
bool hasError = false;
HashMap<String, String> allItems;
RefPtr storageArea = m_storageAreaRegistry->getStorageArea(identifier);
if (!storageArea)
return completionHandler(hasError, WTFMove(allItems));
MESSAGE_CHECK_COMPLETION(isSiteAllowedForConnection(connection.uniqueID(), WebCore::RegistrableDomain { storageArea->origin().topOrigin }), connection, completionHandler(hasError, WTFMove(allItems)));
MESSAGE_CHECK_BASE(isSiteAllowedForConnection(connection.uniqueID(), WebCore::RegistrableDomain { storageArea->origin().topOrigin }), connection);
auto result = storageArea->setItem(connection.uniqueID(), implIdentifier, WTFMove(key), WTFMove(value), WTFMove(urlString));
hasError = !result;
if (hasError)
allItems = storageArea->allItems();
completionHandler(hasError, WTFMove(allItems));
writeOriginToFileIfNecessary(storageArea->origin(), storageArea.get());
}
void NetworkStorageManager::removeItem(IPC::Connection& connection, StorageAreaIdentifier identifier, StorageAreaImplIdentifier implIdentifier, String&& key, String&& urlString, CompletionHandler<void(bool, HashMap<String, String>&&)>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
bool hasError = false;
HashMap<String, String> allItems;
RefPtr storageArea = m_storageAreaRegistry->getStorageArea(identifier);
if (!storageArea)
return completionHandler(hasError, WTFMove(allItems));
MESSAGE_CHECK_COMPLETION(isSiteAllowedForConnection(connection.uniqueID(), WebCore::RegistrableDomain { storageArea->origin().topOrigin }), connection, completionHandler(hasError, WTFMove(allItems)));
auto result = storageArea->removeItem(connection.uniqueID(), implIdentifier, WTFMove(key), WTFMove(urlString));
hasError = !result;
if (hasError)
allItems = storageArea->allItems();
completionHandler(hasError, WTFMove(allItems));
writeOriginToFileIfNecessary(storageArea->origin(), storageArea.get());
}
void NetworkStorageManager::clear(IPC::Connection& connection, StorageAreaIdentifier identifier, StorageAreaImplIdentifier implIdentifier, String&& urlString, CompletionHandler<void()>&& completionHandler)
{
ASSERT(!RunLoop::isMain());
RefPtr storageArea = m_storageAreaRegistry->getStorageArea(identifier);
if (!storageArea)
return completionHandler();
MESSAGE_CHECK_COMPLETION(isSiteAllowedForConnection(connection.uniqueID(), WebCore::RegistrableDomain { storageArea->origin().topOrigin }), connection, completionHandler());
storageArea->clear(connection.uniqueID(), implIdentifier, WTFMove(urlString));
completionHandler();
writeOriginToFileIfNecessary(storageArea->origin(), storageArea.get());
}
void NetworkStorageManager::openDatabase(IPC::Connection& connection, const WebCore::IDBOpenRequestData& requestData)
{
Ref connectionToClient = m_idbStorageRegistry->ensureConnectionToClient(connection.uniqueID(), *requestData.requestIdentifier().connectionIdentifier());
checkedOriginStorageManager(requestData.databaseIdentifier().origin())->idbStorageManager(*m_idbStorageRegistry).openDatabase(connectionToClient, requestData);
}
void NetworkStorageManager::openDBRequestCancelled(const WebCore::IDBOpenRequestData& requestData)
{
checkedOriginStorageManager(requestData.databaseIdentifier().origin())->idbStorageManager(*m_idbStorageRegistry).openDBRequestCancelled(requestData);
}
void NetworkStorageManager::deleteDatabase(IPC::Connection& connection, const WebCore::IDBOpenRequestData& requestData)
{
Ref connectionToClient = m_idbStorageRegistry->ensureConnectionToClient(connection.uniqueID(), *requestData.requestIdentifier().connectionIdentifier());
checkedOriginStorageManager(requestData.databaseIdentifier().origin())->idbStorageManager(*m_idbStorageRegistry).deleteDatabase(connectionToClient, requestData);
}
void NetworkStorageManager::establishTransaction(WebCore::IDBDatabaseConnectionIdentifier databaseConnectionIdentifier, const WebCore::IDBTransactionInfo& transactionInfo)
{
if (auto connection = m_idbStorageRegistry->connection(databaseConnectionIdentifier))
connection->establishTransaction(transactionInfo);
}
void NetworkStorageManager::databaseConnectionPendingClose(WebCore::IDBDatabaseConnectionIdentifier databaseConnectionIdentifier)
{
if (auto connection = m_idbStorageRegistry->connection(databaseConnectionIdentifier))
connection->connectionPendingCloseFromClient();
}
void NetworkStorageManager::databaseConnectionClosed(WebCore::IDBDatabaseConnectionIdentifier databaseConnectionIdentifier)
{
if (auto connection = m_idbStorageRegistry->connection(databaseConnectionIdentifier))
connection->connectionClosedFromClient();
}
void NetworkStorageManager::abortOpenAndUpgradeNeeded(WebCore::IDBDatabaseConnectionIdentifier databaseConnectionIdentifier, const std::optional<WebCore::IDBResourceIdentifier>& transactionIdentifier)
{
if (transactionIdentifier) {
if (RefPtr transaction = m_idbStorageRegistry->transaction(*transactionIdentifier))
transaction->abortWithoutCallback();
}
if (RefPtr connection = m_idbStorageRegistry->connection(databaseConnectionIdentifier))
connection->connectionClosedFromClient();
}
void NetworkStorageManager::didFireVersionChangeEvent(WebCore::IDBDatabaseConnectionIdentifier databaseConnectionIdentifier, const WebCore::IDBResourceIdentifier& requestIdentifier, const WebCore::IndexedDB::ConnectionClosedOnBehalfOfServer connectionClosed)
{
if (RefPtr connection = m_idbStorageRegistry->connection(databaseConnectionIdentifier))
connection->didFireVersionChangeEvent(requestIdentifier, connectionClosed);
}
void NetworkStorageManager::abortTransaction(const WebCore::IDBResourceIdentifier& transactionIdentifier)
{
if (RefPtr transaction = m_idbStorageRegistry->transaction(transactionIdentifier))
transaction->abort();
}
void NetworkStorageManager::commitTransaction(const WebCore::IDBResourceIdentifier& transactionIdentifier, uint64_t handledRequestResultsCount)
{
if (RefPtr transaction = m_idbStorageRegistry->transaction(transactionIdentifier))
transaction->commit(handledRequestResultsCount);
}
void NetworkStorageManager::didFinishHandlingVersionChangeTransaction(WebCore::IDBDatabaseConnectionIdentifier databaseConnectionIdentifier, const WebCore::IDBResourceIdentifier& transactionIdentifier)
{
if (RefPtr connection = m_idbStorageRegistry->connection(databaseConnectionIdentifier))
connection->didFinishHandlingVersionChange(transactionIdentifier);
}
WebCore::IDBServer::UniqueIDBDatabaseTransaction* NetworkStorageManager::idbTransaction(const WebCore::IDBRequestData& requestData)
{
return m_idbStorageRegistry->transaction(requestData.transactionIdentifier());
}
void NetworkStorageManager::createObjectStore(IPC::Connection& connection, const WebCore::IDBRequestData& requestData, const WebCore::IDBObjectStoreInfo& objectStoreInfo)
{
RefPtr transaction = idbTransaction(requestData);
if (!transaction)
return;
MESSAGE_CHECK(transaction->isVersionChange(), connection);
transaction->createObjectStore(requestData, objectStoreInfo);
}
void NetworkStorageManager::deleteObjectStore(IPC::Connection& connection, const WebCore::IDBRequestData& requestData, const String& objectStoreName)
{
RefPtr transaction = idbTransaction(requestData);
if (!transaction)
return;
MESSAGE_CHECK(transaction->isVersionChange(), connection);
transaction->deleteObjectStore(requestData, objectStoreName);
}
void NetworkStorageManager::renameObjectStore(IPC::Connection& connection, const WebCore::IDBRequestData& requestData, WebCore::IDBObjectStoreIdentifier objectStoreIdentifier, const String& newName)
{
RefPtr transaction = idbTransaction(requestData);
if (!transaction)
return;
MESSAGE_CHECK(transaction->isVersionChange(), connection);
transaction->renameObjectStore(requestData, objectStoreIdentifier, newName);
}
void NetworkStorageManager::clearObjectStore(const WebCore::IDBRequestData& requestData, WebCore::IDBObjectStoreIdentifier objectStoreIdentifier)
{
if (RefPtr transaction = idbTransaction(requestData))
transaction->clearObjectStore(requestData, objectStoreIdentifier);
}
void NetworkStorageManager::createIndex(IPC::Connection& connection, const WebCore::IDBRequestData& requestData, const WebCore::IDBIndexInfo& indexInfo)
{
RefPtr transaction = idbTransaction(requestData);
if (!transaction)
return;
MESSAGE_CHECK(transaction->isVersionChange(), connection);
transaction->createIndex(requestData, indexInfo);
}
void NetworkStorageManager::deleteIndex(IPC::Connection& connection, const WebCore::IDBRequestData& requestData, WebCore::IDBObjectStoreIdentifier objectStoreIdentifier, const String& indexName)
{
RefPtr transaction = idbTransaction(requestData);
if (!transaction)
return;
MESSAGE_CHECK(transaction->isVersionChange(), connection);
transaction->deleteIndex(requestData, objectStoreIdentifier, indexName);
}
void NetworkStorageManager::renameIndex(IPC::Connection& connection, const WebCore::IDBRequestData& requestData, WebCore::IDBObjectStoreIdentifier objectStoreIdentifier, WebCore::IDBIndexIdentifier indexIdentifier, const String& newName)
{
RefPtr transaction = idbTransaction(requestData);
if (!transaction)
return;
MESSAGE_CHECK(transaction->isVersionChange(), connection);
transaction->renameIndex(requestData, objectStoreIdentifier, indexIdentifier, newName);
}
void NetworkStorageManager::putOrAdd(IPC::Connection& connection, const WebCore::IDBRequestData& requestData, const WebCore::IDBKeyData& keyData, const WebCore::IDBValue& value, const WebCore::IndexIDToIndexKeyMap& indexKeys, WebCore::IndexedDB::ObjectStoreOverwriteMode overwriteMode)
{
assertIsCurrent(workQueue());
RefPtr transaction = idbTransaction(requestData);
if (!transaction)
return;
if (value.blobURLs().size() != value.blobFilePaths().size()) {
RELEASE_LOG_FAULT(IndexedDB, "NetworkStorageManager::putOrAdd: Number of blob URLs doesn't match the number of blob file paths.");
ASSERT_NOT_REACHED();
return;
}
// Validate temporary blob paths in |value| to make sure they belong to the source process.
if (!value.blobFilePaths().isEmpty()) {
auto it = m_temporaryBlobPathsByConnection.find(connection.uniqueID());
if (it == m_temporaryBlobPathsByConnection.end()) {
RELEASE_LOG_FAULT(IndexedDB, "NetworkStorageManager::putOrAdd: IDBValue contains blob paths but none are allowed for this process");
ASSERT_NOT_REACHED();
return;
}
auto& temporaryBlobPathsForConnection = it->value;
for (auto& blobFilePath : value.blobFilePaths()) {
if (!temporaryBlobPathsForConnection.remove(blobFilePath)) {
RELEASE_LOG_FAULT(IndexedDB, "NetworkStorageManager::putOrAdd: Blob path was not created for this WebProcess");
ASSERT_NOT_REACHED();
return;
}
}
}
transaction->putOrAdd(requestData, keyData, value, indexKeys, overwriteMode);
}
void NetworkStorageManager::getRecord(const WebCore::IDBRequestData& requestData, const WebCore::IDBGetRecordData& getRecordData)
{
if (RefPtr transaction = idbTransaction(requestData))
transaction->getRecord(requestData, getRecordData);
}
void NetworkStorageManager::getAllRecords(const WebCore::IDBRequestData& requestData, const WebCore::IDBGetAllRecordsData& getAllRecordsData)
{
if (RefPtr transaction = idbTransaction(requestData))
transaction->getAllRecords(requestData, getAllRecordsData);
}
void NetworkStorageManager::getCount(const WebCore::IDBRequestData& requestData, const WebCore::IDBKeyRangeData& keyRangeData)
{
if (RefPtr transaction = idbTransaction(requestData))
transaction->getCount(requestData, keyRangeData);
}
void NetworkStorageManager::deleteRecord(const WebCore::IDBRequestData& requestData, const WebCore::IDBKeyRangeData& keyRangeData)
{
if (RefPtr transaction = idbTransaction(requestData))
transaction->deleteRecord(requestData, keyRangeData);
}
void NetworkStorageManager::openCursor(const WebCore::IDBRequestData& requestData, const WebCore::IDBCursorInfo& cursorInfo)
{
if (RefPtr transaction = idbTransaction(requestData))
transaction->openCursor(requestData, cursorInfo);
}
void NetworkStorageManager::iterateCursor(const WebCore::IDBRequestData& requestData, const WebCore::IDBIterateCursorData& cursorData)
{
if (RefPtr transaction = idbTransaction(requestData))
transaction->iterateCursor(requestData, cursorData);
}
void NetworkStorageManager::getAllDatabaseNamesAndVersions(IPC::Connection& connection, const WebCore::IDBResourceIdentifier& requestIdentifier, const WebCore::ClientOrigin& origin)
{
Ref connectionToClient = m_idbStorageRegistry->ensureConnectionToClient(connection.uniqueID(), *requestIdentifier.connectionIdentifier());
auto result = checkedOriginStorageManager(origin)->idbStorageManager(*m_idbStorageRegistry).getAllDatabaseNamesAndVersions();
connectionToClient->didGetAllDatabaseNamesAndVersions(requestIdentifier, WTFMove(result));
}
void NetworkStorageManager::cacheStorageOpenCache(const WebCore::ClientOrigin& origin, const String& cacheName, WebCore::DOMCacheEngine::CacheIdentifierCallback&& callback)
{
checkedOriginStorageManager(origin)->protectedCacheStorageManager(*protectedCacheStorageRegistry(), origin, m_queue.copyRef())->openCache(cacheName, WTFMove(callback));
}
void NetworkStorageManager::cacheStorageRemoveCache(WebCore::DOMCacheIdentifier cacheIdentifier, WebCore::DOMCacheEngine::RemoveCacheIdentifierCallback&& callback)
{
RefPtr cache = protectedCacheStorageRegistry()->cache(cacheIdentifier);
if (!cache)
return callback(makeUnexpected(WebCore::DOMCacheEngine::Error::Internal));
RefPtr cacheStorageManager = cache->manager();
if (!cacheStorageManager)
return callback(makeUnexpected(WebCore::DOMCacheEngine::Error::Internal));
cacheStorageManager->removeCache(cacheIdentifier, WTFMove(callback));
}
void NetworkStorageManager::cacheStorageAllCaches(const WebCore::ClientOrigin& origin, uint64_t updateCounter, WebCore::DOMCacheEngine::CacheInfosCallback&& callback)
{
checkedOriginStorageManager(origin)->protectedCacheStorageManager(*protectedCacheStorageRegistry(), origin, m_queue.copyRef())->allCaches(updateCounter, WTFMove(callback));
}
void NetworkStorageManager::cacheStorageReference(IPC::Connection& connection, WebCore::DOMCacheIdentifier cacheIdentifier)
{
RefPtr cache = protectedCacheStorageRegistry()->cache(cacheIdentifier);
if (!cache)
return;
RefPtr cacheStorageManager = cache->manager();
if (!cacheStorageManager)
return;
cacheStorageManager->reference(connection.uniqueID(), cacheIdentifier);
}
void NetworkStorageManager::cacheStorageDereference(IPC::Connection& connection, WebCore::DOMCacheIdentifier cacheIdentifier)
{
RefPtr cache = protectedCacheStorageRegistry()->cache(cacheIdentifier);
if (!cache)
return;
RefPtr cacheStorageManager = cache->manager();
if (!cacheStorageManager)
return;
cacheStorageManager->dereference(connection.uniqueID(), cacheIdentifier);
}
void NetworkStorageManager::lockCacheStorage(IPC::Connection& connection, const WebCore::ClientOrigin& origin)
{
checkedOriginStorageManager(origin)->protectedCacheStorageManager(*protectedCacheStorageRegistry(), origin, m_queue.copyRef())->lockStorage(connection.uniqueID());
}
void NetworkStorageManager::unlockCacheStorage(IPC::Connection& connection, const WebCore::ClientOrigin& origin)
{
if (RefPtr cacheStorageManager = originStorageManager(origin).existingCacheStorageManager())
cacheStorageManager->unlockStorage(connection.uniqueID());
}
void NetworkStorageManager::cacheStorageRetrieveRecords(WebCore::DOMCacheIdentifier cacheIdentifier, WebCore::RetrieveRecordsOptions&& options, WebCore::DOMCacheEngine::CrossThreadRecordsCallback&& callback)
{
RefPtr cache = protectedCacheStorageRegistry()->cache(cacheIdentifier);
if (!cache)
return callback(makeUnexpected(WebCore::DOMCacheEngine::Error::Internal));
cache->retrieveRecords(WTFMove(options), WTFMove(callback));
}
void NetworkStorageManager::cacheStorageRemoveRecords(WebCore::DOMCacheIdentifier cacheIdentifier, WebCore::ResourceRequest&& request, WebCore::CacheQueryOptions&& options, WebCore::DOMCacheEngine::RecordIdentifiersCallback&& callback)
{
RefPtr cache = protectedCacheStorageRegistry()->cache(cacheIdentifier);
if (!cache)
return callback(makeUnexpected(WebCore::DOMCacheEngine::Error::Internal));
cache->removeRecords(WTFMove(request), WTFMove(options), WTFMove(callback));
}
void NetworkStorageManager::cacheStoragePutRecords(IPC::Connection& connection, WebCore::DOMCacheIdentifier cacheIdentifier, Vector<WebCore::DOMCacheEngine::CrossThreadRecord>&& records, WebCore::DOMCacheEngine::RecordIdentifiersCallback&& callback)
{
RefPtr cache = protectedCacheStorageRegistry()->cache(cacheIdentifier);
if (!cache)
return callback(makeUnexpected(WebCore::DOMCacheEngine::Error::Internal));
for (auto& record : records)
MESSAGE_CHECK_COMPLETION(record.responseBodySize >= CacheStorageDiskStore::computeRealBodySizeForStorage(record.responseBody), connection, callback(makeUnexpected(WebCore::DOMCacheEngine::Error::Internal)));
cache->putRecords(WTFMove(records), WTFMove(callback));
}
void NetworkStorageManager::cacheStorageClearMemoryRepresentation(const WebCore::ClientOrigin& origin, CompletionHandler<void()>&& callback)
{
assertIsCurrent(workQueue());
auto iterator = m_originStorageManagers.find(origin);
if (iterator != m_originStorageManagers.end())
iterator->value->closeCacheStorageManager();
callback();
}
void NetworkStorageManager::cacheStorageRepresentation(CompletionHandler<void(String&&)>&& callback)
{
Vector<String> originStrings;
auto targetTypes = OptionSet<WebsiteDataType> { WebsiteDataType::DOMCache };
for (auto& origin : getAllOrigins()) {
{
CheckedRef originStorageManager = this->originStorageManager(origin);
auto fetchedTypes = originStorageManager->fetchDataTypesInList(targetTypes, false);
if (!fetchedTypes.isEmpty()) {
originStrings.append(makeString("\n{ \"origin\" : { \"topOrigin\" : \""_s,
origin.topOrigin.toString(), "\", \"clientOrigin\": \""_s,
origin.clientOrigin.toString(), "\" }, \"caches\" : "_s,
originStorageManager->protectedCacheStorageManager(*protectedCacheStorageRegistry(), origin, m_queue.copyRef())->representationString(),
'}'
));
}
}
removeOriginStorageManagerIfPossible(origin);
}
std::sort(originStrings.begin(), originStrings.end(), [](auto& a, auto& b) {
return codePointCompareLessThan(a, b);
});
StringBuilder builder;
builder.append("{ \"path\": \""_s, m_customCacheStoragePath, "\", \"origins\": ["_s);
ASCIILiteral divider = ""_s;
for (auto& origin : originStrings) {
builder.append(divider, origin);
divider = ","_s;
}
builder.append("]}"_s);
callback(builder.toString());
}
void NetworkStorageManager::dispatchTaskToBackgroundFetchManager(const WebCore::ClientOrigin& origin, Function<void(BackgroundFetchStoreManager*)>&& callback)
{
ASSERT(RunLoop::isMain());
if (m_closed) {
callback(nullptr);
return;
}
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, queue = Ref { m_queue }, origin = crossThreadCopy(origin), callback = WTFMove(callback)]() mutable {
Ref backgroundFetchManager = checkedOriginStorageManager(origin)->backgroundFetchManager(WTFMove(queue));
callback(backgroundFetchManager.ptr());
});
}
void NetworkStorageManager::notifyBackgroundFetchChange(const String& identifier, BackgroundFetchChange change)
{
if (m_parentConnection)
IPC::Connection::send(*m_parentConnection, Messages::NetworkProcessProxy::NotifyBackgroundFetchChange(m_sessionID, identifier, change), 0);
}
void NetworkStorageManager::closeServiceWorkerRegistrationFiles(CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
if (m_closed)
return completionHandler();
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
if (m_sharedServiceWorkerStorageManager)
m_sharedServiceWorkerStorageManager->closeFiles();
else {
for (auto& manager : m_originStorageManagers.values())
manager->serviceWorkerStorageManager().closeFiles();
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler();
});
});
}
void NetworkStorageManager::clearServiceWorkerRegistrations(CompletionHandler<void()>&& completionHandler)
{
ASSERT(RunLoop::isMain());
if (m_closed)
return completionHandler();
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
if (m_sharedServiceWorkerStorageManager)
m_sharedServiceWorkerStorageManager->clearAllRegistrations();
else {
for (auto& origin : getAllOrigins()) {
checkedOriginStorageManager(origin)->serviceWorkerStorageManager().clearAllRegistrations();
removeOriginStorageManagerIfPossible(origin);
}
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler();
});
});
}
void NetworkStorageManager::importServiceWorkerRegistrations(CompletionHandler<void(std::optional<Vector<WebCore::ServiceWorkerContextData>>)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
if (m_closed)
return completionHandler(std::nullopt);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
std::optional<Vector<WebCore::ServiceWorkerContextData>> result;
if (m_sharedServiceWorkerStorageManager)
result = m_sharedServiceWorkerStorageManager->importRegistrations();
else {
bool hasResult = false;
Vector<WebCore::ServiceWorkerContextData> registrations;
for (auto& origin : getAllOrigins()) {
if (auto originRegistrations = checkedOriginStorageManager(origin)->serviceWorkerStorageManager().importRegistrations()) {
hasResult = true;
registrations.appendVector(WTFMove(*originRegistrations));
}
removeOriginStorageManagerIfPossible(origin);
}
if (hasResult)
result = registrations;
}
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), result = crossThreadCopy(WTFMove(result)), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler(WTFMove(result));
});
});
}
void NetworkStorageManager::updateServiceWorkerRegistrations(Vector<WebCore::ServiceWorkerContextData>&& registrationsToUpdate, Vector<WebCore::ServiceWorkerRegistrationKey>&& registrationsToDelete, CompletionHandler<void(std::optional<Vector<WebCore::ServiceWorkerScripts>>)>&& completionHandler)
{
ASSERT(RunLoop::isMain());
if (m_closed)
return completionHandler(std::nullopt);
protectedWorkQueue()->dispatch([this, protectedThis = Ref { *this }, registrationsToUpdate = crossThreadCopy(WTFMove(registrationsToUpdate)), registrationsToDelete = crossThreadCopy(WTFMove(registrationsToDelete)), completionHandler = WTFMove(completionHandler)]() mutable {
assertIsCurrent(workQueue());
std::optional<Vector<WebCore::ServiceWorkerScripts>> result;
if (m_sharedServiceWorkerStorageManager)
result = m_sharedServiceWorkerStorageManager->updateRegistrations(WTFMove(registrationsToUpdate), WTFMove(registrationsToDelete));
else
result = updateServiceWorkerRegistrationsByOrigin(WTFMove(registrationsToUpdate), WTFMove(registrationsToDelete));
RunLoop::protectedMain()->dispatch([protectedThis = WTFMove(protectedThis), result = crossThreadCopy(WTFMove(result)), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler(WTFMove(result));
});
});
}
void NetworkStorageManager::migrateServiceWorkerRegistrationsToOrigins()
{
ASSERT(!RunLoop::isMain());
auto sharedServiceWorkerStorageManager = makeUnique<ServiceWorkerStorageManager>(m_customServiceWorkerStoragePath);
auto result = sharedServiceWorkerStorageManager->importRegistrations();
if (!result)
return;
updateServiceWorkerRegistrationsByOrigin(WTFMove(*result), { });
sharedServiceWorkerStorageManager->clearAllRegistrations();
}
Vector<WebCore::ServiceWorkerScripts> NetworkStorageManager::updateServiceWorkerRegistrationsByOrigin(Vector<WebCore::ServiceWorkerContextData>&& registrationsToUpdate, Vector<WebCore::ServiceWorkerRegistrationKey>&& registrationsToDelete)
{
ASSERT(!RunLoop::isMain());
HashMap<WebCore::ClientOrigin, std::pair<Vector<WebCore::ServiceWorkerContextData>, Vector<WebCore::ServiceWorkerRegistrationKey>>> originRegistrations;
for (auto& registration : registrationsToUpdate) {
auto origin = registration.registration.key.clientOrigin();
auto& registrations = originRegistrations.ensure(origin, []() {
return std::pair<Vector<WebCore::ServiceWorkerContextData>, Vector<WebCore::ServiceWorkerRegistrationKey>> { };
}).iterator->value.first;
registrations.append(WTFMove(registration));
}
HashMap<WebCore::ClientOrigin, Vector<WebCore::ServiceWorkerRegistrationKey>> originRegistrationsToDelete;
for (auto&& key : registrationsToDelete) {
auto origin = key.clientOrigin();
auto& keys = originRegistrations.ensure(origin, []() {
return std::pair<Vector<WebCore::ServiceWorkerContextData>, Vector<WebCore::ServiceWorkerRegistrationKey>> { };
}).iterator->value.second;
keys.append(WTFMove(key));
}
Vector<WebCore::ServiceWorkerScripts> savedScripts;
for (auto& [origin, registrations] : originRegistrations) {
auto result = checkedOriginStorageManager(origin)->serviceWorkerStorageManager().updateRegistrations(WTFMove(registrations.first), WTFMove(registrations.second));
if (result)
savedScripts.appendVector(WTFMove(*result));
}
return savedScripts;
}
bool NetworkStorageManager::shouldManageServiceWorkerRegistrationsByOrigin()
{
ASSERT(!RunLoop::isMain());
return m_unifiedOriginStorageLevel >= UnifiedOriginStorageLevel::Standard;
}
RefPtr<CacheStorageRegistry> NetworkStorageManager::protectedCacheStorageRegistry()
{
return m_cacheStorageRegistry.get();
}
RefPtr<FileSystemStorageHandleRegistry> NetworkStorageManager::protectedFileSystemStorageHandleRegistry()
{
return m_fileSystemStorageHandleRegistry;
}
std::optional<SharedPreferencesForWebProcess> NetworkStorageManager::sharedPreferencesForWebProcess(IPC::Connection& connection) const
{
assertIsCurrent(workQueue());
auto iter = m_preferencesForConnections.find(connection.uniqueID());
if (iter == m_preferencesForConnections.end())
return std::nullopt;
return iter->value;
}
} // namespace WebKit
#undef MESSAGE_CHECK_COMPLETION
#undef MESSAGE_CHECK
|