1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
|
/*
* Copyright (C) 2006-2022 Apple Inc. All rights reserved.
* Copyright (C) 2011 Google 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.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE 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 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 "DocumentLoader.h"
#include "ApplicationCacheHost.h"
#include "Archive.h"
#include "ArchiveResourceCollection.h"
#include "CachedPage.h"
#include "CachedRawResource.h"
#include "CachedResourceLoader.h"
#include "ContentExtensionError.h"
#include "ContentRuleListResults.h"
#include "ContentSecurityPolicy.h"
#include "CrossOriginOpenerPolicy.h"
#include "CustomHeaderFields.h"
#include "DNS.h"
#include "DocumentInlines.h"
#include "DocumentParser.h"
#include "DocumentWriter.h"
#include "ElementChildIteratorInlines.h"
#include "Event.h"
#include "EventNames.h"
#include "ExtensionStyleSheets.h"
#include "FormState.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "HTMLFormElement.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLObjectElement.h"
#include "HTTPHeaderNames.h"
#include "HTTPParsers.h"
#include "HistoryItem.h"
#include "HistoryController.h"
#include "IconLoader.h"
#include "InspectorInstrumentation.h"
#include "LegacySchemeRegistry.h"
#include "LinkIconCollector.h"
#include "LinkIconType.h"
#include "LoaderStrategy.h"
#include "LocalDOMWindow.h"
#include "LocalFrame.h"
#include "LocalFrameLoaderClient.h"
#include "Logging.h"
#include "MIMETypeRegistry.h"
#include "MemoryCache.h"
#include "MixedContentChecker.h"
#include "NavigationNavigationType.h"
#include "NavigationRequester.h"
#include "NavigationScheduler.h"
#include "NetworkLoadMetrics.h"
#include "NetworkStorageSession.h"
#include "OriginAccessPatterns.h"
#include "Page.h"
#include "Performance.h"
#include "PingLoader.h"
#include "PlatformStrategies.h"
#include "PolicyChecker.h"
#include "ProgressTracker.h"
#include "Quirks.h"
#include "ResourceLoadObserver.h"
#include "ResourceMonitor.h"
#include "SWClientConnection.h"
#include "ScriptableDocumentParser.h"
#include "SecurityPolicy.h"
#include "ServiceWorker.h"
#include "ServiceWorkerClientData.h"
#include "ServiceWorkerProvider.h"
#include "Settings.h"
#include "SubresourceLoader.h"
#include "TextResourceDecoder.h"
#include "UserContentProvider.h"
#include "UserContentURLPattern.h"
#include "ViolationReportType.h"
#include <wtf/Assertions.h>
#include <wtf/CompletionHandler.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/Ref.h>
#include <wtf/Scope.h>
#include <wtf/text/CString.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/WTFString.h>
#if ENABLE(APPLICATION_MANIFEST)
#include "ApplicationManifestLoader.h"
#include "HTMLHeadElement.h"
#include "HTMLLinkElement.h"
#endif
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
#include "ArchiveFactory.h"
#endif
#if ENABLE(CONTENT_FILTERING)
#include "ContentFilter.h"
#include "FrameLoadRequest.h"
#include "ScriptController.h"
#endif
#if USE(QUICK_LOOK)
#include "PreviewConverter.h"
#include "QuickLook.h"
#endif
#if PLATFORM(COCOA)
#include <wtf/cocoa/RuntimeApplicationChecksCocoa.h>
#endif
#define PAGE_ID (m_frame && m_frame->pageID() ? m_frame->pageID()->toUInt64() : 0)
#define FRAME_ID (m_frame ? m_frame->frameID().object().toUInt64() : 0)
#define IS_MAIN_FRAME (m_frame ? m_frame->isMainFrame() : false)
#define DOCUMENTLOADER_RELEASE_LOG(fmt, ...) RELEASE_LOG(Network, "%p - [pageID=%" PRIu64 ", frameID=%" PRIu64 ", isMainFrame=%d] DocumentLoader::" fmt, this, PAGE_ID, FRAME_ID, IS_MAIN_FRAME, ##__VA_ARGS__)
#define DOCUMENTLOADER_RELEASE_LOG_FORWARDABLE(fmt, ...) RELEASE_LOG_FORWARDABLE(Network, fmt, PAGE_ID, FRAME_ID, IS_MAIN_FRAME, ##__VA_ARGS__)
namespace WebCore {
#if ENABLE(CONTENT_FILTERING)
static bool& contentFilterInDocumentLoader()
{
static bool filter = false;
RELEASE_ASSERT(isMainThread());
return filter;
}
#endif
static void cancelAll(const ResourceLoaderMap& loaders)
{
for (auto& loader : copyToVector(loaders.values()))
loader->cancel();
}
static void setAllDefersLoading(const ResourceLoaderMap& loaders, bool defers)
{
for (auto& loader : copyToVector(loaders.values()))
loader->setDefersLoading(defers);
}
static HashMap<ScriptExecutionContextIdentifier, DocumentLoader*>& scriptExecutionContextIdentifierToLoaderMap()
{
static NeverDestroyed<HashMap<ScriptExecutionContextIdentifier, DocumentLoader*>> map;
return map.get();
}
DocumentLoader* DocumentLoader::fromScriptExecutionContextIdentifier(ScriptExecutionContextIdentifier identifier)
{
return scriptExecutionContextIdentifierToLoaderMap().get(identifier);
}
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(DocumentLoader);
DocumentLoader::DocumentLoader(const ResourceRequest& request, const SubstituteData& substituteData)
: FrameDestructionObserver(nullptr)
, m_cachedResourceLoader(CachedResourceLoader::create(this))
, m_originalRequest(request)
, m_substituteData(substituteData)
, m_originalRequestCopy(request)
, m_request(request)
, m_substituteResourceDeliveryTimer(*this, &DocumentLoader::substituteResourceDeliveryTimerFired)
, m_applicationCacheHost(makeUnique<ApplicationCacheHost>(*this))
, m_originalSubstituteDataWasValid(substituteData.isValid())
{
}
FrameLoader* DocumentLoader::frameLoader() const
{
if (!m_frame)
return nullptr;
return &m_frame->loader();
}
RefPtr<FrameLoader> DocumentLoader::protectedFrameLoader() const
{
return frameLoader();
}
SubresourceLoader* DocumentLoader::mainResourceLoader() const
{
if (!m_mainResource)
return nullptr;
return m_mainResource->loader();
}
DocumentLoader::~DocumentLoader()
{
ASSERT(!m_frame || !isLoading() || frameLoader()->activeDocumentLoader() != this);
ASSERT_WITH_MESSAGE(!m_waitingForContentPolicy, "The content policy callback should never outlive its DocumentLoader.");
ASSERT_WITH_MESSAGE(!m_waitingForNavigationPolicy, "The navigation policy callback should never outlive its DocumentLoader.");
m_cachedResourceLoader->clearDocumentLoader();
clearMainResource();
if (m_resultingClientId) {
ASSERT(scriptExecutionContextIdentifierToLoaderMap().contains(*m_resultingClientId));
scriptExecutionContextIdentifierToLoaderMap().remove(*m_resultingClientId);
}
if (auto createdCallback = std::exchange(m_whenDocumentIsCreatedCallback, { }))
createdCallback(nullptr);
}
RefPtr<FragmentedSharedBuffer> DocumentLoader::mainResourceData() const
{
if (m_substituteData.isValid())
return m_substituteData.protectedContent()->copy();
if (m_mainResource)
return m_mainResource->resourceBuffer();
return nullptr;
}
Document* DocumentLoader::document() const
{
if (m_frame && m_frame->loader().documentLoader() == this)
return m_frame->document();
return nullptr;
}
void DocumentLoader::replaceRequestURLForSameDocumentNavigation(const URL& url)
{
m_originalRequestCopy.setURL(url);
m_request.setURL(url);
}
void DocumentLoader::setRequest(const ResourceRequest& req)
{
// Replacing an unreachable URL with alternate content looks like a server-side
// redirect at this point, but we can replace a committed dataSource.
bool handlingUnreachableURL = false;
handlingUnreachableURL = m_substituteData.isValid() && !m_substituteData.failingURL().isEmpty();
bool shouldNotifyAboutProvisionalURLChange = false;
if (handlingUnreachableURL)
m_committed = false;
else if (isLoadingMainResource() && req.url() != m_request.url())
shouldNotifyAboutProvisionalURLChange = true;
// We should never be getting a redirect callback after the data
// source is committed, except in the unreachable URL case. It
// would be a WebFoundation bug if it sent a redirect callback after commit.
ASSERT(!m_committed);
m_request = req;
if (shouldNotifyAboutProvisionalURLChange) {
// Logging for <rdar://problem/54830233>.
if (!frameLoader()->provisionalDocumentLoader())
DOCUMENTLOADER_RELEASE_LOG("DocumentLoader::setRequest: With no provisional document loader");
protectedFrameLoader()->protectedClient()->dispatchDidChangeProvisionalURL();
}
}
void DocumentLoader::setMainDocumentError(const ResourceError& error)
{
if (!error.isNull())
DOCUMENTLOADER_RELEASE_LOG("setMainDocumentError: (type=%d, code=%d)", static_cast<int>(error.type()), error.errorCode());
m_mainDocumentError = error;
protectedFrameLoader()->protectedClient()->setMainDocumentError(this, error);
}
void DocumentLoader::mainReceivedError(const ResourceError& error, LoadWillContinueInAnotherProcess loadWillContinueInAnotherProcess)
{
ASSERT(!error.isNull());
if (auto createdCallback = std::exchange(m_whenDocumentIsCreatedCallback, { }))
createdCallback(nullptr);
if (!frameLoader())
return;
if (!error.isNull())
DOCUMENTLOADER_RELEASE_LOG("mainReceivedError: (type=%d, code=%d)", static_cast<int>(error.type()), error.errorCode());
if (m_identifierForLoadWithoutResourceLoader) {
ASSERT(!mainResourceLoader());
protectedFrameLoader()->protectedClient()->dispatchDidFailLoading(this, IsMainResourceLoad::Yes, *m_identifierForLoadWithoutResourceLoader, error);
}
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
#endif
m_applicationCacheHost->failedLoadingMainResource();
setMainDocumentError(error);
clearMainResourceLoader();
protectedFrameLoader()->receivedMainResourceError(error, loadWillContinueInAnotherProcess);
}
void DocumentLoader::frameDestroyed()
{
DOCUMENTLOADER_RELEASE_LOG("DocumentLoader::frameDestroyed: m_frame=%p", m_frame.get());
FrameDestructionObserver::frameDestroyed();
}
// Cancels the data source's pending loads. Conceptually, a data source only loads
// one document at a time, but one document may have many related resources.
// stopLoading will stop all loads initiated by the data source,
// but not loads initiated by child frames' data sources -- that's the WebFrame's job.
void DocumentLoader::stopLoading()
{
DOCUMENTLOADER_RELEASE_LOG_FORWARDABLE(DOCUMENTLOADER_STOPLOADING);
RefPtr frame = m_frame.get();
ASSERT(frame);
if (!frame)
return;
Ref<DocumentLoader> protectedThis(*this);
// In some rare cases, calling FrameLoader::stopLoading could cause isLoading() to return false.
// (This can happen when there's a single XMLHttpRequest currently loading and stopLoading causes it
// to stop loading. Because of this, we need to save it so we don't return early.
bool loading = isLoading();
if (m_committed) {
// Attempt to stop the frame if the document loader is loading, or if it is done loading but
// still parsing. Failure to do so can cause a world leak.
RefPtr document = frame->document();
if (loading || document->parsing())
frame->loader().stopLoading(UnloadEventPolicy::None);
}
for (auto& callback : m_iconLoaders.values())
callback(nullptr);
m_iconLoaders.clear();
m_iconsPendingLoadDecision.clear();
#if ENABLE(APPLICATION_MANIFEST)
m_applicationManifestLoader = nullptr;
m_finishedLoadingApplicationManifest = false;
notifyFinishedLoadingApplicationManifest();
#endif
// Always cancel multipart loaders
cancelAll(m_multipartSubresourceLoaders);
if (RefPtr document = this->document())
document->suspendFontLoading();
// Appcache uses ResourceHandle directly, DocumentLoader doesn't count these loads.
m_applicationCacheHost->stopLoadingInFrame(*frame);
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
clearArchiveResources();
#endif
if (!loading) {
// If something above restarted loading we might run into mysterious crashes like
// https://bugs.webkit.org/show_bug.cgi?id=62764 and <rdar://problem/9328684>
ASSERT(!isLoading());
return;
}
// We might run in to infinite recursion if we're stopping loading as the result of
// detaching from the frame, so break out of that recursion here.
// See <rdar://problem/9673866> for more details.
if (m_isStopping)
return;
m_isStopping = true;
// The frame may have been detached from this document by the onunload handler
if (RefPtr frameLoader = this->frameLoader()) {
DOCUMENTLOADER_RELEASE_LOG("stopLoading: canceling load");
if (isLoadingMainResource()) {
// Stop the main resource loader and let it send the cancelled message.
cancelMainResourceLoad(frameLoader->cancelledError(m_request));
} else if (!m_subresourceLoaders.isEmpty() || !m_plugInStreamLoaders.isEmpty()) {
// The main resource loader already finished loading. Set the cancelled error on the
// document and let the subresourceLoaders and pluginLoaders send individual cancelled messages below.
setMainDocumentError(frameLoader->cancelledError(m_request));
} else {
// If there are no resource loaders, we need to manufacture a cancelled message.
// (A back/forward navigation has no resource loaders because its resources are cached.)
mainReceivedError(frameLoader->cancelledError(m_request));
}
}
// We always need to explicitly cancel the Document's parser when stopping the load.
// Otherwise cancelling the parser while starting the next page load might result
// in unexpected side effects such as erroneous event dispatch. ( http://webkit.org/b/117112 )
if (RefPtr document = this->document())
document->cancelParsing();
stopLoadingSubresources();
stopLoadingPlugIns();
m_isStopping = false;
}
void DocumentLoader::commitIfReady()
{
if (!m_committed) {
m_committed = true;
RefPtr protectedFrame { m_frame.get() };
protectedFrameLoader()->commitProvisionalLoad();
}
}
bool DocumentLoader::isLoading() const
{
// if (document() && document()->hasActiveParser())
// return true;
// FIXME: The above code should be enabled, but it seems to cause
// http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
// see http://webkit.org/b/110554 and http://webkit.org/b/110401
return isLoadingMainResource() || !m_subresourceLoaders.isEmpty() || !m_plugInStreamLoaders.isEmpty();
}
void DocumentLoader::notifyFinished(CachedResource& resource, const NetworkLoadMetrics& metrics, LoadWillContinueInAnotherProcess loadWillContinueInAnotherProcess)
{
ASSERT(isMainThread());
#if ENABLE(CONTENT_FILTERING)
if (m_contentFilter && !m_contentFilter->continueAfterNotifyFinished(resource))
return;
#endif
if (RefPtr document = this->document()) {
if (RefPtr domWindow = document->domWindow())
domWindow->protectedPerformance()->navigationFinished(metrics);
}
ASSERT_UNUSED(resource, m_mainResource == &resource);
ASSERT(m_mainResource);
if (!m_mainResource->errorOccurred() && !m_mainResource->wasCanceled()) {
finishedLoading();
return;
}
if (m_request.cachePolicy() == ResourceRequestCachePolicy::ReturnCacheDataDontLoad && !m_mainResource->wasCanceled()) {
protectedFrameLoader()->retryAfterFailedCacheOnlyMainResourceLoad();
return;
}
if (!m_mainResource->resourceError().isNull())
DOCUMENTLOADER_RELEASE_LOG("notifyFinished: canceling load (type=%d, code=%d)", static_cast<int>(m_mainResource->resourceError().type()), m_mainResource->resourceError().errorCode());
mainReceivedError(m_mainResource->resourceError(), loadWillContinueInAnotherProcess);
}
void DocumentLoader::finishedLoading()
{
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(!m_frame->page()->defersLoading() || protectedFrameLoader()->stateMachine().creatingInitialEmptyDocument() || InspectorInstrumentation::isDebuggerPaused(m_frame.get()));
#endif
Ref<DocumentLoader> protectedThis(*this);
if (m_identifierForLoadWithoutResourceLoader) {
// A didFinishLoading delegate might try to cancel the load (despite it
// being finished). Clear m_identifierForLoadWithoutResourceLoader
// before calling dispatchDidFinishLoading so that we don't later try to
// cancel the already-finished substitute load.
NetworkLoadMetrics emptyMetrics;
ResourceLoaderIdentifier identifier = *std::exchange(m_identifierForLoadWithoutResourceLoader, std::nullopt);
protectedFrameLoader()->notifier().dispatchDidFinishLoading(this, IsMainResourceLoad::Yes, identifier, emptyMetrics, nullptr);
}
maybeFinishLoadingMultipartContent();
timing().markEndTime();
commitIfReady();
RefPtr frameLoader = this->frameLoader();
if (!frameLoader)
return;
if (!maybeCreateArchive()) {
// If this is an empty document, it will not have actually been created yet. Commit dummy data so that
// DocumentWriter::begin() gets called and creates the Document.
if (!m_gotFirstByte)
commitData(SharedBuffer::create());
frameLoader = this->frameLoader();
if (!frameLoader)
return;
Ref frameLoaderClient = frameLoader->client();
frameLoaderClient->finishedLoading(this);
frameLoaderClient->loadStorageAccessQuirksIfNeeded();
}
m_writer.end();
if (!m_mainDocumentError.isNull())
return;
clearMainResourceLoader();
frameLoader = this->frameLoader();
if (!frameLoader)
return;
if (!frameLoader->stateMachine().creatingInitialEmptyDocument())
frameLoader->checkLoadComplete();
m_applicationCacheHost->finishedLoadingMainResource();
}
static bool isRedirectToGetAfterPost(const ResourceRequest& oldRequest, const ResourceRequest& newRequest)
{
return oldRequest.httpMethod() == "POST"_s && newRequest.httpMethod() == "GET"_s;
}
bool DocumentLoader::isPostOrRedirectAfterPost(const ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
if (newRequest.httpMethod() == "POST"_s)
return true;
int status = redirectResponse.httpStatusCode();
if (((status >= 301 && status <= 303) || status == 307)
&& m_originalRequest.httpMethod() == "POST"_s)
return true;
return false;
}
void DocumentLoader::handleSubstituteDataLoadNow()
{
Ref<DocumentLoader> protectedThis = Ref { *this };
if (m_substituteData.response().isRedirection()) {
auto newRequest = m_request.redirectedRequest(m_substituteData.response(), true);
auto substituteData = std::exchange(m_substituteData, { });
auto callback = [protectedThis, newRequest] (auto&& request) mutable {
if (request.isNull())
return;
protectedThis->loadMainResource(WTFMove(newRequest));
};
redirectReceived(WTFMove(newRequest), substituteData.response(), WTFMove(callback));
return;
}
ResourceResponse response = m_substituteData.response();
if (response.url().isEmpty())
response = ResourceResponse(m_request.url(), m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding());
#if ENABLE(CONTENT_EXTENSIONS)
if (RefPtr page = m_frame ? m_frame->page() : nullptr) {
// We intentionally do nothing with the results of this call.
// We want the CSS to be loaded for us, but we ignore any attempt to block or upgrade the connection since there is no connection.
page->protectedUserContentProvider()->processContentRuleListsForLoad(*page, response.url(), ContentExtensions::ResourceType::Document, *this);
}
#endif
responseReceived(response, nullptr);
}
bool DocumentLoader::setControllingServiceWorkerRegistration(ServiceWorkerRegistrationData&& data)
{
if (!m_loadingMainResource)
return false;
ASSERT(!m_gotFirstByte);
m_serviceWorkerRegistrationData = makeUnique<ServiceWorkerRegistrationData>(WTFMove(data));
return true;
}
void DocumentLoader::matchRegistration(const URL& url, SWClientConnection::RegistrationCallback&& callback)
{
bool shouldTryLoadingThroughServiceWorker = m_canUseServiceWorkers && !frameLoader()->isReloadingFromOrigin() && m_frame->page() && url.protocolIsInHTTPFamily();
if (!shouldTryLoadingThroughServiceWorker) {
callback(std::nullopt);
return;
}
RefPtr frame = m_frame.get();
auto origin = (!frame->isMainFrame() && frame->document()) ? frame->protectedDocument()->topOrigin().data() : SecurityOriginData::fromURL(url);
if (!ServiceWorkerProvider::singleton().protectedServiceWorkerConnection()->mayHaveServiceWorkerRegisteredForOrigin(origin)) {
callback(std::nullopt);
return;
}
Ref connection = ServiceWorkerProvider::singleton().serviceWorkerConnection();
connection->matchRegistration(WTFMove(origin), url, WTFMove(callback));
}
void DocumentLoader::redirectReceived(CachedResource& resource, ResourceRequest&& request, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
{
ASSERT_UNUSED(resource, &resource == m_mainResource);
redirectReceived(WTFMove(request), redirectResponse, WTFMove(completionHandler));
}
void DocumentLoader::redirectReceived(ResourceRequest&& request, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
{
if (m_serviceWorkerRegistrationData) {
m_serviceWorkerRegistrationData = { };
unregisterReservedServiceWorkerClient();
}
willSendRequest(WTFMove(request), redirectResponse, [completionHandler = WTFMove(completionHandler), protectedThis = Ref { *this }, this] (ResourceRequest&& request) mutable {
ASSERT(!m_substituteData.isValid());
if (request.isNull() || !m_mainDocumentError.isNull() || !m_frame) {
completionHandler({ });
return;
}
if (m_applicationCacheHost->canLoadMainResource(request)) {
auto url = request.url();
// Let's check service worker registration to see whether loading from network or not.
this->matchRegistration(url, [request = WTFMove(request), completionHandler = WTFMove(completionHandler), protectedThis = Ref { *this }, this](auto&& registrationData) mutable {
if (!m_mainDocumentError.isNull() || !m_frame) {
completionHandler({ });
return;
}
if (!registrationData && this->tryLoadingRedirectRequestFromApplicationCache(request)) {
completionHandler({ });
return;
}
completionHandler(WTFMove(request));
});
return;
}
completionHandler(WTFMove(request));
});
}
void DocumentLoader::willSendRequest(ResourceRequest&& newRequest, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
{
// Note that there are no asserts here as there are for the other callbacks. This is due to the
// fact that this "callback" is sent when starting every load, and the state of callback
// deferrals plays less of a part in this function in preventing the bad behavior deferring
// callbacks is meant to prevent.
ASSERT(!newRequest.isNull());
// Logging for <rdar://problem/54830233>.
if (!frameLoader() || !frameLoader()->provisionalDocumentLoader())
DOCUMENTLOADER_RELEASE_LOG("willSendRequest: With no provisional document loader");
bool didReceiveRedirectResponse = !redirectResponse.isNull();
if (!protectedFrameLoader()->checkIfFormActionAllowedByCSP(newRequest.url(), didReceiveRedirectResponse, redirectResponse.url())) {
DOCUMENTLOADER_RELEASE_LOG("willSendRequest: canceling - form action not allowed by CSP");
cancelMainResourceLoad(protectedFrameLoader()->cancelledError(newRequest));
return completionHandler(WTFMove(newRequest));
}
RefPtr frame = m_frame.get();
if (auto requester = m_triggeringAction.requester(); requester && requester->documentIdentifier) {
if (RefPtr requestingDocument = Document::allDocumentsMap().get(requester->documentIdentifier); requestingDocument && requestingDocument->frame()) {
if (frame && requestingDocument->isNavigationBlockedByThirdPartyIFrameRedirectBlocking(*frame, newRequest.url())) {
DOCUMENTLOADER_RELEASE_LOG("willSendRequest: canceling - cross-site redirect of top frame triggered by third-party iframe");
if (RefPtr document = frame->document()) {
auto message = makeString("Unsafe JavaScript attempt to initiate navigation for frame with URL '"_s
, document->url().string()
, "' from frame with URL '"_s
, requestingDocument->url().string()
, "'. The frame attempting navigation of the top-level window is cross-origin or untrusted and the user has never interacted with the frame."_s);
document->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
}
cancelMainResourceLoad(protectedFrameLoader()->cancelledError(newRequest));
return completionHandler(WTFMove(newRequest));
}
}
}
ASSERT(timing().startTime());
if (didReceiveRedirectResponse) {
if (newRequest.url().protocolIsAbout() || newRequest.url().protocolIsData()) {
DOCUMENTLOADER_RELEASE_LOG("willSendRequest: canceling - redirecting URL scheme is not allowed");
loadErrorDocument();
if (frame && frame->document())
frame->protectedDocument()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, makeString("Not allowed to redirect to "_s, newRequest.url().stringCenterEllipsizedToLength(), " due to its scheme"_s));
if (RefPtr frameLoader = this->frameLoader())
cancelMainResourceLoad(frameLoader->blockedError(newRequest));
return completionHandler(WTFMove(newRequest));
}
// If the redirecting url is not allowed to display content from the target origin,
// then block the redirect.
Ref<SecurityOrigin> redirectingOrigin(SecurityOrigin::create(redirectResponse.url()));
if (!redirectingOrigin.get().canDisplay(newRequest.url(), OriginAccessPatternsForWebProcess::singleton())) {
DOCUMENTLOADER_RELEASE_LOG("willSendRequest: canceling - redirecting URL not allowed to display content from target");
FrameLoader::reportLocalLoadFailed(frame.get(), newRequest.url().string());
cancelMainResourceLoad(protectedFrameLoader()->cancelledError(newRequest));
return completionHandler(WTFMove(newRequest));
}
if (!portAllowed(newRequest.url())) {
DOCUMENTLOADER_RELEASE_LOG("willSendRequest: canceling - redirecting to a URL with a blocked port");
if (frame)
FrameLoader::reportBlockedLoadFailed(*frame, newRequest.url());
cancelMainResourceLoad(protectedFrameLoader()->blockedError(newRequest));
return completionHandler(WTFMove(newRequest));
}
if (isIPAddressDisallowed(newRequest.url())) {
DOCUMENTLOADER_RELEASE_LOG("willSendRequest: canceling - redirecting to a URL with a disallowed IP address");
if (frame)
FrameLoader::reportBlockedLoadFailed(*frame, newRequest.url());
cancelMainResourceLoad(protectedFrameLoader()->blockedError(newRequest));
return completionHandler(WTFMove(newRequest));
}
}
ASSERT(frame);
RefPtr topFrame = dynamicDowncast<LocalFrame>(frame->tree().top());
RefPtr document = frame->document();
ASSERT(document);
// Update cookie policy base URL as URL changes, except for subframes, which use the
// URL of the main frame which doesn't change when we redirect.
if (frame->isMainFrame())
newRequest.setFirstPartyForCookies(newRequest.url());
FrameLoader::addSameSiteInfoToRequestIfNeeded(newRequest, document.get());
if (!didReceiveRedirectResponse)
protectedFrameLoader()->protectedClient()->dispatchWillChangeDocument(document->url(), newRequest.url());
// If we're fielding a redirect in response to a POST, force a load from origin, since
// this is a common site technique to return to a page viewing some data that the POST
// just modified.
// Also, POST requests always load from origin, but this does not affect subresources.
if (newRequest.cachePolicy() == ResourceRequestCachePolicy::UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
newRequest.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
if (isRedirectToGetAfterPost(m_request, newRequest))
newRequest.clearHTTPOrigin();
if (topFrame && topFrame != frame.get()) {
// We shouldn't check for mixed content against the current frame when navigating; we only need to be concerned with the ancestor frames.
RefPtr parentFrame = dynamicDowncast<LocalFrame>(frame->tree().parent());
if (!parentFrame)
return completionHandler(WTFMove(newRequest));
if (MixedContentChecker::shouldBlockRequestForDisplayableContent(*parentFrame, newRequest.url(), MixedContentChecker::ContentType::Active)) {
cancelMainResourceLoad(protectedFrameLoader()->cancelledError(newRequest));
return completionHandler(WTFMove(newRequest));
}
}
if (!newRequest.url().host().isEmpty() && SecurityOrigin::shouldIgnoreHost(newRequest.url())) {
auto url = newRequest.url();
url.removeHostAndPort();
newRequest.setURL(WTFMove(url));
}
#if ENABLE(CONTENT_FILTERING)
if (m_contentFilter && !m_contentFilter->continueAfterWillSendRequest(newRequest, redirectResponse))
return completionHandler(WTFMove(newRequest));
#endif
setRequest(newRequest);
if (!didReceiveRedirectResponse)
return completionHandler(WTFMove(newRequest));
auto navigationPolicyCompletionHandler = [this, protectedThis = Ref { *this }, frame, completionHandler = WTFMove(completionHandler)] (ResourceRequest&& request, WeakPtr<FormState>&&, NavigationPolicyDecision navigationPolicyDecision) mutable {
m_waitingForNavigationPolicy = false;
switch (navigationPolicyDecision) {
case NavigationPolicyDecision::IgnoreLoad:
case NavigationPolicyDecision::LoadWillContinueInAnotherProcess:
stopLoadingForPolicyChange(navigationPolicyDecision == NavigationPolicyDecision::LoadWillContinueInAnotherProcess ? LoadWillContinueInAnotherProcess::Yes : LoadWillContinueInAnotherProcess::No);
break;
case NavigationPolicyDecision::ContinueLoad:
break;
}
completionHandler(WTFMove(request));
};
ASSERT(!m_waitingForNavigationPolicy);
m_waitingForNavigationPolicy = true;
// FIXME: Add a load type check.
auto& policyChecker = frameLoader()->policyChecker();
RELEASE_ASSERT(!isBackForwardLoadType(policyChecker.loadType()) || frame->loader().history().provisionalItem());
policyChecker.checkNavigationPolicy(WTFMove(newRequest), redirectResponse, WTFMove(navigationPolicyCompletionHandler));
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#process-a-navigate-fetch (Step 12.5.6)
std::optional<CrossOriginOpenerPolicyEnforcementResult> DocumentLoader::doCrossOriginOpenerHandlingOfResponse(const ResourceResponse& response)
{
// COOP only applies to top-level browsing contexts.
RefPtr frame = m_frame.get();
if (!frame->isMainFrame())
return std::nullopt;
RefPtr document = frame->document();
if (!document || !frame->document()->settings().crossOriginOpenerPolicyEnabled())
return std::nullopt;
URL openerURL;
if (RefPtr openerFrame = dynamicDowncast<LocalFrame>(frame->opener()))
openerURL = openerFrame->document() ? openerFrame->document()->url() : URL();
auto currentCoopEnforcementResult = CrossOriginOpenerPolicyEnforcementResult::from(document->url(), document->securityOrigin(), document->crossOriginOpenerPolicy(), m_triggeringAction.requester(), openerURL);
auto newCoopEnforcementResult = WebCore::doCrossOriginOpenerHandlingOfResponse(*document, response, m_triggeringAction.requester(), m_contentSecurityPolicy.get(), frame->effectiveSandboxFlags(), m_request.httpReferrer(), frameLoader()->stateMachine().isDisplayingInitialEmptyDocument(), currentCoopEnforcementResult);
if (!newCoopEnforcementResult) {
cancelMainResourceLoad(protectedFrameLoader()->cancelledError(m_request));
return std::nullopt;
}
return newCoopEnforcementResult;
}
bool DocumentLoader::tryLoadingRequestFromApplicationCache()
{
m_applicationCacheHost->maybeLoadMainResource(m_request, m_substituteData);
return tryLoadingSubstituteData();
}
void DocumentLoader::setRedirectionAsSubstituteData(ResourceResponse&& response)
{
ASSERT(response.isRedirection());
m_substituteData = { FragmentedSharedBuffer::create(), { }, WTFMove(response), SubstituteData::SessionHistoryVisibility::Visible };
}
bool DocumentLoader::tryLoadingSubstituteData()
{
if (!m_substituteData.isValid() || !m_frame->page())
return false;
DOCUMENTLOADER_RELEASE_LOG("startLoadingMainResource: Returning substitute data");
m_identifierForLoadWithoutResourceLoader = ResourceLoaderIdentifier::generate();
protectedFrameLoader()->notifier().assignIdentifierToInitialRequest(*m_identifierForLoadWithoutResourceLoader, IsMainResourceLoad::No, this, m_request);
protectedFrameLoader()->notifier().dispatchWillSendRequest(this, *m_identifierForLoadWithoutResourceLoader, m_request, ResourceResponse(), nullptr);
if (!m_deferMainResourceDataLoad || protectedFrameLoader()->loadsSynchronously())
handleSubstituteDataLoadNow();
else {
auto loadData = [weakThis = WeakPtr { *this }] {
if (RefPtr protectedThis = weakThis.get()) {
protectedThis->m_dataLoadToken.clear();
protectedThis->handleSubstituteDataLoadNow();
}
};
#if USE(COCOA_EVENT_LOOP)
RunLoop::dispatch(*m_frame->page()->scheduledRunLoopPairs(), WTFMove(loadData));
#else
RunLoop::protectedCurrent()->dispatch(WTFMove(loadData));
#endif
}
return true;
}
bool DocumentLoader::tryLoadingRedirectRequestFromApplicationCache(const ResourceRequest& request)
{
m_applicationCacheHost->maybeLoadMainResourceForRedirect(request, m_substituteData);
if (!m_substituteData.isValid())
return false;
RELEASE_ASSERT(m_mainResource);
RefPtr loader = m_mainResource->loader();
m_identifierForLoadWithoutResourceLoader = loader ? loader->identifier() : m_mainResource->identifierForLoadWithoutResourceLoader();
// We need to remove our reference to the CachedResource in favor of a SubstituteData load, which can triger the cancellation of the underyling ResourceLoader.
// If the ResourceLoader is indeed cancelled, it would normally send resource load callbacks.
// Therefore, sever our relationship with the network load but prevent the ResourceLoader from sending ResourceLoadNotifier callbacks.
RefPtr resourceLoader = mainResourceLoader();
if (resourceLoader) {
ASSERT(resourceLoader->shouldSendResourceLoadCallbacks());
resourceLoader->setSendCallbackPolicy(SendCallbackPolicy::DoNotSendCallbacks);
}
clearMainResource();
if (resourceLoader)
resourceLoader->setSendCallbackPolicy(SendCallbackPolicy::SendCallbacks);
handleSubstituteDataLoadNow();
return true;
}
void DocumentLoader::stopLoadingAfterXFrameOptionsOrContentSecurityPolicyDenied(ResourceLoaderIdentifier identifier, const ResourceResponse& response)
{
Ref<DocumentLoader> protectedThis { *this };
InspectorInstrumentation::continueAfterXFrameOptionsDenied(*protectedFrame(), identifier, *this, response);
loadErrorDocument();
// The load event might have detached this frame. In that case, the load will already have been cancelled during detach.
if (RefPtr frameLoader = this->frameLoader())
cancelMainResourceLoad(frameLoader->cancelledError(m_request));
}
static URL microsoftTeamsRedirectURL()
{
return URL { "https://www.microsoft.com/en-us/microsoft-365/microsoft-teams/"_str };
}
bool DocumentLoader::shouldClearContentSecurityPolicyForResponse(const ResourceResponse& response) const
{
return response.httpHeaderField(HTTPHeaderName::ContentSecurityPolicy).isNull() && !m_isLoadingMultipartContent;
}
void DocumentLoader::responseReceived(CachedResource& resource, const ResourceResponse& response, CompletionHandler<void()>&& completionHandler)
{
ASSERT_UNUSED(resource, m_mainResource == &resource);
RefPtr frame = m_frame.get();
if (shouldClearContentSecurityPolicyForResponse(response))
m_contentSecurityPolicy = nullptr;
else {
// FIXME(294912): Clean up use of bare pointers for ReportingClient
ReportingClient* reportingClient = nullptr;
if (frame && frame->document())
reportingClient = frame->document();
if (!m_contentSecurityPolicy)
m_contentSecurityPolicy = makeUnique<ContentSecurityPolicy>(URL { response.url() }, nullptr, reportingClient);
m_contentSecurityPolicy->didReceiveHeaders(ContentSecurityPolicyResponseHeaders { response }, m_request.httpReferrer(), ContentSecurityPolicy::ReportParsingErrors::No);
}
if (frame && frame->document() && frame->document()->settings().crossOriginOpenerPolicyEnabled())
m_responseCOOP = obtainCrossOriginOpenerPolicy(response);
if (frame && frame->settings().clearSiteDataHTTPHeaderEnabled())
m_responseClearSiteDataValues = parseClearSiteDataHeader(response);
// FIXME(218779): Remove this quirk once microsoft.com completes their login flow redesign.
if (frame && frame->document()) {
Ref document = *frame->document();
if (Quirks::isMicrosoftTeamsRedirectURL(response.url())) {
auto firstPartyDomain = RegistrableDomain(response.url());
if (auto loginDomains = NetworkStorageSession::subResourceDomainsInNeedOfStorageAccessForFirstParty(firstPartyDomain)) {
if (!Quirks::hasStorageAccessForAllLoginDomains(*loginDomains, firstPartyDomain)) {
frame->protectedNavigationScheduler()->scheduleRedirect(document, 0, microsoftTeamsRedirectURL(), IsMetaRefresh::No);
completionHandler();
return;
}
}
}
}
if (m_canUseServiceWorkers && response.source() == ResourceResponse::Source::MemoryCache) {
matchRegistration(response.url(), [this, protectedThis = Ref { *this }, response, completionHandler = WTFMove(completionHandler)](auto&& registrationData) mutable {
if (!m_mainDocumentError.isNull() || !m_frame) {
completionHandler();
return;
}
if (registrationData)
m_serviceWorkerRegistrationData = makeUnique<ServiceWorkerRegistrationData>(WTFMove(*registrationData));
responseReceived(response, WTFMove(completionHandler));
});
return;
}
responseReceived(response, WTFMove(completionHandler));
}
void DocumentLoader::responseReceived(const ResourceResponse& response, CompletionHandler<void()>&& completionHandler)
{
ASSERT(response.certificateInfo());
CompletionHandlerCallingScope completionHandlerCaller(WTFMove(completionHandler));
#if ENABLE(CONTENT_FILTERING)
if (m_contentFilter && !m_contentFilter->continueAfterResponseReceived(response))
return;
#endif
Ref<DocumentLoader> protectedThis(*this);
bool willLoadFallback = m_applicationCacheHost->maybeLoadFallbackForMainResponse(request(), response);
// The memory cache doesn't understand the application cache or its caching rules. So if a main resource is served
// from the application cache, ensure we don't save the result for future use.
if (willLoadFallback)
MemoryCache::singleton().remove(*m_mainResource);
if (willLoadFallback)
return;
ASSERT(m_identifierForLoadWithoutResourceLoader || m_mainResource);
ResourceLoaderIdentifier identifier = m_identifierForLoadWithoutResourceLoader ? *m_identifierForLoadWithoutResourceLoader : *m_mainResource->resourceLoaderIdentifier();
if (m_substituteData.isValid() || !platformStrategies()->loaderStrategy()->havePerformedSecurityChecks(response)) {
auto url = response.url();
RefPtr frame = m_frame.get();
// FIXME(294912): Clean up use of bare pointers for ReportingClient
ReportingClient* reportingClient = nullptr;
if (frame && frame->document())
reportingClient = frame->document();
ContentSecurityPolicy contentSecurityPolicy(URL { url }, this, reportingClient);
contentSecurityPolicy.didReceiveHeaders(ContentSecurityPolicyResponseHeaders { response }, m_request.httpReferrer());
if (frame && !contentSecurityPolicy.allowFrameAncestors(*frame, url)) {
stopLoadingAfterXFrameOptionsOrContentSecurityPolicyDenied(identifier, response);
return;
}
if (frame && !contentSecurityPolicy.overridesXFrameOptions()) {
String frameOptions = response.httpHeaderFields().get(HTTPHeaderName::XFrameOptions);
if (!frameOptions.isNull()) {
if (protectedFrameLoader()->shouldInterruptLoadForXFrameOptions(frameOptions, url, identifier)) {
auto message = makeString("Refused to display '"_s, url.stringCenterEllipsizedToLength(), "' in a frame because it set 'X-Frame-Options' to '"_s, frameOptions, "'."_s);
frame->protectedDocument()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, identifier.toUInt64());
stopLoadingAfterXFrameOptionsOrContentSecurityPolicyDenied(identifier, response);
return;
}
}
}
}
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
#endif
if (m_isLoadingMultipartContent) {
setupForReplace();
m_mainResource->clear();
} else if (response.isMultipart())
m_isLoadingMultipartContent = true;
m_response = response;
if (m_identifierForLoadWithoutResourceLoader) {
RefPtr frameLoader = this->frameLoader();
if (m_mainResource && m_mainResource->wasRedirected()) {
ASSERT(m_mainResource->status() == CachedResource::Status::Cached);
if (frameLoader)
frameLoader->protectedClient()->dispatchDidReceiveServerRedirectForProvisionalLoad();
}
addResponse(m_response);
if (frameLoader)
frameLoader->notifier().dispatchDidReceiveResponse(this, *m_identifierForLoadWithoutResourceLoader, m_response, 0);
}
ASSERT(!m_waitingForContentPolicy);
ASSERT(frameLoader());
m_waitingForContentPolicy = true;
// Always show content with valid substitute data.
if (m_substituteData.isValid()) {
continueAfterContentPolicy(PolicyAction::Use);
return;
}
RefPtr frame = m_frame.get();
#if ENABLE(FTPDIR)
// Respect the hidden FTP Directory Listing pref so it can be tested even if the policy delegate might otherwise disallow it
if (frame && frame->settings().forceFTPDirectoryListings() && m_response.mimeType() == "application/x-ftp-directory"_s) {
continueAfterContentPolicy(PolicyAction::Use);
return;
}
#endif
if (!frame) {
DOCUMENTLOADER_RELEASE_LOG("responseReceived by DocumentLoader with null frame");
return;
}
RefPtr<SubresourceLoader> mainResourceLoader = this->mainResourceLoader();
if (mainResourceLoader)
mainResourceLoader->markInAsyncResponsePolicyCheck();
protectedFrameLoader()->checkContentPolicy(m_response, [this, protectedThis = Ref { *this }, mainResourceLoader = WTFMove(mainResourceLoader),
completionHandler = completionHandlerCaller.release()] (PolicyAction policy) mutable {
continueAfterContentPolicy(policy);
if (mainResourceLoader)
mainResourceLoader->didReceiveResponsePolicy();
if (completionHandler)
completionHandler();
});
}
// Prevent web archives from loading if
// 1) it is remote;
// 2) it is not the main frame;
// 3) it is not any of { loaded by clients; loaded by drag; reloaded from any of the previous two };
// because they can claim to be from any domain and thus avoid cross-domain security checks (4120255, 45524528, 47610130).
bool DocumentLoader::disallowWebArchive() const
{
String mimeType = m_response.mimeType();
if (mimeType.isNull() || !MIMETypeRegistry::isWebArchiveMIMEType(mimeType))
return false;
#if USE(QUICK_LOOK)
if (isQuickLookPreviewURL(m_response.url()))
return false;
#endif
if (m_substituteData.isValid())
return false;
if (!LegacySchemeRegistry::shouldTreatURLSchemeAsLocal(m_request.url().protocol()))
return true;
#if ENABLE(WEB_ARCHIVE)
// On purpose of maintaining existing tests.
bool alwaysAllowLocalWebArchive = frame()->mainFrame().settings().alwaysAllowLocalWebarchive();
#else
bool alwaysAllowLocalWebArchive { false };
#endif
if (!frame() || (frame()->isMainFrame() && allowsWebArchiveForMainFrame()) || alwaysAllowLocalWebArchive)
return false;
return true;
}
// Prevent data URIs from loading as the main frame unless the result of user action.
bool DocumentLoader::disallowDataRequest() const
{
if (!m_response.url().protocolIsData())
return false;
if (!frame() || !frame()->isMainFrame() || allowsDataURLsForMainFrame() || frame()->settings().allowTopNavigationToDataURLs())
return false;
if (RefPtr currentDocument = frame()->document()) {
ResourceLoaderIdentifier identifier = m_identifierForLoadWithoutResourceLoader ? *m_identifierForLoadWithoutResourceLoader : *m_mainResource->resourceLoaderIdentifier();
currentDocument->addConsoleMessage(MessageSource::Security, MessageLevel::Error, makeString("Not allowed to navigate top frame to data URL '"_s, m_response.url().stringCenterEllipsizedToLength(), "'."_s), identifier.toUInt64());
}
DOCUMENTLOADER_RELEASE_LOG("continueAfterContentPolicy: cannot show URL");
return true;
}
void DocumentLoader::continueAfterContentPolicy(PolicyAction policy)
{
ASSERT(m_waitingForContentPolicy);
m_waitingForContentPolicy = false;
if (isStopping())
return;
RefPtr frame = m_frame.get();
if (!frame) {
DOCUMENTLOADER_RELEASE_LOG("continueAfterContentPolicy: policyAction=%i received by DocumentLoader with null frame", (int)policy);
return;
}
switch (policy) {
case PolicyAction::Use: {
if (!protectedFrameLoader()->protectedClient()->canShowMIMEType(m_response.mimeType()) || disallowWebArchive() || disallowDataRequest()) {
protectedFrameLoader()->policyChecker().cannotShowMIMEType(m_response);
// Check reachedTerminalState since the load may have already been canceled inside of _handleUnimplementablePolicyWithErrorCode::.
stopLoadingForPolicyChange();
return;
}
break;
}
case PolicyAction::Download: {
// m_mainResource can be null, e.g. when loading a substitute resource from application cache.
if (!m_mainResource) {
DOCUMENTLOADER_RELEASE_LOG("continueAfterContentPolicy: cannot show URL");
mainReceivedError(platformStrategies()->loaderStrategy()->cannotShowURLError(m_request));
return;
}
if (RefPtr mainResourceLoader = this->mainResourceLoader())
InspectorInstrumentation::continueWithPolicyDownload(*frame, *mainResourceLoader->identifier(), *this, m_response);
if (!frame->effectiveSandboxFlags().contains(SandboxFlag::Downloads)) {
// When starting the request, we didn't know that it would result in download and not navigation. Now we know that main document URL didn't change.
// Download may use this knowledge for purposes unrelated to cookies, notably for setting file quarantine data.
protectedFrameLoader()->setOriginalURLForDownloadRequest(m_request);
if (m_request.url().protocolIsData()) {
// We decode data URL internally, there is no resource load to convert.
protectedFrameLoader()->protectedClient()->startDownload(m_request);
} else
protectedFrameLoader()->protectedClient()->convertMainResourceLoadToDownload(this, m_request, m_response);
} else if (frame->document())
frame->protectedDocument()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to download due to sandboxing"_s);
// The main resource might be loading from the memory cache, or its loader might have gone missing.
if (RefPtr loader = mainResourceLoader()) {
loader->didFail(interruptedForPolicyChangeError());
return;
}
// We must stop loading even if there is no main resource loader. Otherwise, we might remain
// the client of a CachedRawResource that will continue to send us data.
stopLoadingForPolicyChange();
return;
}
case PolicyAction::LoadWillContinueInAnotherProcess:
ASSERT_NOT_REACHED();
#if !ASSERT_ENABLED
FALLTHROUGH;
#endif
case PolicyAction::Ignore:
if (RefPtr mainResourceLoader = this->mainResourceLoader())
InspectorInstrumentation::continueWithPolicyIgnore(*frame, *mainResourceLoader->identifier(), *this, m_response);
stopLoadingForPolicyChange();
return;
}
if (m_response.isInHTTPFamily()) {
int status = m_response.httpStatusCode(); // Status may be zero when loading substitute data, in particular from a WebArchive.
if (status && (status < 200 || status >= 300)) {
if (RefPtr owner = dynamicDowncast<HTMLObjectElement>(frame->ownerElement())) {
owner->renderFallbackContent();
// object elements are no longer rendered after we fallback, so don't
// keep trying to process data from their load
cancelMainResourceLoad(protectedFrameLoader()->cancelledError(m_request));
}
}
}
if (!isStopping() && m_substituteData.isValid() && isLoadingMainResource()) {
RefPtr content = m_substituteData.content();
if (content && content->size()) {
content->forEachSegmentAsSharedBuffer([&](auto&& buffer) {
dataReceived(buffer);
});
}
if (isLoadingMainResource())
finishedLoading();
// Remove ourselves as a client of this CachedResource as we've decided to commit substitute data but the
// load may keep going and be useful to other clients of the CachedResource. If we did not do this, we
// may receive data later on even though this DocumentLoader has finished loading.
clearMainResource();
}
}
void DocumentLoader::commitLoad(const SharedBuffer& data)
{
// Both unloading the old page and parsing the new page may execute JavaScript which destroys the datasource
// by starting a new load, so retain temporarily.
RefPtr protectedFrame { m_frame.get() };
Ref protectedThis { *this };
commitIfReady();
RefPtr frameLoader = this->frameLoader();
if (!frameLoader)
return;
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
if (ArchiveFactory::isArchiveMIMEType(response().mimeType()))
return;
#endif
Ref client = frameLoader->client();
client->committedLoad(this, data);
if (isMultipartReplacingLoad())
client->didReplaceMultipartContent();
}
ResourceError DocumentLoader::interruptedForPolicyChangeError() const
{
if (!frameLoader()) {
ResourceError error;
error.setType(ResourceError::Type::Cancellation);
return error;
}
auto error = platformStrategies()->loaderStrategy()->interruptedForPolicyChangeError(request());
error.setType(ResourceError::Type::Cancellation);
return error;
}
void DocumentLoader::stopLoadingForPolicyChange(LoadWillContinueInAnotherProcess loadWillContinueInAnotherProcess)
{
cancelMainResourceLoad(interruptedForPolicyChangeError(), loadWillContinueInAnotherProcess);
}
// https://w3c.github.io/ServiceWorker/#control-and-use-window-client
static inline bool shouldUseActiveServiceWorkerFromParent(const Document& document, const Document& parent)
{
return !document.url().protocolIsInHTTPFamily() && !document.securityOrigin().isOpaque() && parent.protectedSecurityOrigin()->isSameOriginDomain(document.protectedSecurityOrigin());
}
#if ENABLE(CONTENT_EXTENSIONS)
static inline bool shouldEnableResourceMonitor(const Frame& frame)
{
if (frame.isMainFrame())
return false;
return frame.settings().iFrameResourceMonitoringEnabled();
}
#endif
void DocumentLoader::commitData(const SharedBuffer& data)
{
if (!m_gotFirstByte) {
m_gotFirstByte = true;
bool hasBegun = m_writer.begin(documentURL(), false, nullptr, m_resultingClientId, &triggeringAction());
if (!hasBegun)
return;
m_writer.setDocumentWasLoadedAsPartOfNavigation();
RefPtr frame = m_frame.get();
RefPtr documentOrNull = frame ? frame->document() : nullptr;
auto scope = makeScopeExit([this, protectedThis = Ref { *this }, documentOrNull] {
if (auto createdCallback = std::exchange(m_whenDocumentIsCreatedCallback, { }))
createdCallback(isInFinishedLoadingOfEmptyDocument() ? nullptr : documentOrNull.get());
});
if (!documentOrNull)
return;
Ref document = *documentOrNull;
ASSERT(frame);
#if ENABLE(CONTENT_EXTENSIONS)
if (shouldEnableResourceMonitor(*frame)) {
URL url = documentURL();
if (!url.isEmpty() && url.protocolIsInHTTPFamily())
document->protectedResourceMonitor()->setDocumentURL(WTFMove(url));
}
#endif
if (SecurityPolicy::allowSubstituteDataAccessToLocal() && m_originalSubstituteDataWasValid) {
// If this document was loaded with substituteData, then the document can
// load local resources. See https://bugs.webkit.org/show_bug.cgi?id=16756
// and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
// discussion.
document->protectedSecurityOrigin()->grantLoadLocalResources();
}
if (protectedFrameLoader()->stateMachine().creatingInitialEmptyDocument())
return;
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
if (RefPtr archive = m_archive; archive && archive->shouldOverrideBaseURL())
document->setBaseURLOverride(archive->mainResource()->url());
#endif
if (m_canUseServiceWorkers) {
if (!document->securityOrigin().isOpaque()) {
if (m_serviceWorkerRegistrationData && m_serviceWorkerRegistrationData->activeWorker) {
document->setActiveServiceWorker(ServiceWorker::getOrCreate(document, WTFMove(m_serviceWorkerRegistrationData->activeWorker.value())));
m_serviceWorkerRegistrationData = { };
} else if (RefPtr parent = document->parentDocument()) {
if (shouldUseActiveServiceWorkerFromParent(document, *parent))
document->setActiveServiceWorker(parent->activeServiceWorker());
}
} else if (m_resultingClientId) {
// In case document has an opaque origin, say due to sandboxing, we should have created a new context, let's create a new identifier instead.
if (document->securityOrigin().isOpaque())
document->createNewIdentifier();
}
if (m_frame->document()->activeServiceWorker() || document->url().protocolIsInHTTPFamily() || (document->page() && document->page()->isServiceWorkerPage()) || (document->parentDocument() && shouldUseActiveServiceWorkerFromParent(document, *document->protectedParentDocument())))
document->setServiceWorkerConnection(&ServiceWorkerProvider::singleton().serviceWorkerConnection());
if (m_resultingClientId) {
if (*m_resultingClientId != document->identifier())
unregisterReservedServiceWorkerClient();
scriptExecutionContextIdentifierToLoaderMap().remove(*m_resultingClientId);
m_resultingClientId = std::nullopt;
}
}
// Call receivedFirstData() exactly once per load. We should only reach this point multiple times
// for multipart loads, and FrameLoader::isReplacing() will be true after the first time.
if (!isMultipartReplacingLoad())
protectedFrameLoader()->receivedFirstData();
// The load could be canceled under receivedFirstData(), which makes delegate calls and even sometimes dispatches DOM events.
if (!isLoading())
return;
if (RefPtr window = document->domWindow()) {
window->prewarmLocalStorageIfNecessary();
if (m_mainResource) {
auto* metrics = m_response.deprecatedNetworkLoadMetricsOrNull();
window->protectedPerformance()->addNavigationTiming(*this, document, *m_mainResource, timing(), metrics ? *metrics : NetworkLoadMetrics::emptyMetrics());
}
}
DocumentWriter::IsEncodingUserChosen userChosen;
String encoding;
if (overrideEncoding().isNull()) {
userChosen = DocumentWriter::IsEncodingUserChosen::No;
encoding = response().textEncodingName();
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
if (RefPtr archive = m_archive; archive && archive->shouldUseMainResourceEncoding())
encoding = archive->mainResource()->textEncoding();
#endif
} else {
userChosen = DocumentWriter::IsEncodingUserChosen::Yes;
encoding = overrideEncoding();
}
m_writer.setEncoding(encoding, userChosen);
}
#if ENABLE(CONTENT_EXTENSIONS)
if (!m_pendingNamedContentExtensionStyleSheets.isEmpty() || !m_pendingContentExtensionDisplayNoneSelectors.isEmpty()) {
auto& extensionStyleSheets = m_frame->protectedDocument()->extensionStyleSheets();
for (auto& pendingStyleSheet : m_pendingNamedContentExtensionStyleSheets)
extensionStyleSheets.maybeAddContentExtensionSheet(pendingStyleSheet.key, Ref { *pendingStyleSheet.value });
for (auto& pendingSelectorEntry : m_pendingContentExtensionDisplayNoneSelectors) {
for (const auto& pendingSelector : pendingSelectorEntry.value)
extensionStyleSheets.addDisplayNoneSelector(pendingSelectorEntry.key, pendingSelector.first, pendingSelector.second);
}
m_pendingNamedContentExtensionStyleSheets.clear();
m_pendingContentExtensionDisplayNoneSelectors.clear();
}
#endif
ASSERT(m_frame->document()->parsing());
m_writer.addData(data);
}
void DocumentLoader::dataReceived(CachedResource& resource, const SharedBuffer& buffer)
{
ASSERT_UNUSED(resource, &resource == m_mainResource);
dataReceived(buffer);
}
void DocumentLoader::dataReceived(const SharedBuffer& buffer)
{
#if ENABLE(CONTENT_FILTERING)
if (m_contentFilter && !m_contentFilter->continueAfterDataReceived(buffer))
return;
#endif
ASSERT(!buffer.span().empty());
ASSERT(!m_response.isNull());
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
#endif
if (m_identifierForLoadWithoutResourceLoader)
protectedFrameLoader()->notifier().dispatchDidReceiveData(this, *m_identifierForLoadWithoutResourceLoader, &buffer, buffer.size(), -1);
m_applicationCacheHost->mainResourceDataReceived(buffer, -1, false);
if (!isMultipartReplacingLoad())
commitLoad(buffer);
}
void DocumentLoader::setupForReplace()
{
if (!mainResourceData())
return;
protectedFrameLoader()->protectedClient()->willReplaceMultipartContent();
maybeFinishLoadingMultipartContent();
maybeCreateArchive();
m_writer.end();
protectedFrameLoader()->setReplacing();
m_gotFirstByte = false;
unregisterReservedServiceWorkerClient();
if (m_resultingClientId) {
scriptExecutionContextIdentifierToLoaderMap().remove(*m_resultingClientId);
m_resultingClientId = std::nullopt;
}
stopLoadingSubresources();
stopLoadingPlugIns();
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
clearArchiveResources();
#endif
}
void DocumentLoader::checkLoadComplete()
{
if (!m_frame || isLoading())
return;
ASSERT(this == frameLoader()->activeDocumentLoader());
m_frame->protectedDocument()->protectedWindow()->finishedLoading();
}
void DocumentLoader::applyPoliciesToSettings()
{
if (!m_frame) {
ASSERT_NOT_REACHED();
return;
}
if (!m_frame->isMainFrame())
return;
#if ENABLE(MEDIA_SOURCE)
m_frame->settings().setMediaSourceEnabled(m_mediaSourcePolicy == MediaSourcePolicy::Default ? Settings::platformDefaultMediaSourceEnabled() : m_mediaSourcePolicy == MediaSourcePolicy::Enable);
#endif
#if ENABLE(OVERFLOW_SCROLLING_TOUCH)
if (m_legacyOverflowScrollingTouchPolicy == LegacyOverflowScrollingTouchPolicy::Disable)
m_frame->settings().setLegacyOverflowScrollingTouchEnabled(false);
#endif
#if ENABLE(TEXT_AUTOSIZING)
m_frame->settings().setIdempotentModeAutosizingOnlyHonorsPercentages(m_idempotentModeAutosizingOnlyHonorsPercentages);
#endif
if (m_pushAndNotificationsEnabledPolicy != PushAndNotificationsEnabledPolicy::UseGlobalPolicy) {
bool enabled = m_pushAndNotificationsEnabledPolicy == PushAndNotificationsEnabledPolicy::Yes;
m_frame->settings().setPushAPIEnabled(enabled);
#if ENABLE(NOTIFICATIONS)
m_frame->settings().setNotificationsEnabled(enabled);
#endif
#if ENABLE(NOTIFICATION_EVENT)
m_frame->settings().setNotificationEventEnabled(enabled);
#endif
#if PLATFORM(IOS)
m_frame->settings().setAppBadgeEnabled(enabled);
#endif
}
if (m_inlineMediaPlaybackPolicy != InlineMediaPlaybackPolicy::Default)
m_frame->settings().setInlineMediaPlaybackRequiresPlaysInlineAttribute(m_inlineMediaPlaybackPolicy == InlineMediaPlaybackPolicy::RequiresPlaysInlineAttribute);
}
ColorSchemePreference DocumentLoader::colorSchemePreference() const
{
return m_colorSchemePreference;
}
void DocumentLoader::attachToFrame(LocalFrame& frame)
{
if (m_frame == &frame)
return;
ASSERT(!m_frame);
observeFrame(&frame);
m_writer.setFrame(frame);
attachToFrame();
#if ASSERT_ENABLED
m_hasEverBeenAttached = true;
#endif
applyPoliciesToSettings();
}
void DocumentLoader::attachToFrame()
{
ASSERT(m_frame);
DOCUMENTLOADER_RELEASE_LOG_FORWARDABLE(DOCUMENTLOADER_ATTACHTOFRAME);
}
void DocumentLoader::detachFromFrame(LoadWillContinueInAnotherProcess loadWillContinueInAnotherProcess)
{
DOCUMENTLOADER_RELEASE_LOG_FORWARDABLE(DOCUMENTLOADER_DETACHFROMFRAME);
RefPtr frame = m_frame.get();
#if ASSERT_ENABLED
if (m_hasEverBeenAttached)
ASSERT_WITH_MESSAGE(frame, "detachFromFrame() is being called on a DocumentLoader twice without an attachToFrame() inbetween");
else
ASSERT_WITH_MESSAGE(frame, "detachFromFrame() is being called on a DocumentLoader that has never attached to any Frame");
#endif
Ref protectedThis { *this };
// It never makes sense to have a document loader that is detached from its
// frame have any loads active, so kill all the loads.
stopLoading();
if (m_mainResource && m_mainResource->hasClient(*this))
m_mainResource->removeClient(*this);
#if ENABLE(CONTENT_FILTERING)
if (m_contentFilter)
m_contentFilter->stopFilteringMainResource();
#endif
m_applicationCacheHost->setDOMApplicationCache(nullptr);
cancelPolicyCheckIfNeeded();
// cancelPolicyCheckIfNeeded can clear m_frame if the policy check
// is stopped, resulting in a recursive call into this detachFromFrame.
// If m_frame is nullptr after cancelPolicyCheckIfNeeded, our work is
// already done so just return.
frame = m_frame.get();
if (!frame)
return;
if (auto navigationID = std::exchange(m_navigationID, { }))
frame->loader().client().documentLoaderDetached(*navigationID, loadWillContinueInAnotherProcess);
InspectorInstrumentation::loaderDetachedFromFrame(*frame, *this);
observeFrame(nullptr);
}
void DocumentLoader::setNavigationID(NavigationIdentifier navigationID)
{
m_navigationID = navigationID;
}
void DocumentLoader::clearMainResourceLoader()
{
m_loadingMainResource = false;
m_isContinuingLoadAfterProvisionalLoadStarted = false;
RefPtr frameLoader = this->frameLoader();
if (!frameLoader)
return;
if (this == frameLoader->activeDocumentLoader())
checkLoadComplete();
}
#if ENABLE(APPLICATION_MANIFEST)
void DocumentLoader::loadApplicationManifest(CompletionHandler<void(const std::optional<ApplicationManifest>&)>&& completionHandler)
{
if (completionHandler)
m_loadApplicationManifestCallbacks.append(WTFMove(completionHandler));
bool isLoading = !!m_applicationManifestLoader;
auto notifyIfUnableToLoad = makeScopeExit([this, protectedThis = Ref { *this }, &isLoading] {
if (!isLoading || m_finishedLoadingApplicationManifest)
notifyFinishedLoadingApplicationManifest();
});
if (isLoading)
return;
RefPtr document = this->document();
if (!document)
return;
if (!document->isTopDocument())
return;
if (document->url().isEmpty() || document->url().protocolIsAbout())
return;
RefPtr head = document->head();
if (!head)
return;
URL manifestURL;
bool useCredentials = false;
for (Ref link : childrenOfType<HTMLLinkElement>(*head)) {
if (!link->isApplicationManifest())
continue;
auto href = link->href();
if (href.isEmpty() || !href.isValid())
continue;
if (!link->mediaAttributeMatches())
continue;
manifestURL = href;
useCredentials = equalLettersIgnoringASCIICase(link->attributeWithoutSynchronization(HTMLNames::crossoriginAttr), "use-credentials"_s);
break;
}
if (manifestURL.isEmpty() || !manifestURL.isValid())
return;
m_applicationManifestLoader = makeUnique<ApplicationManifestLoader>(*this, manifestURL, useCredentials);
isLoading = m_applicationManifestLoader->startLoading();
if (!isLoading)
m_finishedLoadingApplicationManifest = true;
}
void DocumentLoader::finishedLoadingApplicationManifest(ApplicationManifestLoader& loader)
{
ASSERT_UNUSED(loader, &loader == m_applicationManifestLoader.get());
// If the DocumentLoader has detached from its frame, all manifest loads should have already been canceled.
ASSERT(m_frame);
ASSERT(!m_finishedLoadingApplicationManifest);
m_finishedLoadingApplicationManifest = true;
notifyFinishedLoadingApplicationManifest();
}
void DocumentLoader::notifyFinishedLoadingApplicationManifest()
{
std::optional<ApplicationManifest> manifest = m_applicationManifestLoader ? m_applicationManifestLoader->processManifest() : std::nullopt;
ASSERT_IMPLIES(manifest, m_finishedLoadingApplicationManifest);
for (auto& callback : std::exchange(m_loadApplicationManifestCallbacks, { }))
callback(manifest);
}
#endif // ENABLE(APPLICATION_MANIFEST)
bool DocumentLoader::isLoadingInAPISense() const
{
// Once a frame has loaded, we no longer need to consider subresources,
// but we still need to consider subframes.
if (frameLoader()->state() != FrameState::Complete) {
ASSERT(m_frame->document());
Ref document = *m_frame->document();
if ((isLoadingMainResource() || !document->loadEventFinished()) && isLoading())
return true;
if (m_cachedResourceLoader->requestCount())
return true;
if (document->isDelayingLoadEvent())
return true;
if (document->processingLoadEvent())
return true;
if (document->hasActiveParser())
return true;
RefPtr scriptableParser = document->scriptableDocumentParser();
if (scriptableParser && scriptableParser->hasScriptsWaitingForStylesheets())
return true;
}
return protectedFrameLoader()->subframeIsLoading();
}
bool DocumentLoader::maybeCreateArchive()
{
#if !ENABLE(WEB_ARCHIVE) && !ENABLE(MHTML)
return false;
#else
// Give the archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
RefPtr archive = ArchiveFactory::create(m_response.url(), mainResourceData().get(), m_response.mimeType());
m_archive = archive.copyRef();
if (!archive)
return false;
addAllArchiveResources(*archive);
ASSERT(archive->mainResource());
Ref mainResource = *archive->mainResource();
Ref parsedArchiveData = mainResource->protectedData()->makeContiguous();
m_parsedArchiveData = parsedArchiveData.copyRef();
m_writer.setMIMEType(mainResource->mimeType());
ASSERT(m_frame->document());
commitData(parsedArchiveData);
return true;
#endif
}
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
void DocumentLoader::setArchive(Ref<Archive>&& archive)
{
m_archive = archive.copyRef();
addAllArchiveResources(archive);
}
void DocumentLoader::addAllArchiveResources(Archive& archive)
{
if (!m_archiveResourceCollection)
m_archiveResourceCollection = makeUnique<ArchiveResourceCollection>();
m_archiveResourceCollection->addAllResources(archive);
}
// FIXME: Adding a resource directly to a DocumentLoader/ArchiveResourceCollection seems like bad design, but is API some apps rely on.
// Can we change the design in a manner that will let us deprecate that API without reducing functionality of those apps?
void DocumentLoader::addArchiveResource(Ref<ArchiveResource>&& resource)
{
if (!m_archiveResourceCollection)
m_archiveResourceCollection = makeUnique<ArchiveResourceCollection>();
m_archiveResourceCollection->addResource(WTFMove(resource));
}
RefPtr<Archive> DocumentLoader::popArchiveForSubframe(const String& frameName, const URL& url)
{
return m_archiveResourceCollection ? m_archiveResourceCollection->popSubframeArchive(frameName, url) : nullptr;
}
void DocumentLoader::clearArchiveResources()
{
m_archiveResourceCollection = nullptr;
m_substituteResourceDeliveryTimer.stop();
}
SharedBuffer* DocumentLoader::parsedArchiveData() const
{
return m_parsedArchiveData.get();
}
#endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
RefPtr<ArchiveResource> DocumentLoader::archiveResourceForURL(const URL& url) const
{
if (!m_archiveResourceCollection)
return nullptr;
RefPtr resource = m_archiveResourceCollection->archiveResourceForURL(url);
if (!resource || resource->shouldIgnoreWhenUnarchiving())
return nullptr;
return resource;
}
RefPtr<ArchiveResource> DocumentLoader::mainResource() const
{
RefPtr<FragmentedSharedBuffer> data = mainResourceData();
if (!data)
data = SharedBuffer::create();
auto& response = this->response();
return ArchiveResource::create(WTFMove(data), response.url(), response.mimeType(), response.textEncodingName(), frame()->tree().uniqueName());
}
RefPtr<ArchiveResource> DocumentLoader::subresource(const URL& url) const
{
if (!isCommitted())
return nullptr;
auto* resource = m_cachedResourceLoader->cachedResource(url);
if (!resource || !resource->isLoaded())
return archiveResourceForURL(url);
if (resource->type() == CachedResource::Type::MainResource)
return nullptr;
RefPtr data = resource->resourceBuffer();
if (!data)
return nullptr;
return ArchiveResource::create(data.get(), url, resource->response());
}
Vector<Ref<ArchiveResource>> DocumentLoader::subresources() const
{
if (!isCommitted())
return { };
Vector<Ref<ArchiveResource>> subresources;
for (auto& handle : m_cachedResourceLoader->allCachedResources().values()) {
if (auto subresource = this->subresource(handle->url()))
subresources.append(subresource.releaseNonNull());
}
return subresources;
}
void DocumentLoader::deliverSubstituteResourcesAfterDelay()
{
if (m_pendingSubstituteResources.isEmpty())
return;
ASSERT(m_frame);
ASSERT(m_frame->page());
if (m_frame->page()->defersLoading())
return;
if (!m_substituteResourceDeliveryTimer.isActive())
m_substituteResourceDeliveryTimer.startOneShot(0_s);
}
void DocumentLoader::substituteResourceDeliveryTimerFired()
{
if (m_pendingSubstituteResources.isEmpty())
return;
ASSERT(m_frame);
ASSERT(m_frame->page());
if (m_frame->page()->defersLoading())
return;
auto pendingSubstituteResources = WTFMove(m_pendingSubstituteResources);
for (auto& pendingSubstituteResource : pendingSubstituteResources) {
auto& loader = pendingSubstituteResource.key;
if (auto& resource = pendingSubstituteResource.value)
resource->deliver(*loader);
else {
// A null resource means that we should fail the load.
// FIXME: Maybe we should use another error here - something like "not in cache".
loader->didFail(loader->cannotShowURLError());
}
}
}
#if ASSERT_ENABLED
bool DocumentLoader::isSubstituteLoadPending(ResourceLoader* loader) const
{
return m_pendingSubstituteResources.contains(loader);
}
#endif // ASSERT_ENABLED
void DocumentLoader::cancelPendingSubstituteLoad(ResourceLoader* loader)
{
if (m_pendingSubstituteResources.isEmpty())
return;
m_pendingSubstituteResources.remove(loader);
if (m_pendingSubstituteResources.isEmpty())
m_substituteResourceDeliveryTimer.stop();
}
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
bool DocumentLoader::scheduleArchiveLoad(ResourceLoader& loader, const ResourceRequest& request)
{
if (RefPtr resource = archiveResourceForURL(request.url())) {
scheduleSubstituteResourceLoad(loader, *resource);
return true;
}
RefPtr archive = m_archive;
if (!archive)
return false;
#if ENABLE(WEB_ARCHIVE)
// The idea of WebArchiveDebugMode is that we should fail instead of trying to fetch from the network.
// Returning true ensures the caller will not try to fetch from the network.
if (m_frame->settings().webArchiveDebugModeEnabled() && responseMIMEType() == "application/x-webarchive"_s)
return true;
#endif
// If we want to load from the archive only, then we should always return true so that the caller
// does not try to fetch from the network.
return archive->shouldLoadFromArchiveOnly();
}
#endif
void DocumentLoader::scheduleSubstituteResourceLoad(ResourceLoader& loader, SubstituteResource& resource)
{
ASSERT(!loader.options().serviceWorkerRegistrationIdentifier);
m_pendingSubstituteResources.set(&loader, &resource);
deliverSubstituteResourcesAfterDelay();
}
void DocumentLoader::scheduleCannotShowURLError(ResourceLoader& loader)
{
m_pendingSubstituteResources.set(&loader, nullptr);
deliverSubstituteResourcesAfterDelay();
}
void DocumentLoader::addResponse(const ResourceResponse& response)
{
if (!m_stopRecordingResponses)
m_responses.append(response);
}
void DocumentLoader::stopRecordingResponses()
{
m_stopRecordingResponses = true;
m_responses.shrinkToFit();
}
void DocumentLoader::setCustomHeaderFields(Vector<CustomHeaderFields>&& fields)
{
m_customHeaderFields = WTFMove(fields);
}
void DocumentLoader::setTitle(const StringWithDirection& title)
{
if (m_pageTitle == title)
return;
protectedFrameLoader()->willChangeTitle(this);
m_pageTitle = title;
if (RefPtr frameLoader = this->frameLoader())
frameLoader->didChangeTitle(this);
}
URL DocumentLoader::urlForHistory() const
{
// Return the URL to be used for history and B/F list.
// Returns nil for WebDataProtocol URLs that aren't alternates
// for unreachable URLs, because these can't be stored in history.
if (m_substituteData.isValid() && m_substituteData.shouldRevealToSessionHistory() != SubstituteData::SessionHistoryVisibility::Visible)
return unreachableURL();
return m_originalRequestCopy.url();
}
bool DocumentLoader::urlForHistoryReflectsFailure() const
{
return m_substituteData.isValid() || m_response.httpStatusCode() >= 400;
}
URL DocumentLoader::documentURL() const
{
URL url = substituteData().response().url();
#if ENABLE(WEB_ARCHIVE)
if (RefPtr archive = m_archive; url.isEmpty() && archive && archive->shouldUseMainResourceURL())
url = archive->mainResource()->url();
#endif
if (url.isEmpty())
url = m_request.url();
if (url.isEmpty())
url = m_response.url();
return url;
}
#if PLATFORM(IOS_FAMILY)
// FIXME: This method seems to violate the encapsulation of this class.
void DocumentLoader::setResponseMIMEType(const String& responseMIMEType)
{
m_response.setMimeType(String { responseMIMEType });
}
#endif
void DocumentLoader::setDefersLoading(bool defers)
{
// Multiple frames may be loading the same main resource simultaneously. If deferral state changes,
// each frame's DocumentLoader will try to send a setDefersLoading() to the same underlying ResourceLoader. Ensure only
// the "owning" DocumentLoader does so, as setDefersLoading() is not resilient to setting the same value repeatedly.
if (RefPtr loader = mainResourceLoader(); loader && loader->documentLoader() == this)
loader->setDefersLoading(defers);
setAllDefersLoading(m_subresourceLoaders, defers);
setAllDefersLoading(m_plugInStreamLoaders, defers);
if (!defers)
deliverSubstituteResourcesAfterDelay();
}
void DocumentLoader::setMainResourceDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
{
if (m_mainResource)
m_mainResource->setDataBufferingPolicy(dataBufferingPolicy);
}
void DocumentLoader::stopLoadingPlugIns()
{
cancelAll(m_plugInStreamLoaders);
}
void DocumentLoader::stopLoadingSubresources()
{
cancelAll(m_subresourceLoaders);
ASSERT(m_subresourceLoaders.isEmpty());
}
void DocumentLoader::addSubresourceLoader(SubresourceLoader& loader)
{
// The main resource's underlying ResourceLoader will ask to be added here.
// It is much simpler to handle special casing of main resource loads if we don't
// let it be added. In the main resource load case, mainResourceLoader()
// will still be null at this point, but m_gotFirstByte should be false here if and only
// if we are just starting the main resource load.
if (!m_gotFirstByte)
return;
ASSERT(!m_subresourceLoaders.contains(*loader.identifier()));
ASSERT(!mainResourceLoader() || mainResourceLoader() != &loader);
// Application Cache loaders are handled by their ApplicationCacheGroup directly.
if (loader.options().applicationCacheMode == ApplicationCacheMode::Bypass)
return;
#if ASSERT_ENABLED
if (document()) {
switch (document()->backForwardCacheState()) {
case Document::NotInBackForwardCache:
break;
case Document::AboutToEnterBackForwardCache: {
// A page about to enter the BackForwardCache should only be able to start ping loads.
auto* cachedResource = loader.cachedResource();
ASSERT(cachedResource && (CachedResource::shouldUsePingLoad(cachedResource->type()) || cachedResource->options().keepAlive));
break;
}
case Document::InBackForwardCache:
// A page in the BackForwardCache should not be able to start loads.
ASSERT_NOT_REACHED();
break;
}
}
#endif
m_subresourceLoaders.add(*loader.identifier(), &loader);
}
void DocumentLoader::removeSubresourceLoader(LoadCompletionType type, SubresourceLoader& loader)
{
if (!m_subresourceLoaders.remove(*loader.identifier()))
return;
checkLoadComplete();
if (RefPtr frame = m_frame.get())
frame->protectedLoader()->subresourceLoadDone(type);
}
void DocumentLoader::addPlugInStreamLoader(ResourceLoader& loader)
{
ASSERT(!m_plugInStreamLoaders.contains(*loader.identifier()));
m_plugInStreamLoaders.add(*loader.identifier(), &loader);
}
void DocumentLoader::removePlugInStreamLoader(ResourceLoader& loader)
{
ASSERT(&loader == m_plugInStreamLoaders.get(*loader.identifier()));
m_plugInStreamLoaders.remove(*loader.identifier());
checkLoadComplete();
}
bool DocumentLoader::isMultipartReplacingLoad() const
{
return isLoadingMultipartContent() && protectedFrameLoader()->isReplacing();
}
bool DocumentLoader::maybeLoadEmpty()
{
bool shouldLoadEmpty = !m_substituteData.isValid() && (m_request.url().isEmpty() || LegacySchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(m_request.url().protocol()));
Ref frameLoaderClient = frameLoader()->client();
if (!shouldLoadEmpty && !frameLoaderClient->representationExistsForURLScheme(m_request.url().protocol()))
return false;
if (m_request.url().isEmpty() && !protectedFrameLoader()->stateMachine().creatingInitialEmptyDocument()) {
m_request.setURL(aboutBlankURL());
if (isLoadingMainResource())
frameLoaderClient->dispatchDidChangeProvisionalURL();
}
String mimeType = shouldLoadEmpty ? textHTMLContentTypeAtom() : frameLoaderClient->generatedMIMETypeForURLScheme(m_request.url().protocol());
m_response = ResourceResponse(m_request.url(), mimeType, 0, "UTF-8"_s);
bool isDisplayingInitialEmptyDocument = frameLoader()->stateMachine().isDisplayingInitialEmptyDocument();
if (!isDisplayingInitialEmptyDocument) {
if (auto coopEnforcementResult = doCrossOriginOpenerHandlingOfResponse(m_response)) {
m_responseCOOP = coopEnforcementResult->crossOriginOpenerPolicy;
if (coopEnforcementResult->needsBrowsingContextGroupSwitch)
protectedFrameLoader()->switchBrowsingContextsGroup();
}
}
SetForScope isInFinishedLoadingOfEmptyDocument { m_isInFinishedLoadingOfEmptyDocument, true };
m_isInitialAboutBlank = isDisplayingInitialEmptyDocument;
finishedLoading();
return true;
}
void DocumentLoader::loadErrorDocument()
{
m_response = ResourceResponse(m_request.url(), textHTMLContentTypeAtom(), 0, "UTF-8"_s);
SetForScope isInFinishedLoadingOfEmptyDocument { m_isInFinishedLoadingOfEmptyDocument, true };
commitIfReady();
if (!frameLoader())
return;
commitData(SharedBuffer::create());
m_frame->document()->enforceSandboxFlags(SandboxFlag::Origin);
m_writer.end();
}
static bool canUseServiceWorkers(LocalFrame* frame)
{
if (!frame || !frame->settings().serviceWorkersEnabled())
return false;
auto* ownerElement = frame->ownerElement();
return !ownerElement || !is<HTMLPlugInElement>(ownerElement);
}
static bool shouldCancelLoadingAboutURL(const URL& url)
{
if (!url.protocolIsAbout())
return false;
if (url.isAboutBlank() || url.isAboutSrcDoc())
return false;
if (!url.hasOpaquePath())
return false;
#if PLATFORM(COCOA)
if (!linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::OnlyLoadWellKnownAboutURLs))
return false;
#endif
return true;
}
void DocumentLoader::startLoadingMainResource()
{
RefPtr frame = m_frame.get();
m_canUseServiceWorkers = canUseServiceWorkers(frame.get());
m_mainDocumentError = ResourceError();
timing().markStartTime();
ASSERT(!m_mainResource);
ASSERT(!m_loadingMainResource);
m_loadingMainResource = true;
Ref<DocumentLoader> protectedThis(*this);
if (shouldCancelLoadingAboutURL(m_request.url())) {
cancelMainResourceLoad(platformStrategies()->loaderStrategy()->cannotShowURLError(m_request));
return;
}
if (maybeLoadEmpty()) {
DOCUMENTLOADER_RELEASE_LOG_FORWARDABLE(DOCUMENTLOADER_STARTLOADINGMAINRESOURCE_EMTPY_DOCUMENT);
return;
}
#if ENABLE(CONTENT_FILTERING)
// Always filter in WK1
contentFilterInDocumentLoader() = frame && frame->view() && frame->protectedView()->platformWidget();
if (contentFilterInDocumentLoader())
m_contentFilter = !m_substituteData.isValid() ? ContentFilter::create(*this) : nullptr;
#endif
auto url = m_request.url();
auto fragmentDirective = url.consumeFragmentDirective();
m_request.setURL(url, m_request.didFilterLinkDecoration());
frame = m_frame.get();
if (frame) {
RefPtr page = frame->protectedPage();
if (page)
page->setMainFrameURLFragment(WTFMove(fragmentDirective));
}
// Make sure we re-apply the user agent to the Document's ResourceRequest upon reload in case the embedding
// application has changed it, by clearing the previous user agent value here and applying the new value in CachedResourceLoader.
m_request.clearHTTPUserAgent();
ASSERT(timing().startTime());
willSendRequest(ResourceRequest(m_request), ResourceResponse(), [this, protectedThis = Ref { *this }] (ResourceRequest&& request) mutable {
request.setRequester(ResourceRequestRequester::Main);
m_request = request;
// FIXME: Implement local URL interception by getting the service worker of the parent.
// willSendRequest() may lead to our Frame being detached or cancelling the load via nulling the ResourceRequest.
if (!m_frame || m_request.isNull()) {
DOCUMENTLOADER_RELEASE_LOG("startLoadingMainResource: Load canceled after willSendRequest");
return;
}
// If this is a reload the cache layer might have made the previous request conditional. DocumentLoader can't handle 304 responses itself.
request.makeUnconditional();
DOCUMENTLOADER_RELEASE_LOG_FORWARDABLE(DOCUMENTLOADER_STARTLOADINGMAINRESOURCE_STARTING_LOAD);
if (m_applicationCacheHost->canLoadMainResource(request) || m_substituteData.isValid()) {
auto url = request.url();
matchRegistration(url, [request = WTFMove(request), protectedThis = Ref { *this }, this] (auto&& registrationData) mutable {
if (!m_mainDocumentError.isNull()) {
DOCUMENTLOADER_RELEASE_LOG("startLoadingMainResource callback: Load canceled because of main document error (type=%d, code=%d)", static_cast<int>(m_mainDocumentError.type()), m_mainDocumentError.errorCode());
return;
}
if (!m_frame) {
DOCUMENTLOADER_RELEASE_LOG("startLoadingMainResource callback: Load canceled because no frame");
return;
}
if (registrationData)
m_serviceWorkerRegistrationData = makeUnique<ServiceWorkerRegistrationData>(WTFMove(*registrationData));
// Prefer existing substitute data (from WKWebView.loadData etc) over service worker fetch.
if (this->tryLoadingSubstituteData()) {
DOCUMENTLOADER_RELEASE_LOG("startLoadingMainResource callback: Load canceled because of substitute data");
return;
}
if (!m_serviceWorkerRegistrationData && this->tryLoadingRequestFromApplicationCache()) {
DOCUMENTLOADER_RELEASE_LOG("startLoadingMainResource callback: Loaded from Application Cache");
return;
}
this->loadMainResource(WTFMove(request));
});
return;
}
loadMainResource(WTFMove(request));
});
}
void DocumentLoader::unregisterReservedServiceWorkerClient()
{
if (!m_resultingClientId)
return;
if (RefPtr serviceWorkerConnection = ServiceWorkerProvider::singleton().existingServiceWorkerConnection())
serviceWorkerConnection->unregisterServiceWorkerClient(*m_resultingClientId);
}
void DocumentLoader::loadMainResource(ResourceRequest&& request)
{
ResourceLoaderOptions mainResourceLoadOptions(
SendCallbackPolicy::SendCallbacks,
ContentSniffingPolicy::SniffContent,
DataBufferingPolicy::BufferData,
StoredCredentialsPolicy::Use,
ClientCredentialPolicy::MayAskClientForCredentials,
FetchOptions::Credentials::Include,
SecurityCheckPolicy::SkipSecurityCheck,
FetchOptions::Mode::Navigate,
CertificateInfoPolicy::IncludeCertificateInfo,
ContentSecurityPolicyImposition::SkipPolicyCheck,
DefersLoadingPolicy::AllowDefersLoading,
CachingPolicy::AllowCaching);
auto isSandboxingAllowingServiceWorkerFetchHandling = [](SandboxFlags flags) {
return !(flags.contains(SandboxFlag::Origin)) && !(flags.contains(SandboxFlag::Scripts));
};
RefPtr frame = m_frame.get();
if (!m_canUseServiceWorkers || !isSandboxingAllowingServiceWorkerFetchHandling(frame->effectiveSandboxFlags()))
mainResourceLoadOptions.serviceWorkersMode = ServiceWorkersMode::None;
else {
// The main navigation load will trigger the registration of the client.
if (m_resultingClientId) {
scriptExecutionContextIdentifierToLoaderMap().remove(*m_resultingClientId);
unregisterReservedServiceWorkerClient();
}
m_resultingClientId = ScriptExecutionContextIdentifier::generate();
ASSERT(!scriptExecutionContextIdentifierToLoaderMap().contains(*m_resultingClientId));
scriptExecutionContextIdentifierToLoaderMap().add(*m_resultingClientId, this);
mainResourceLoadOptions.resultingClientIdentifier = m_resultingClientId->object();
}
CachedResourceRequest mainResourceRequest(WTFMove(request), mainResourceLoadOptions);
if (!frame->isMainFrame() && frame->document()) {
// If we are loading the main resource of a subframe, use the cache partition of the main document.
mainResourceRequest.setDomainForCachePartition(*frame->protectedDocument());
} else {
if (protectedFrameLoader()->frame().settings().storageBlockingPolicy() != StorageBlockingPolicy::BlockThirdParty)
mainResourceRequest.setDomainForCachePartition(emptyString());
else {
auto origin = SecurityOrigin::create(mainResourceRequest.resourceRequest().url());
mainResourceRequest.setDomainForCachePartition(origin->domainForCachePartition());
}
}
auto mainResourceOrError = m_cachedResourceLoader->requestMainResource(WTFMove(mainResourceRequest));
if (!mainResourceOrError) {
// The frame may have gone away if this load was cancelled synchronously and this was the last pending load.
// This is because we may have fired the load event in a parent frame.
frame = m_frame.get();
if (!frame) {
DOCUMENTLOADER_RELEASE_LOG("loadMainResource: Unable to load main resource, frame has gone away");
return;
}
if (!m_request.url().isValid()) {
DOCUMENTLOADER_RELEASE_LOG("loadMainResource: Unable to load main resource, URL is invalid");
cancelMainResourceLoad(platformStrategies()->loaderStrategy()->cannotShowURLError(m_request));
return;
}
if (advancedPrivacyProtections().contains(AdvancedPrivacyProtections::HTTPSOnly)) {
if (auto httpNavigationWithHTTPSOnlyError = platformStrategies()->loaderStrategy()->httpNavigationWithHTTPSOnlyError(m_request); mainResourceOrError.error().domain() == httpNavigationWithHTTPSOnlyError.domain()
&& mainResourceOrError.error().errorCode() == httpNavigationWithHTTPSOnlyError.errorCode()) {
DOCUMENTLOADER_RELEASE_LOG("loadMainResource: Unable to load main resource, URL has HTTP scheme with HTTPSOnly enabled");
cancelMainResourceLoad(mainResourceOrError.error());
return;
}
}
DOCUMENTLOADER_RELEASE_LOG("loadMainResource: Unable to load main resource, returning empty document");
setRequest(ResourceRequest());
// If the load was aborted by clearing m_request, it's possible the ApplicationCacheHost
// is now in a state where starting an empty load will be inconsistent. Replace it with
// a new ApplicationCacheHost.
m_applicationCacheHost = makeUnique<ApplicationCacheHost>(*this);
maybeLoadEmpty();
return;
}
m_mainResource = mainResourceOrError.value();
ASSERT(frame);
#if ENABLE(CONTENT_EXTENSIONS)
if (m_mainResource->errorOccurred() && frame->page() && m_mainResource->resourceError().domain() == ContentExtensions::WebKitContentBlockerDomain) {
DOCUMENTLOADER_RELEASE_LOG("loadMainResource: Blocked by content blocker error");
cancelMainResourceLoad(protectedFrameLoader()->blockedByContentBlockerError(m_request));
return;
}
#endif
if (!mainResourceLoader()) {
m_identifierForLoadWithoutResourceLoader = ResourceLoaderIdentifier::generate();
protectedFrameLoader()->notifier().assignIdentifierToInitialRequest(*m_identifierForLoadWithoutResourceLoader, IsMainResourceLoad::Yes, this, mainResourceRequest.resourceRequest());
protectedFrameLoader()->notifier().dispatchWillSendRequest(this, *m_identifierForLoadWithoutResourceLoader, mainResourceRequest.resourceRequest(), ResourceResponse(), nullptr);
}
becomeMainResourceClient();
// A bunch of headers are set when the underlying ResourceLoader is created, and m_request needs to include those.
ResourceRequest updatedRequest = mainResourceLoader() ? mainResourceLoader()->originalRequest() : mainResourceRequest.resourceRequest();
// If there was a fragment identifier on m_request, the cache will have stripped it. m_request should include
// the fragment identifier, so add that back in.
if (equalIgnoringFragmentIdentifier(m_request.url(), updatedRequest.url()))
updatedRequest.setURL(m_request.url());
setRequest(updatedRequest);
}
void DocumentLoader::cancelPolicyCheckIfNeeded()
{
if (m_waitingForContentPolicy || m_waitingForNavigationPolicy) {
RELEASE_ASSERT(frameLoader());
protectedFrameLoader()->policyChecker().stopCheck();
m_waitingForContentPolicy = false;
m_waitingForNavigationPolicy = false;
}
}
void DocumentLoader::cancelMainResourceLoad(const ResourceError& resourceError, LoadWillContinueInAnotherProcess loadWillContinueInAnotherProcess)
{
Ref<DocumentLoader> protectedThis(*this);
ResourceError error = resourceError.isNull() ? protectedFrameLoader()->cancelledError(m_request) : resourceError;
DOCUMENTLOADER_RELEASE_LOG("cancelMainResourceLoad: (type=%d, code=%d)", static_cast<int>(error.type()), error.errorCode());
m_dataLoadToken.clear();
cancelPolicyCheckIfNeeded();
if (RefPtr loader = mainResourceLoader())
loader->cancel(error, loadWillContinueInAnotherProcess);
clearMainResource();
mainReceivedError(error);
}
void DocumentLoader::willContinueMainResourceLoadAfterRedirect(const ResourceRequest& newRequest)
{
setRequest(newRequest);
}
void DocumentLoader::clearMainResource()
{
ASSERT(isMainThread());
if (m_mainResource && m_mainResource->hasClient(*this))
m_mainResource->removeClient(*this);
#if ENABLE(CONTENT_FILTERING)
if (m_contentFilter)
m_contentFilter->stopFilteringMainResource();
#endif
m_mainResource = nullptr;
m_isContinuingLoadAfterProvisionalLoadStarted = false;
unregisterReservedServiceWorkerClient();
}
void DocumentLoader::subresourceLoaderFinishedLoadingOnePart(ResourceLoader& loader)
{
auto identifier = *loader.identifier();
if (!m_multipartSubresourceLoaders.add(identifier, &loader).isNewEntry) {
ASSERT(m_multipartSubresourceLoaders.get(identifier) == &loader);
ASSERT(!m_subresourceLoaders.contains(identifier));
} else {
ASSERT(m_subresourceLoaders.contains(identifier));
m_subresourceLoaders.remove(identifier);
}
checkLoadComplete();
if (m_frame)
m_frame->loader().checkLoadComplete();
}
void DocumentLoader::maybeFinishLoadingMultipartContent()
{
if (!isMultipartReplacingLoad())
return;
protectedFrameLoader()->setupForReplace();
m_committed = false;
commitLoad(mainResourceData()->makeContiguous());
}
void DocumentLoader::startIconLoading()
{
static uint64_t nextIconCallbackID = 1;
RefPtr document = this->document();
if (!document)
return;
if (!m_frame->isMainFrame())
return;
if (document->url().isEmpty() || document->url().protocolIsAbout())
return;
m_linkIcons = LinkIconCollector { *document }.iconsOfTypes({ LinkIconType::Favicon, LinkIconType::TouchIcon, LinkIconType::TouchPrecomposedIcon });
auto findResult = m_linkIcons.findIf([](auto& icon) { return icon.type == LinkIconType::Favicon; });
if (findResult == notFound && document->url().protocolIsInHTTPFamily())
m_linkIcons.append({ document->completeURL("/favicon.ico"_s), LinkIconType::Favicon, String(), std::nullopt, { } });
if (!m_linkIcons.size())
return;
auto iconDecisions = WTF::map(m_linkIcons, [&](auto& icon) -> std::pair<WebCore::LinkIcon&, uint64_t> {
auto result = m_iconsPendingLoadDecision.add(nextIconCallbackID++, icon);
return { icon, result.iterator->key };
});
m_frame->loader().client().getLoadDecisionForIcons(WTFMove(iconDecisions));
}
void DocumentLoader::didGetLoadDecisionForIcon(bool decision, uint64_t loadIdentifier, CompletionHandler<void(FragmentedSharedBuffer*)>&& completionHandler)
{
auto icon = m_iconsPendingLoadDecision.take(loadIdentifier);
// If the decision was not to load or this DocumentLoader is already detached, there is no load to perform.
if (!decision || !m_frame)
return completionHandler(nullptr);
// If the LinkIcon we just took is empty, then the DocumentLoader had all of its loaders stopped
// while this icon load decision was pending.
// In this case we need to notify the client that the icon finished loading with empty data.
if (icon.url.isEmpty())
return completionHandler(nullptr);
auto iconLoader = makeUnique<IconLoader>(*this, icon.url);
auto* rawIconLoader = iconLoader.get();
m_iconLoaders.add(WTFMove(iconLoader), WTFMove(completionHandler));
rawIconLoader->startLoading();
}
void DocumentLoader::finishedLoadingIcon(IconLoader& loader, FragmentedSharedBuffer* buffer)
{
// If the DocumentLoader has detached from its frame, all icon loads should have already been cancelled.
ASSERT(m_frame);
if (auto callback = m_iconLoaders.take(&loader))
callback(buffer);
}
void DocumentLoader::dispatchOnloadEvents()
{
m_wasOnloadDispatched = true;
m_applicationCacheHost->stopDeferringEvents();
}
void DocumentLoader::setTriggeringAction(NavigationAction&& action)
{
m_triggeringAction = WTFMove(action);
m_triggeringAction.setShouldOpenExternalURLsPolicy(m_frame ? shouldOpenExternalURLsPolicyToPropagate() : m_shouldOpenExternalURLsPolicy);
}
ShouldOpenExternalURLsPolicy DocumentLoader::shouldOpenExternalURLsPolicyToPropagate() const
{
if (!m_frame)
return ShouldOpenExternalURLsPolicy::ShouldNotAllow;
if (m_frame->isMainFrame())
return m_shouldOpenExternalURLsPolicy;
if (RefPtr document = this->document(); document && document->isSameOriginAsTopDocument())
return m_shouldOpenExternalURLsPolicy;
return ShouldOpenExternalURLsPolicy::ShouldNotAllow;
}
// https://www.w3.org/TR/css-view-transitions-2/#navigation-can-trigger-a-cross-document-view-transition
bool DocumentLoader::navigationCanTriggerCrossDocumentViewTransition(Document& oldDocument, bool fromBackForwardCache)
{
if (loadStartedDuringSwipeAnimation())
return false;
if (std::holds_alternative<Document::SkipTransition>(oldDocument.resolveViewTransitionRule()))
return false;
if (!m_triggeringAction.navigationAPIType() || *m_triggeringAction.navigationAPIType() == NavigationNavigationType::Reload)
return false;
Ref newOrigin = SecurityOrigin::create(documentURL());
if (!newOrigin->isSameOriginAs(oldDocument.protectedSecurityOrigin()))
return false;
if (const auto* metrics = response().deprecatedNetworkLoadMetricsOrNull(); metrics && !fromBackForwardCache) {
if (metrics->crossOriginRedirect())
return false;
}
if (*m_triggeringAction.navigationAPIType() == NavigationNavigationType::Traverse)
return true;
if (isRequestFromClientOrUserInput())
return false;
return true;
}
void DocumentLoader::becomeMainResourceClient()
{
#if ENABLE(CONTENT_FILTERING)
if (m_contentFilter)
m_contentFilter->startFilteringMainResource(*m_mainResource);
#endif
m_mainResource->addClient(*this);
}
#if ENABLE(CONTENT_EXTENSIONS)
void DocumentLoader::addPendingContentExtensionSheet(const String& identifier, StyleSheetContents& sheet)
{
ASSERT(!m_gotFirstByte);
m_pendingNamedContentExtensionStyleSheets.set(identifier, &sheet);
}
void DocumentLoader::addPendingContentExtensionDisplayNoneSelector(const String& identifier, const String& selector, uint32_t selectorID)
{
ASSERT(!m_gotFirstByte);
auto addResult = m_pendingContentExtensionDisplayNoneSelectors.add(identifier, Vector<std::pair<String, uint32_t>>());
addResult.iterator->value.append(std::make_pair(selector, selectorID));
}
#endif
#if USE(QUICK_LOOK)
void DocumentLoader::previewResponseReceived(CachedResource& resource, const ResourceResponse& response)
{
ASSERT_UNUSED(resource, m_mainResource == &resource);
m_response = response;
}
void DocumentLoader::setPreviewConverter(RefPtr<PreviewConverter>&& previewConverter)
{
m_previewConverter = WTFMove(previewConverter);
}
PreviewConverter* DocumentLoader::previewConverter() const
{
return m_previewConverter.get();
}
#endif
void DocumentLoader::addConsoleMessage(MessageSource messageSource, MessageLevel messageLevel, const String& message, unsigned long requestIdentifier)
{
protectedFrame()->protectedDocument()->addConsoleMessage(messageSource, messageLevel, message, requestIdentifier);
}
void DocumentLoader::enqueueSecurityPolicyViolationEvent(SecurityPolicyViolationEventInit&& eventInit)
{
protectedFrame()->protectedDocument()->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
}
#if ENABLE(CONTENT_FILTERING)
void DocumentLoader::dataReceivedThroughContentFilter(const SharedBuffer& buffer, size_t)
{
dataReceived(buffer);
}
void DocumentLoader::cancelMainResourceLoadForContentFilter(const ResourceError& error)
{
cancelMainResourceLoad(error);
}
ResourceError DocumentLoader::contentFilterDidBlock(ContentFilterUnblockHandler unblockHandler, String&& unblockRequestDeniedScript)
{
return handleContentFilterDidBlock(unblockHandler, WTFMove(unblockRequestDeniedScript));
}
void DocumentLoader::handleProvisionalLoadFailureFromContentFilter(const URL& blockedPageURL, SubstituteData& substituteData)
{
protectedFrameLoader()->load(FrameLoadRequest(*frame(), blockedPageURL, substituteData));
}
#endif // ENABLE(CONTENT_FILTERING)
#if ENABLE(CONTENT_FILTERING)
ResourceError DocumentLoader::handleContentFilterDidBlock(ContentFilterUnblockHandler unblockHandler, String&& unblockRequestDeniedScript)
{
unblockHandler.setUnreachableURL(documentURL());
if (!unblockRequestDeniedScript.isEmpty() && frame()) {
unblockHandler.wrapWithDecisionHandler([scriptController = WeakPtr { frame()->script() }, script = WTFMove(unblockRequestDeniedScript).isolatedCopy()](bool unblocked) {
if (!unblocked && scriptController) {
// FIXME: This probably needs to figure out if the origin is considered tainted.
scriptController->executeScriptIgnoringException(script, JSC::SourceTaintedOrigin::Untainted);
}
});
}
protectedFrameLoader()->client().contentFilterDidBlockLoad(WTFMove(unblockHandler));
auto error = protectedFrameLoader()->blockedByContentFilterError(request());
m_blockedByContentFilter = true;
m_blockedError = error;
return error;
}
bool DocumentLoader::contentFilterWillHandleProvisionalLoadFailure(const ResourceError& error)
{
if (m_contentFilter && m_contentFilter->willHandleProvisionalLoadFailure(error))
return true;
if (contentFilterInDocumentLoader())
return false;
return m_blockedByContentFilter && m_blockedError.errorCode() == error.errorCode() && m_blockedError.domain() == error.domain();
}
void DocumentLoader::contentFilterHandleProvisionalLoadFailure(const ResourceError& error)
{
if (m_contentFilter)
m_contentFilter->handleProvisionalLoadFailure(error);
if (contentFilterInDocumentLoader())
return;
handleProvisionalLoadFailureFromContentFilter(m_blockedPageURL, m_substituteDataFromContentFilter);
}
#endif // ENABLE(CONTENT_FILTERING)
void DocumentLoader::setActiveContentRuleListActionPatterns(const HashMap<String, Vector<String>>& patterns)
{
MemoryCompactRobinHoodHashMap<String, Vector<UserContentURLPattern>> parsedPatternMap;
for (auto& pair : patterns) {
auto patternVector = WTF::compactMap(pair.value, [](auto& patternString) -> std::optional<UserContentURLPattern> {
UserContentURLPattern parsedPattern(patternString);
if (parsedPattern.isValid())
return parsedPattern;
return std::nullopt;
});
parsedPatternMap.set(pair.key, WTFMove(patternVector));
}
m_activeContentRuleListActionPatterns = WTFMove(parsedPatternMap);
}
bool DocumentLoader::allowsActiveContentRuleListActionsForURL(const String& contentRuleListIdentifier, const URL& url) const
{
for (const auto& pattern : m_activeContentRuleListActionPatterns.get(contentRuleListIdentifier)) {
if (pattern.matches(url))
return true;
}
return false;
}
void DocumentLoader::setHTTPSByDefaultMode(HTTPSByDefaultMode mode)
{
if (mode == HTTPSByDefaultMode::Disabled) {
if (m_advancedPrivacyProtections.contains(AdvancedPrivacyProtections::HTTPSOnly))
m_httpsByDefaultMode = HTTPSByDefaultMode::UpgradeWithUserMediatedFallback;
else if (m_advancedPrivacyProtections.contains(AdvancedPrivacyProtections::HTTPSFirst))
m_httpsByDefaultMode = HTTPSByDefaultMode::UpgradeWithAutomaticFallback;
} else
m_httpsByDefaultMode = mode;
}
Ref<CachedResourceLoader> DocumentLoader::protectedCachedResourceLoader() const
{
return m_cachedResourceLoader;
}
void DocumentLoader::whenDocumentIsCreated(Function<void(Document*)>&& callback)
{
ASSERT(!m_canUseServiceWorkers || !!m_resultingClientId);
if (auto previousCallback = std::exchange(m_whenDocumentIsCreatedCallback, { })) {
callback = [previousCallback = WTFMove(previousCallback), newCallback = WTFMove(callback)] (auto* document) mutable {
previousCallback(document);
newCallback(document);
};
}
m_whenDocumentIsCreatedCallback = WTFMove(callback);
}
} // namespace WebCore
#undef PAGE_ID
#undef FRAME_ID
#undef IS_MAIN_FRAME
|