1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/dom/BrowsingContext.h"
#include "ipc/IPCMessageUtils.h"
#ifdef ACCESSIBILITY
# include "mozilla/a11y/DocAccessibleParent.h"
# include "mozilla/a11y/Platform.h"
# include "nsAccessibilityService.h"
# if defined(XP_WIN)
# include "mozilla/a11y/AccessibleWrap.h"
# include "mozilla/a11y/Compatibility.h"
# include "mozilla/a11y/nsWinUtils.h"
# endif
#endif
#include "js/LocaleSensitive.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/BindingIPCUtils.h"
#include "mozilla/dom/BrowserHost.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/BrowsingContextGroup.h"
#include "mozilla/dom/BrowsingContextBinding.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Geolocation.h"
#include "mozilla/dom/HTMLEmbedElement.h"
#include "mozilla/dom/HTMLIFrameElement.h"
#include "mozilla/dom/Location.h"
#include "mozilla/dom/LocationBinding.h"
#include "mozilla/dom/MediaDevices.h"
#include "mozilla/dom/Navigation.h"
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/PopupBlocker.h"
#include "mozilla/dom/ReferrerInfo.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SessionStoreChild.h"
#include "mozilla/dom/SessionStorageManager.h"
#include "mozilla/dom/StructuredCloneTags.h"
#include "mozilla/dom/UserActivationIPCUtils.h"
#include "mozilla/dom/WindowBinding.h"
#include "mozilla/dom/WindowContext.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/dom/WindowProxyHolder.h"
#include "mozilla/dom/SyncedContextInlines.h"
#include "mozilla/dom/XULFrameElement.h"
#include "mozilla/ipc/ProtocolUtils.h"
#include "mozilla/net/DocumentLoadListener.h"
#include "mozilla/net/RequestContextService.h"
#include "mozilla/Assertions.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Components.h"
#include "mozilla/Logging.h"
#include "mozilla/MediaFeatureChange.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_fission.h"
#include "mozilla/StaticPrefs_media.h"
#include "mozilla/StaticPrefs_page_load.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/URLQueryStringStripper.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/glean/DomMetrics.h"
#include "mozilla/StartupTimeline.h"
#include "GeckoProfiler.h"
#include "mozilla/ProfilerMarkers.h"
#include "nsIURIFixup.h"
#include "nsIXULRuntime.h"
#include "nsDocShell.h"
#include "nsDocShellLoadState.h"
#include "nsFocusManager.h"
#include "nsGlobalWindowInner.h"
#include "nsGlobalWindowOuter.h"
#include "PresShell.h"
#include "nsIObserverService.h"
#include "nsISHistory.h"
#include "nsJSUtils.h"
#include "nsContentUtils.h"
#include "nsQueryObject.h"
#include "nsSandboxFlags.h"
#include "nsScreen.h"
#include "nsScriptError.h"
#include "nsThreadUtils.h"
#include "xpcprivate.h"
#include "AutoplayPolicy.h"
#include "GVAutoplayRequestStatusIPC.h"
extern mozilla::LazyLogModule gAutoplayPermissionLog;
extern mozilla::LazyLogModule gNavigationAPILog;
extern mozilla::LazyLogModule gTimeoutDeferralLog;
#define AUTOPLAY_LOG(msg, ...) \
MOZ_LOG(gAutoplayPermissionLog, LogLevel::Debug, (msg, ##__VA_ARGS__))
namespace IPC {
// Allow serialization and deserialization of OrientationType over IPC
template <>
struct ParamTraits<mozilla::dom::OrientationType>
: public mozilla::dom::WebIDLEnumSerializer<mozilla::dom::OrientationType> {
};
template <>
struct ParamTraits<mozilla::dom::DisplayMode>
: public mozilla::dom::WebIDLEnumSerializer<mozilla::dom::DisplayMode> {};
template <>
struct ParamTraits<mozilla::dom::PrefersColorSchemeOverride>
: public mozilla::dom::WebIDLEnumSerializer<
mozilla::dom::PrefersColorSchemeOverride> {};
template <>
struct ParamTraits<mozilla::dom::ForcedColorsOverride>
: public mozilla::dom::WebIDLEnumSerializer<
mozilla::dom::ForcedColorsOverride> {};
template <>
struct ParamTraits<mozilla::dom::ExplicitActiveStatus>
: public ContiguousEnumSerializer<
mozilla::dom::ExplicitActiveStatus,
mozilla::dom::ExplicitActiveStatus::None,
mozilla::dom::ExplicitActiveStatus::EndGuard_> {};
// Allow serialization and deserialization of TouchEventsOverride over IPC
template <>
struct ParamTraits<mozilla::dom::TouchEventsOverride>
: public mozilla::dom::WebIDLEnumSerializer<
mozilla::dom::TouchEventsOverride> {};
template <>
struct ParamTraits<mozilla::dom::EmbedderColorSchemes> {
using paramType = mozilla::dom::EmbedderColorSchemes;
static void Write(MessageWriter* aWriter, const paramType& aParam) {
WriteParam(aWriter, aParam.mUsed);
WriteParam(aWriter, aParam.mPreferred);
}
static bool Read(MessageReader* aReader, paramType* aResult) {
return ReadParam(aReader, &aResult->mUsed) &&
ReadParam(aReader, &aResult->mPreferred);
}
};
} // namespace IPC
namespace mozilla {
namespace dom {
// Explicit specialization of the `Transaction` type. Required by the `extern
// template class` declaration in the header.
template class syncedcontext::Transaction<BrowsingContext>;
extern mozilla::LazyLogModule gUserInteractionPRLog;
#define USER_ACTIVATION_LOG(msg, ...) \
MOZ_LOG(gUserInteractionPRLog, LogLevel::Debug, (msg, ##__VA_ARGS__))
static LazyLogModule gBrowsingContextLog("BrowsingContext");
static LazyLogModule gBrowsingContextSyncLog("BrowsingContextSync");
typedef nsTHashMap<nsUint64HashKey, BrowsingContext*> BrowsingContextMap;
// All BrowsingContexts indexed by Id
static StaticAutoPtr<BrowsingContextMap> sBrowsingContexts;
// Top-level Content BrowsingContexts only, indexed by BrowserId instead of Id
static StaticAutoPtr<BrowsingContextMap> sCurrentTopByBrowserId;
static bool gIPCEnabledAnnotation = false;
static bool gFissionEnabledAnnotation = false;
static void UnregisterBrowserId(BrowsingContext* aBrowsingContext) {
if (!aBrowsingContext->IsTopContent() || !sCurrentTopByBrowserId) {
return;
}
// Avoids an extra lookup
auto browserIdEntry =
sCurrentTopByBrowserId->Lookup(aBrowsingContext->BrowserId());
if (browserIdEntry && browserIdEntry.Data() == aBrowsingContext) {
browserIdEntry.Remove();
}
}
static void Register(BrowsingContext* aBrowsingContext) {
sBrowsingContexts->InsertOrUpdate(aBrowsingContext->Id(), aBrowsingContext);
if (aBrowsingContext->IsTopContent()) {
sCurrentTopByBrowserId->InsertOrUpdate(aBrowsingContext->BrowserId(),
aBrowsingContext);
}
aBrowsingContext->Group()->Register(aBrowsingContext);
}
// static
void BrowsingContext::UpdateCurrentTopByBrowserId(
BrowsingContext* aNewBrowsingContext) {
if (aNewBrowsingContext->IsTopContent()) {
sCurrentTopByBrowserId->InsertOrUpdate(aNewBrowsingContext->BrowserId(),
aNewBrowsingContext);
}
}
BrowsingContext* BrowsingContext::GetParent() const {
return mParentWindow ? mParentWindow->GetBrowsingContext() : nullptr;
}
bool BrowsingContext::IsInSubtreeOf(BrowsingContext* aContext) {
BrowsingContext* bc = this;
do {
if (bc == aContext) {
return true;
}
} while ((bc = bc->GetParent()));
return false;
}
BrowsingContext* BrowsingContext::Top() {
BrowsingContext* bc = this;
while (bc->mParentWindow) {
bc = bc->GetParent();
}
return bc;
}
const BrowsingContext* BrowsingContext::Top() const {
const BrowsingContext* bc = this;
while (bc->mParentWindow) {
bc = bc->GetParent();
}
return bc;
}
int32_t BrowsingContext::IndexOf(BrowsingContext* aChild) {
int32_t index = -1;
for (BrowsingContext* child : Children()) {
++index;
if (child == aChild) {
break;
}
}
return index;
}
WindowContext* BrowsingContext::GetTopWindowContext() const {
if (mParentWindow) {
return mParentWindow->TopWindowContext();
}
return mCurrentWindowContext;
}
/* static */
void BrowsingContext::Init() {
if (!sBrowsingContexts) {
sBrowsingContexts = new BrowsingContextMap();
sCurrentTopByBrowserId = new BrowsingContextMap();
ClearOnShutdown(&sBrowsingContexts);
ClearOnShutdown(&sCurrentTopByBrowserId);
CrashReporter::RegisterAnnotationBool(
CrashReporter::Annotation::DOMIPCEnabled, &gIPCEnabledAnnotation);
CrashReporter::RegisterAnnotationBool(
CrashReporter::Annotation::DOMFissionEnabled,
&gFissionEnabledAnnotation);
}
}
/* static */
LogModule* BrowsingContext::GetLog() { return gBrowsingContextLog; }
/* static */
LogModule* BrowsingContext::GetSyncLog() { return gBrowsingContextSyncLog; }
/* static */
already_AddRefed<BrowsingContext> BrowsingContext::Get(uint64_t aId) {
if (sBrowsingContexts) {
return do_AddRef(sBrowsingContexts->Get(aId));
}
return nullptr;
}
/* static */
already_AddRefed<BrowsingContext> BrowsingContext::GetCurrentTopByBrowserId(
uint64_t aBrowserId) {
return do_AddRef(sCurrentTopByBrowserId->Get(aBrowserId));
}
/* static */
already_AddRefed<BrowsingContext> BrowsingContext::GetFromWindow(
WindowProxyHolder& aProxy) {
return do_AddRef(aProxy.get());
}
CanonicalBrowsingContext* BrowsingContext::Canonical() {
return CanonicalBrowsingContext::Cast(this);
}
bool BrowsingContext::IsOwnedByProcess() const {
return mIsInProcess && mDocShell &&
!nsDocShell::Cast(mDocShell)->WillChangeProcess();
}
bool BrowsingContext::SameOriginWithTop() {
MOZ_ASSERT(IsInProcess());
// If the top BrowsingContext is not same-process to us, it is cross-origin
if (!Top()->IsInProcess()) {
return false;
}
nsIDocShell* docShell = GetDocShell();
if (!docShell) {
return false;
}
Document* doc = docShell->GetDocument();
if (!doc) {
return false;
}
nsIPrincipal* principal = doc->NodePrincipal();
nsIDocShell* topDocShell = Top()->GetDocShell();
if (!topDocShell) {
return false;
}
Document* topDoc = topDocShell->GetDocument();
if (!topDoc) {
return false;
}
nsIPrincipal* topPrincipal = topDoc->NodePrincipal();
return principal->Equals(topPrincipal);
}
/* static */
already_AddRefed<BrowsingContext> BrowsingContext::CreateDetached(
nsGlobalWindowInner* aParent, BrowsingContext* aOpener,
BrowsingContextGroup* aSpecificGroup, const nsAString& aName, Type aType,
CreateDetachedOptions aOptions) {
if (aParent) {
MOZ_DIAGNOSTIC_ASSERT(aParent->GetWindowContext());
MOZ_DIAGNOSTIC_ASSERT(aParent->GetBrowsingContext()->mType == aType);
MOZ_DIAGNOSTIC_ASSERT(aParent->GetBrowsingContext()->GetBrowserId() != 0);
}
MOZ_DIAGNOSTIC_ASSERT(aType != Type::Chrome || XRE_IsParentProcess());
uint64_t id = nsContentUtils::GenerateBrowsingContextId();
MOZ_LOG(GetLog(), LogLevel::Debug,
("Creating 0x%08" PRIx64 " in %s", id,
XRE_IsParentProcess() ? "Parent" : "Child"));
RefPtr<BrowsingContext> parentBC =
aParent ? aParent->GetBrowsingContext() : nullptr;
RefPtr<WindowContext> parentWC =
aParent ? aParent->GetWindowContext() : nullptr;
BrowsingContext* inherit = parentBC ? parentBC.get() : aOpener;
// Determine which BrowsingContextGroup this context should be created in.
RefPtr<BrowsingContextGroup> group = aSpecificGroup;
if (aType == Type::Chrome) {
MOZ_DIAGNOSTIC_ASSERT(!group);
group = BrowsingContextGroup::GetChromeGroup();
} else if (!group) {
group = BrowsingContextGroup::Select(parentWC, aOpener);
}
// Configure initial values for synced fields.
FieldValues fields;
fields.Get<IDX_Name>() = aName;
if (aOpener) {
MOZ_DIAGNOSTIC_ASSERT(!aParent,
"new BC with both initial opener and parent");
MOZ_DIAGNOSTIC_ASSERT(aOpener->Group() == group);
MOZ_DIAGNOSTIC_ASSERT(aOpener->mType == aType);
fields.Get<IDX_OpenerId>() = aOpener->Id();
fields.Get<IDX_HadOriginalOpener>() = true;
if (aType == Type::Chrome && !aParent) {
// See SetOpener for why we do this inheritance.
fields.Get<IDX_PrefersColorSchemeOverride>() =
aOpener->Top()->GetPrefersColorSchemeOverride();
}
}
if (aParent) {
MOZ_DIAGNOSTIC_ASSERT(parentBC->Group() == group);
MOZ_DIAGNOSTIC_ASSERT(parentBC->mType == aType);
fields.Get<IDX_EmbedderInnerWindowId>() = aParent->WindowID();
// Non-toplevel content documents are always embededed within content.
fields.Get<IDX_EmbeddedInContentDocument>() =
parentBC->mType == Type::Content;
// XXX(farre): Can/Should we check aParent->IsLoading() here? (Bug
// 1608448) Check if the parent was itself loading already
auto readystate = aParent->GetDocument()->GetReadyStateEnum();
fields.Get<IDX_AncestorLoading>() =
parentBC->GetAncestorLoading() ||
readystate == Document::ReadyState::READYSTATE_LOADING ||
readystate == Document::ReadyState::READYSTATE_INTERACTIVE;
}
fields.Get<IDX_BrowserId>() =
parentBC ? parentBC->GetBrowserId() : nsContentUtils::GenerateBrowserId();
fields.Get<IDX_OpenerPolicy>() = nsILoadInfo::OPENER_POLICY_UNSAFE_NONE;
if (aOpener && aOpener->SameOriginWithTop()) {
// We inherit the opener policy if there is a creator and if the creator's
// origin is same origin with the creator's top-level origin.
// If it is cross origin we should not inherit the CrossOriginOpenerPolicy
fields.Get<IDX_OpenerPolicy>() = aOpener->Top()->GetOpenerPolicy();
// If we inherit a policy which is potentially cross-origin isolated, we
// must be in a potentially cross-origin isolated BCG.
bool isPotentiallyCrossOriginIsolated =
fields.Get<IDX_OpenerPolicy>() ==
nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP;
MOZ_RELEASE_ASSERT(isPotentiallyCrossOriginIsolated ==
group->IsPotentiallyCrossOriginIsolated());
} else if (aOpener) {
// They are not same origin
auto topPolicy = aOpener->Top()->GetOpenerPolicy();
MOZ_RELEASE_ASSERT(
topPolicy == nsILoadInfo::OPENER_POLICY_UNSAFE_NONE ||
topPolicy == nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_ALLOW_POPUPS ||
aOptions.isForPrinting);
if (aOptions.isForPrinting) {
// Ensure our opener policy is consistent for printing for our top.
fields.Get<IDX_OpenerPolicy>() = topPolicy;
}
} else if (!aParent && group->IsPotentiallyCrossOriginIsolated()) {
// If we're creating a brand-new toplevel BC in a potentially cross-origin
// isolated group, it should start out with a strict opener policy.
fields.Get<IDX_OpenerPolicy>() =
nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP;
}
fields.Get<IDX_HistoryID>() = nsID::GenerateUUID();
fields.Get<IDX_ExplicitActive>() = [&] {
if (parentBC || aType == Type::Content) {
// Non-root browsing-contexts inherit their status from its parent.
// Top-content either gets managed by the top chrome, or gets manually
// managed by the front-end (see ManuallyManagesActiveness). In any case
// we want to start off as inactive.
return ExplicitActiveStatus::None;
}
// Chrome starts as active.
return ExplicitActiveStatus::Active;
}();
fields.Get<IDX_FullZoom>() = parentBC ? parentBC->FullZoom() : 1.0f;
fields.Get<IDX_TextZoom>() = parentBC ? parentBC->TextZoom() : 1.0f;
bool allowContentRetargeting =
inherit ? inherit->GetAllowContentRetargetingOnChildren() : true;
fields.Get<IDX_AllowContentRetargeting>() = allowContentRetargeting;
fields.Get<IDX_AllowContentRetargetingOnChildren>() = allowContentRetargeting;
// Assume top allows fullscreen for its children unless otherwise stated.
// Subframes start with it false unless otherwise noted in SetEmbedderElement.
fields.Get<IDX_FullscreenAllowedByOwner>() = !aParent;
fields.Get<IDX_DefaultLoadFlags>() =
inherit ? inherit->GetDefaultLoadFlags() : nsIRequest::LOAD_NORMAL;
fields.Get<IDX_OrientationLock>() = mozilla::hal::ScreenOrientation::None;
fields.Get<IDX_UseGlobalHistory>() =
inherit ? inherit->GetUseGlobalHistory() : false;
fields.Get<IDX_UseErrorPages>() = true;
fields.Get<IDX_TouchEventsOverrideInternal>() = TouchEventsOverride::None;
fields.Get<IDX_AllowJavascript>() =
inherit ? inherit->GetAllowJavascript() : true;
fields.Get<IDX_IPAddressSpace>() = inherit
? inherit->GetIPAddressSpace()
: nsILoadInfo::IPAddressSpace::Unknown;
bool parentalControlsEnabled;
if (inherit) {
parentalControlsEnabled = inherit->GetParentalControlsEnabled();
} else if (XRE_IsParentProcess()) {
parentalControlsEnabled =
CanonicalBrowsingContext::ShouldEnforceParentalControls();
} else {
parentalControlsEnabled = false;
}
fields.Get<IDX_ParentalControlsEnabled>() = parentalControlsEnabled;
fields.Get<IDX_IsPopupRequested>() = aOptions.isPopupRequested;
fields.Get<IDX_TopLevelCreatedByWebContent>() =
aOptions.topLevelCreatedByWebContent;
if (!parentBC) {
fields.Get<IDX_ShouldDelayMediaFromStart>() =
StaticPrefs::media_block_autoplay_until_in_foreground();
}
RefPtr<BrowsingContext> context;
if (XRE_IsParentProcess()) {
context = new CanonicalBrowsingContext(parentWC, group, id,
/* aOwnerProcessId */ 0,
/* aEmbedderProcessId */ 0, aType,
std::move(fields));
} else {
context =
new BrowsingContext(parentWC, group, id, aType, std::move(fields));
}
context->mWindowless = aOptions.windowless;
context->mEmbeddedByThisProcess = XRE_IsParentProcess() || aParent;
context->mCreatedDynamically = aOptions.createdDynamically;
if (inherit) {
context->mPrivateBrowsingId = inherit->mPrivateBrowsingId;
context->mUseRemoteTabs = inherit->mUseRemoteTabs;
context->mUseRemoteSubframes = inherit->mUseRemoteSubframes;
context->mOriginAttributes = inherit->mOriginAttributes;
}
nsCOMPtr<nsIRequestContextService> rcsvc =
net::RequestContextService::GetOrCreate();
if (rcsvc) {
nsCOMPtr<nsIRequestContext> requestContext;
nsresult rv = rcsvc->NewRequestContext(getter_AddRefs(requestContext));
if (NS_SUCCEEDED(rv) && requestContext) {
context->mRequestContextId = requestContext->GetID();
}
}
return context.forget();
}
already_AddRefed<BrowsingContext> BrowsingContext::CreateIndependent(
Type aType, bool aWindowless) {
MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess(),
"BCs created in the content process must be related to "
"some BrowserChild");
RefPtr<BrowsingContext> bc(
CreateDetached(nullptr, nullptr, nullptr, u""_ns, aType, {}));
bc->mWindowless = aWindowless;
bc->mEmbeddedByThisProcess = true;
bc->EnsureAttached();
return bc.forget();
}
void BrowsingContext::EnsureAttached() {
if (!mEverAttached) {
Register(this);
// Attach the browsing context to the tree.
Attach(/* aFromIPC */ false, /* aOriginProcess */ nullptr);
}
}
/* static */
mozilla::ipc::IPCResult BrowsingContext::CreateFromIPC(
BrowsingContext::IPCInitializer&& aInit, BrowsingContextGroup* aGroup,
ContentParent* aOriginProcess) {
MOZ_DIAGNOSTIC_ASSERT(aOriginProcess || XRE_IsContentProcess());
MOZ_DIAGNOSTIC_ASSERT(aGroup);
uint64_t originId = 0;
if (aOriginProcess) {
originId = aOriginProcess->ChildID();
aGroup->EnsureHostProcess(aOriginProcess);
}
MOZ_LOG(GetLog(), LogLevel::Debug,
("Creating 0x%08" PRIx64 " from IPC (origin=0x%08" PRIx64 ")",
aInit.mId, originId));
RefPtr<WindowContext> parent = aInit.GetParent();
RefPtr<BrowsingContext> context;
if (XRE_IsParentProcess()) {
// If the new BrowsingContext has a parent, it is a sub-frame embedded in
// whatever process sent the message. If it doesn't, and is not windowless,
// it is a new window or tab, and will be embedded in the parent process.
uint64_t embedderProcessId = (aInit.mWindowless || parent) ? originId : 0;
context = new CanonicalBrowsingContext(parent, aGroup, aInit.mId, originId,
embedderProcessId, Type::Content,
std::move(aInit.mFields));
} else {
context = new BrowsingContext(parent, aGroup, aInit.mId, Type::Content,
std::move(aInit.mFields));
}
context->mWindowless = aInit.mWindowless;
context->mCreatedDynamically = aInit.mCreatedDynamically;
context->mChildOffset = aInit.mChildOffset;
if (context->GetHasSessionHistory()) {
context->CreateChildSHistory();
if (mozilla::SessionHistoryInParent()) {
context->GetChildSessionHistory()->SetIndexAndLength(
aInit.mSessionHistoryIndex, aInit.mSessionHistoryCount, nsID());
}
}
// NOTE: Call through the `Set` methods for these values to ensure that any
// relevant process-local state is also updated.
context->SetOriginAttributes(aInit.mOriginAttributes);
context->SetRemoteTabs(aInit.mUseRemoteTabs);
context->SetRemoteSubframes(aInit.mUseRemoteSubframes);
context->mRequestContextId = aInit.mRequestContextId;
// NOTE: Private browsing ID is set by `SetOriginAttributes`.
if (const char* failure =
context->BrowsingContextCoherencyChecks(aOriginProcess)) {
mozilla::ipc::IProtocol* actor = aOriginProcess;
if (!actor) {
actor = ContentChild::GetSingleton();
}
return IPC_FAIL_UNSAFE_PRINTF(actor, "Incoherent BrowsingContext: %s",
failure);
}
Register(context);
context->Attach(/* aFromIPC */ true, aOriginProcess);
return IPC_OK();
}
BrowsingContext::BrowsingContext(WindowContext* aParentWindow,
BrowsingContextGroup* aGroup,
uint64_t aBrowsingContextId, Type aType,
FieldValues&& aInit)
: mFields(std::move(aInit)),
mType(aType),
mBrowsingContextId(aBrowsingContextId),
mGroup(aGroup),
mParentWindow(aParentWindow),
mPrivateBrowsingId(0),
mEverAttached(false),
mIsInProcess(false),
mIsDiscarded(false),
mWindowless(false),
mDanglingRemoteOuterProxies(false),
mEmbeddedByThisProcess(false),
mUseRemoteTabs(false),
mUseRemoteSubframes(false),
mCreatedDynamically(false),
mIsInBFCache(false),
mCanExecuteScripts(true),
mChildOffset(0) {
MOZ_RELEASE_ASSERT(!mParentWindow || mParentWindow->Group() == mGroup);
MOZ_RELEASE_ASSERT(mBrowsingContextId != 0);
MOZ_RELEASE_ASSERT(mGroup);
}
void BrowsingContext::SetDocShell(nsIDocShell* aDocShell) {
// XXX(nika): We should communicate that we are now an active BrowsingContext
// process to the parent & do other validation here.
MOZ_DIAGNOSTIC_ASSERT(mEverAttached);
MOZ_RELEASE_ASSERT(aDocShell->GetBrowsingContext() == this);
mDocShell = aDocShell;
mDanglingRemoteOuterProxies = !mIsInProcess;
mIsInProcess = true;
if (mChildSessionHistory) {
mChildSessionHistory->SetIsInProcess(true);
}
RecomputeCanExecuteScripts();
ClearCachedValuesOfLocations();
}
// This class implements a callback that will return the remote window proxy for
// mBrowsingContext in that compartment, if it has one. It also removes the
// proxy from the map, because the object will be transplanted into another kind
// of object.
class MOZ_STACK_CLASS CompartmentRemoteProxyTransplantCallback
: public js::CompartmentTransplantCallback {
public:
explicit CompartmentRemoteProxyTransplantCallback(
BrowsingContext* aBrowsingContext)
: mBrowsingContext(aBrowsingContext) {}
virtual JSObject* getObjectToTransplant(
JS::Compartment* compartment) override {
auto* priv = xpc::CompartmentPrivate::Get(compartment);
if (!priv) {
return nullptr;
}
auto& map = priv->GetRemoteProxyMap();
auto result = map.lookup(mBrowsingContext);
if (!result) {
return nullptr;
}
JSObject* resultObject = result->value();
map.remove(result);
return resultObject;
}
private:
BrowsingContext* mBrowsingContext;
};
void BrowsingContext::CleanUpDanglingRemoteOuterWindowProxies(
JSContext* aCx, JS::MutableHandle<JSObject*> aOuter) {
if (!mDanglingRemoteOuterProxies) {
return;
}
mDanglingRemoteOuterProxies = false;
CompartmentRemoteProxyTransplantCallback cb(this);
js::RemapRemoteWindowProxies(aCx, &cb, aOuter);
}
bool BrowsingContext::IsActive() const {
const BrowsingContext* current = this;
do {
auto explicit_ = current->GetExplicitActive();
if (explicit_ != ExplicitActiveStatus::None) {
return explicit_ == ExplicitActiveStatus::Active;
}
if (mParentWindow && !mParentWindow->IsCurrent()) {
return false;
}
} while ((current = current->GetParent()));
return false;
}
bool BrowsingContext::GetIsActiveBrowserWindow() {
if (!XRE_IsParentProcess()) {
return Top()->GetIsActiveBrowserWindowInternal();
}
// chrome:// urls loaded in the parent won't receive
// their own activation so we defer to the top chrome
// Browsing Context when in the parent process.
return Canonical()
->TopCrossChromeBoundary()
->GetIsActiveBrowserWindowInternal();
}
void BrowsingContext::SetIsActiveBrowserWindow(bool aActive) {
(void)SetIsActiveBrowserWindowInternal(aActive);
}
bool BrowsingContext::FullscreenAllowed() const {
for (auto* current = this; current; current = current->GetParent()) {
if (!current->GetFullscreenAllowedByOwner()) {
return false;
}
}
return true;
}
static bool OwnerAllowsFullscreen(const Element& aEmbedder) {
if (aEmbedder.IsXULElement()) {
return !aEmbedder.HasAttr(nsGkAtoms::disablefullscreen);
}
if (aEmbedder.IsHTMLElement(nsGkAtoms::iframe)) {
// This is controlled by feature policy.
return true;
}
if (const auto* embed = HTMLEmbedElement::FromNode(aEmbedder)) {
return embed->AllowFullscreen();
}
return false;
}
void BrowsingContext::SetEmbedderElement(Element* aEmbedder) {
mEmbeddedByThisProcess = true;
if (RefPtr<WindowContext> parent = GetParentWindowContext()) {
parent->ClearLightDOMChildren();
}
// Update embedder-element-specific fields in a shared transaction.
// Don't do this when clearing our embedder, as we're being destroyed either
// way.
if (aEmbedder) {
Transaction txn;
txn.SetEmbedderElementType(Some(aEmbedder->LocalName()));
txn.SetEmbeddedInContentDocument(
aEmbedder->OwnerDoc()->IsContentDocument());
if (nsCOMPtr<nsPIDOMWindowInner> inner =
do_QueryInterface(aEmbedder->GetOwnerGlobal())) {
txn.SetEmbedderInnerWindowId(inner->WindowID());
}
txn.SetFullscreenAllowedByOwner(OwnerAllowsFullscreen(*aEmbedder));
if (XRE_IsParentProcess() && aEmbedder->IsXULElement() && IsTopContent()) {
nsAutoString messageManagerGroup;
aEmbedder->GetAttr(nsGkAtoms::messagemanagergroup, messageManagerGroup);
txn.SetMessageManagerGroup(messageManagerGroup);
txn.SetUseGlobalHistory(
!aEmbedder->HasAttr(nsGkAtoms::disableglobalhistory));
if (!aEmbedder->HasAttr(nsGkAtoms::manualactiveness)) {
// We're active iff the parent cross-chrome-boundary is active. Note we
// can't just use this->Canonical()->GetParentCrossChromeBoundary here,
// since mEmbedderElement is still null at this point.
RefPtr bc = aEmbedder->OwnerDoc()->GetBrowsingContext();
const bool isActive = bc && bc->IsActive();
txn.SetExplicitActive(isActive ? ExplicitActiveStatus::Active
: ExplicitActiveStatus::Inactive);
if (auto* bp = Canonical()->GetBrowserParent()) {
bp->SetRenderLayers(isActive);
}
}
}
MOZ_ALWAYS_SUCCEEDS(txn.Commit(this));
}
if (XRE_IsParentProcess() && IsTopContent()) {
Canonical()->MaybeSetPermanentKey(aEmbedder);
}
mEmbedderElement = aEmbedder;
if (mEmbedderElement) {
if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
obs->NotifyWhenScriptSafe(ToSupports(this),
"browsing-context-did-set-embedder", nullptr);
}
if (IsEmbedderTypeObjectOrEmbed()) {
(void)SetIsSyntheticDocumentContainer(true);
}
}
}
bool BrowsingContext::IsEmbedderTypeObjectOrEmbed() {
if (const Maybe<nsString>& type = GetEmbedderElementType()) {
return nsGkAtoms::object->Equals(*type) || nsGkAtoms::embed->Equals(*type);
}
return false;
}
void BrowsingContext::Embed() {
if (auto* frame = HTMLIFrameElement::FromNode(mEmbedderElement)) {
frame->BindToBrowsingContext(this);
}
}
const char* BrowsingContext::BrowsingContextCoherencyChecks(
ContentParent* aOriginProcess) {
#define COHERENCY_ASSERT(condition) \
if (!(condition)) return "Assertion " #condition " failed";
if (mGroup->IsPotentiallyCrossOriginIsolated() !=
(Top()->GetOpenerPolicy() ==
nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP)) {
return "Invalid CrossOriginIsolated state";
}
if (aOriginProcess && !IsContent()) {
return "Content cannot create chrome BCs";
}
// LoadContext should generally match our opener or parent.
if (IsContent()) {
if (RefPtr<BrowsingContext> opener = GetOpener()) {
COHERENCY_ASSERT(opener->mType == mType);
COHERENCY_ASSERT(opener->mGroup == mGroup);
COHERENCY_ASSERT(opener->mUseRemoteTabs == mUseRemoteTabs);
COHERENCY_ASSERT(opener->mUseRemoteSubframes == mUseRemoteSubframes);
COHERENCY_ASSERT(opener->mPrivateBrowsingId == mPrivateBrowsingId);
COHERENCY_ASSERT(
opener->mOriginAttributes.EqualsIgnoringFPD(mOriginAttributes));
}
}
if (RefPtr<BrowsingContext> parent = GetParent()) {
COHERENCY_ASSERT(parent->mType == mType);
COHERENCY_ASSERT(parent->mGroup == mGroup);
COHERENCY_ASSERT(parent->mUseRemoteTabs == mUseRemoteTabs);
COHERENCY_ASSERT(parent->mUseRemoteSubframes == mUseRemoteSubframes);
COHERENCY_ASSERT(parent->mPrivateBrowsingId == mPrivateBrowsingId);
COHERENCY_ASSERT(
parent->mOriginAttributes.EqualsIgnoringFPD(mOriginAttributes));
}
// UseRemoteSubframes and UseRemoteTabs must match.
if (mUseRemoteSubframes && !mUseRemoteTabs) {
return "Cannot set useRemoteSubframes without also setting useRemoteTabs";
}
// Double-check OriginAttributes/Private Browsing
// Chrome browsing contexts must not have a private browsing OriginAttribute
// Content browsing contexts must maintain the equality:
// mOriginAttributes.mPrivateBrowsingId == mPrivateBrowsingId
if (IsChrome()) {
COHERENCY_ASSERT(mOriginAttributes.mPrivateBrowsingId == 0);
} else {
COHERENCY_ASSERT(mOriginAttributes.mPrivateBrowsingId ==
mPrivateBrowsingId);
}
#undef COHERENCY_ASSERT
return nullptr;
}
void BrowsingContext::Attach(bool aFromIPC, ContentParent* aOriginProcess) {
MOZ_DIAGNOSTIC_ASSERT(!mEverAttached);
MOZ_DIAGNOSTIC_ASSERT_IF(aFromIPC, aOriginProcess || XRE_IsContentProcess());
mEverAttached = true;
if (MOZ_LOG_TEST(GetLog(), LogLevel::Debug)) {
nsAutoCString suffix;
mOriginAttributes.CreateSuffix(suffix);
MOZ_LOG(GetLog(), LogLevel::Debug,
("%s: Connecting 0x%08" PRIx64 " to 0x%08" PRIx64
" (private=%d, remote=%d, fission=%d, oa=%s)",
XRE_IsParentProcess() ? "Parent" : "Child", Id(),
GetParent() ? GetParent()->Id() : 0, (int)mPrivateBrowsingId,
(int)mUseRemoteTabs, (int)mUseRemoteSubframes, suffix.get()));
}
MOZ_DIAGNOSTIC_ASSERT(mGroup);
MOZ_DIAGNOSTIC_ASSERT(!mIsDiscarded);
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
// We'll already have checked this if `aFromIPC` is set before calling this
// function.
if (!aFromIPC) {
if (const char* failure = BrowsingContextCoherencyChecks(aOriginProcess)) {
MOZ_CRASH_UNSAFE_PRINTF("Incoherent BrowsingContext: %s", failure);
}
}
#endif
// Add ourselves either to our parent or BrowsingContextGroup's child list.
// Important: We shouldn't return IPC_FAIL after this point, since the
// BrowsingContext will have already been added to the tree.
if (mParentWindow) {
if (!aFromIPC) {
MOZ_DIAGNOSTIC_ASSERT(!mParentWindow->IsDiscarded(),
"local attach in discarded window");
MOZ_DIAGNOSTIC_ASSERT(!GetParent()->IsDiscarded(),
"local attach call in discarded bc");
MOZ_DIAGNOSTIC_ASSERT(mParentWindow->GetWindowGlobalChild(),
"local attach call with oop parent window");
MOZ_DIAGNOSTIC_ASSERT(mParentWindow->GetWindowGlobalChild()->CanSend(),
"local attach call with dead parent window");
}
mChildOffset =
mCreatedDynamically ? -1 : mParentWindow->Children().Length();
mParentWindow->AppendChildBrowsingContext(this);
RecomputeCanExecuteScripts();
} else {
mGroup->Toplevels().AppendElement(this);
}
if (GetIsPopupSpam()) {
PopupBlocker::RegisterOpenPopupSpam();
}
if (IsTop() && GetHasSessionHistory() && !mChildSessionHistory) {
CreateChildSHistory();
}
// Why the context is being attached. This will always be "attach" in the
// content process, but may be "replace" if it's known the context being
// replaced in the parent process.
const char16_t* why = u"attach";
if (XRE_IsContentProcess() && !aFromIPC) {
// Send attach to our parent if we need to.
ContentChild::GetSingleton()->SendCreateBrowsingContext(
mGroup->Id(), GetIPCInitializer());
} else if (XRE_IsParentProcess()) {
// If this window was created as a subframe by a content process, it must be
// being hosted within the same BrowserParent as its mParentWindow.
// Toplevel BrowsingContexts created by content have their BrowserParent
// configured during `RecvConstructPopupBrowser`.
if (mParentWindow && aOriginProcess) {
MOZ_DIAGNOSTIC_ASSERT(
mParentWindow->Canonical()->GetContentParent() == aOriginProcess,
"Creator process isn't the same as our embedder?");
Canonical()->SetCurrentBrowserParent(
mParentWindow->Canonical()->GetBrowserParent());
}
mGroup->EachOtherParent(aOriginProcess, [&](ContentParent* aParent) {
MOZ_DIAGNOSTIC_ASSERT(IsContent(),
"chrome BCG cannot be synced to content process");
if (!Canonical()->IsEmbeddedInProcess(aParent->ChildID())) {
(void)aParent->SendCreateBrowsingContext(mGroup->Id(),
GetIPCInitializer());
}
});
if (IsTop() && IsContent() && Canonical()->GetWebProgress()) {
why = u"replace";
}
// We want to create a BrowsingContextWebProgress for all content
// BrowsingContexts.
if (IsContent() && !Canonical()->mWebProgress) {
Canonical()->mWebProgress = new BrowsingContextWebProgress(Canonical());
}
}
if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
obs->NotifyWhenScriptSafe(ToSupports(this), "browsing-context-attached",
why);
}
if (XRE_IsParentProcess()) {
Canonical()->CanonicalAttach();
}
}
void BrowsingContext::Detach(bool aFromIPC) {
MOZ_LOG(GetLog(), LogLevel::Debug,
("%s: Detaching 0x%08" PRIx64 " from 0x%08" PRIx64,
XRE_IsParentProcess() ? "Parent" : "Child", Id(),
GetParent() ? GetParent()->Id() : 0));
MOZ_DIAGNOSTIC_ASSERT(mEverAttached);
MOZ_DIAGNOSTIC_ASSERT(!mIsDiscarded);
if (XRE_IsParentProcess()) {
Canonical()->AddPendingDiscard();
Canonical()->mActiveEntryList = nullptr;
}
auto callListeners =
MakeScopeExit([&, listeners = std::move(mDiscardListeners), id = Id()] {
for (const auto& listener : listeners) {
listener(id);
}
if (XRE_IsParentProcess()) {
Canonical()->RemovePendingDiscard();
}
});
nsCOMPtr<nsIRequestContextService> rcsvc =
net::RequestContextService::GetOrCreate();
if (rcsvc) {
rcsvc->RemoveRequestContext(GetRequestContextId());
}
// This will only ever be null if the cycle-collector has unlinked us. Don't
// try to detach ourselves in that case.
if (NS_WARN_IF(!mGroup)) {
MOZ_ASSERT_UNREACHABLE();
return;
}
if (mParentWindow) {
mParentWindow->RemoveChildBrowsingContext(this);
} else {
mGroup->Toplevels().RemoveElement(this);
}
if (XRE_IsParentProcess()) {
RefPtr<CanonicalBrowsingContext> self{Canonical()};
Group()->EachParent([&](ContentParent* aParent) {
// Only the embedder process is allowed to initiate a BrowsingContext
// detach, so if we've gotten here, the host process already knows we've
// been detached, and there's no need to tell it again.
//
// If the owner process is not the same as the embedder process, its
// BrowsingContext will be detached when its nsWebBrowser instance is
// destroyed.
bool doDiscard = !Canonical()->IsEmbeddedInProcess(aParent->ChildID()) &&
!Canonical()->IsOwnedByProcess(aParent->ChildID());
// Hold a strong reference to ourself, and keep our BrowsingContextGroup
// alive, until the responses comes back to ensure we don't die while
// messages relating to this context are in-flight.
//
// When the callback is called, the keepalive on our group will be
// destroyed, and the reference to the BrowsingContext will be dropped,
// which may cause it to be fully destroyed.
mGroup->AddKeepAlive();
self->AddPendingDiscard();
auto callback = [self](auto) {
self->mGroup->RemoveKeepAlive();
self->RemovePendingDiscard();
};
aParent->SendDiscardBrowsingContext(this, doDiscard, callback, callback);
});
} else {
// Hold a strong reference to ourself until the responses come back to
// ensure the BrowsingContext isn't cleaned up before the parent process
// acknowledges the discard request.
auto callback = [self = RefPtr{this}](auto) {};
ContentChild::GetSingleton()->SendDiscardBrowsingContext(
this, !aFromIPC, callback, callback);
}
mGroup->Unregister(this);
UnregisterBrowserId(this);
mIsDiscarded = true;
if (XRE_IsParentProcess()) {
nsFocusManager* fm = nsFocusManager::GetFocusManager();
if (fm) {
fm->BrowsingContextDetached(this);
}
}
if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
// Why the context is being discarded. This will always be "discard" in the
// content process, but may be "replace" if it's known the context being
// replaced in the parent process.
const char16_t* why = u"discard";
if (XRE_IsParentProcess() && Canonical()->IsReplaced()) {
why = u"replace";
}
obs->NotifyObservers(ToSupports(this), "browsing-context-discarded", why);
}
// NOTE: Doesn't use SetClosed, as it will be set in all processes
// automatically by calls to Detach()
mFields.SetWithoutSyncing<IDX_Closed>(true);
if (GetIsPopupSpam()) {
PopupBlocker::UnregisterOpenPopupSpam();
// NOTE: Doesn't use SetIsPopupSpam, as it will be set all processes
// automatically.
mFields.SetWithoutSyncing<IDX_IsPopupSpam>(false);
}
AssertOriginAttributesMatchPrivateBrowsing();
if (XRE_IsParentProcess()) {
Canonical()->CanonicalDiscard();
}
}
void BrowsingContext::AddDiscardListener(
std::function<void(uint64_t)>&& aListener) {
if (mIsDiscarded) {
aListener(Id());
return;
}
mDiscardListeners.AppendElement(std::move(aListener));
}
void BrowsingContext::PrepareForProcessChange() {
MOZ_LOG(GetLog(), LogLevel::Debug,
("%s: Preparing 0x%08" PRIx64 " for a process change",
XRE_IsParentProcess() ? "Parent" : "Child", Id()));
MOZ_ASSERT(mIsInProcess, "Must currently be an in-process frame");
MOZ_ASSERT(!mIsDiscarded, "We're already closed?");
mIsInProcess = false;
mUserGestureStart = TimeStamp();
ClearCachedValuesOfLocations();
// NOTE: For now, clear our nsDocShell reference, as we're primarily in a
// different process now. This may need to change in the future with
// Cross-Process BFCache.
mDocShell = nullptr;
if (mChildSessionHistory) {
// This can be removed once session history is stored exclusively in the
// parent process.
mChildSessionHistory->SetIsInProcess(false);
}
if (!mWindowProxy) {
return;
}
// We have to go through mWindowProxy rather than calling GetDOMWindow() on
// mDocShell because the mDocshell reference gets cleared immediately after
// the window is closed.
nsGlobalWindowOuter::PrepareForProcessChange(mWindowProxy);
MOZ_ASSERT(!mWindowProxy);
}
bool BrowsingContext::IsTargetable() const {
return !GetClosed() && AncestorsAreCurrent();
}
void BrowsingContext::SetOpener(BrowsingContext* aOpener) {
MOZ_DIAGNOSTIC_ASSERT(!aOpener || aOpener->Group() == Group());
MOZ_DIAGNOSTIC_ASSERT(!aOpener || aOpener->mType == mType);
MOZ_ALWAYS_SUCCEEDS(SetOpenerId(aOpener ? aOpener->Id() : 0));
if (IsChrome() && IsTop() && aOpener) {
// Inherit color scheme overrides from parent window. This is to inherit the
// color scheme of dark themed PBM windows in dialogs opened by such
// windows.
auto openerOverride = aOpener->Top()->PrefersColorSchemeOverride();
if (openerOverride != PrefersColorSchemeOverride()) {
MOZ_ALWAYS_SUCCEEDS(SetPrefersColorSchemeOverride(openerOverride));
}
}
}
bool BrowsingContext::HasOpener() const {
if (sBrowsingContexts) {
return sBrowsingContexts->Contains(GetOpenerId());
}
return false;
}
bool BrowsingContext::AncestorsAreCurrent() const {
const BrowsingContext* bc = this;
while (true) {
if (bc->IsDiscarded()) {
return false;
}
if (WindowContext* wc = bc->GetParentWindowContext()) {
if (!wc->IsCurrent() || wc->IsDiscarded()) {
return false;
}
bc = wc->GetBrowsingContext();
} else {
return true;
}
}
}
bool BrowsingContext::IsInBFCache() const {
if (mozilla::SessionHistoryInParent()) {
return mIsInBFCache;
}
return mParentWindow &&
mParentWindow->TopWindowContext()->GetWindowStateSaved();
}
Span<RefPtr<BrowsingContext>> BrowsingContext::Children() const {
if (WindowContext* current = mCurrentWindowContext) {
return current->Children();
}
return Span<RefPtr<BrowsingContext>>();
}
void BrowsingContext::GetChildren(
nsTArray<RefPtr<BrowsingContext>>& aChildren) {
aChildren.AppendElements(Children());
}
Span<RefPtr<BrowsingContext>> BrowsingContext::NonSyntheticChildren() const {
if (WindowContext* current = mCurrentWindowContext) {
return current->NonSyntheticChildren();
}
return Span<RefPtr<BrowsingContext>>();
}
BrowsingContext* BrowsingContext::NonSyntheticLightDOMChildAt(
uint32_t aIndex) const {
if (WindowContext* current = mCurrentWindowContext) {
return current->NonSyntheticLightDOMChildAt(aIndex);
}
return nullptr;
}
uint32_t BrowsingContext::NonSyntheticLightDOMChildrenCount() const {
if (WindowContext* current = mCurrentWindowContext) {
return current->NonSyntheticLightDOMChildrenCount();
}
return 0;
}
void BrowsingContext::GetWindowContexts(
nsTArray<RefPtr<WindowContext>>& aWindows) {
aWindows.AppendElements(mWindowContexts);
}
void BrowsingContext::RegisterWindowContext(WindowContext* aWindow) {
MOZ_ASSERT(!mWindowContexts.Contains(aWindow),
"WindowContext already registered!");
MOZ_ASSERT(aWindow->GetBrowsingContext() == this);
mWindowContexts.AppendElement(aWindow);
// If the newly registered WindowContext is for our current inner window ID,
// re-run the `DidSet` handler to re-establish the relationship.
if (aWindow->InnerWindowId() == GetCurrentInnerWindowId()) {
DidSet(FieldIndex<IDX_CurrentInnerWindowId>());
MOZ_DIAGNOSTIC_ASSERT(mCurrentWindowContext == aWindow);
}
}
void BrowsingContext::UnregisterWindowContext(WindowContext* aWindow) {
MOZ_ASSERT(mWindowContexts.Contains(aWindow),
"WindowContext not registered!");
mWindowContexts.RemoveElement(aWindow);
// If our currently active window was unregistered, clear our reference to it.
if (aWindow == mCurrentWindowContext) {
// Re-read our `CurrentInnerWindowId` value and use it to set
// `mCurrentWindowContext`. As `aWindow` is now unregistered and discarded,
// we won't find it, and the value will be cleared back to `nullptr`.
DidSet(FieldIndex<IDX_CurrentInnerWindowId>());
MOZ_DIAGNOSTIC_ASSERT(mCurrentWindowContext == nullptr);
}
}
void BrowsingContext::PreOrderWalkVoid(
const std::function<void(BrowsingContext*)>& aCallback) {
aCallback(this);
AutoTArray<RefPtr<BrowsingContext>, 8> children;
children.AppendElements(Children());
for (auto& child : children) {
child->PreOrderWalkVoid(aCallback);
}
}
BrowsingContext::WalkFlag BrowsingContext::PreOrderWalkFlag(
const std::function<WalkFlag(BrowsingContext*)>& aCallback) {
switch (aCallback(this)) {
case WalkFlag::Skip:
return WalkFlag::Next;
case WalkFlag::Stop:
return WalkFlag::Stop;
case WalkFlag::Next:
default:
break;
}
AutoTArray<RefPtr<BrowsingContext>, 8> children;
children.AppendElements(Children());
for (auto& child : children) {
switch (child->PreOrderWalkFlag(aCallback)) {
case WalkFlag::Stop:
return WalkFlag::Stop;
default:
break;
}
}
return WalkFlag::Next;
}
void BrowsingContext::PostOrderWalk(
const std::function<void(BrowsingContext*)>& aCallback) {
AutoTArray<RefPtr<BrowsingContext>, 8> children;
children.AppendElements(Children());
for (auto& child : children) {
child->PostOrderWalk(aCallback);
}
aCallback(this);
}
void BrowsingContext::GetAllBrowsingContextsInSubtree(
nsTArray<RefPtr<BrowsingContext>>& aBrowsingContexts) {
PreOrderWalk([&](BrowsingContext* aContext) {
aBrowsingContexts.AppendElement(aContext);
});
}
BrowsingContext* BrowsingContext::FindChildWithName(
const nsAString& aName, WindowGlobalChild& aRequestingWindow) {
if (aName.IsEmpty()) {
// You can't find a browsing context with the empty name.
return nullptr;
}
for (BrowsingContext* child : NonSyntheticChildren()) {
if (child->NameEquals(aName) && aRequestingWindow.CanNavigate(child) &&
child->IsTargetable()) {
return child;
}
}
return nullptr;
}
BrowsingContext* BrowsingContext::FindWithSpecialName(
const nsAString& aName, WindowGlobalChild& aRequestingWindow) {
// TODO(farre): Neither BrowsingContext nor nsDocShell checks if the
// browsing context pointed to by a special name is active. Should
// it be? See Bug 1527913.
if (aName.LowerCaseEqualsLiteral("_self")) {
return this;
}
if (aName.LowerCaseEqualsLiteral("_parent")) {
if (BrowsingContext* parent = GetParent()) {
return aRequestingWindow.CanNavigate(parent) ? parent : nullptr;
}
return this;
}
if (aName.LowerCaseEqualsLiteral("_top")) {
BrowsingContext* top = Top();
return aRequestingWindow.CanNavigate(top) ? top : nullptr;
}
return nullptr;
}
BrowsingContext* BrowsingContext::FindWithNameInSubtree(
const nsAString& aName, WindowGlobalChild* aRequestingWindow) {
MOZ_DIAGNOSTIC_ASSERT(!aName.IsEmpty());
if (NameEquals(aName) &&
(!aRequestingWindow || aRequestingWindow->CanNavigate(this)) &&
IsTargetable()) {
return this;
}
for (BrowsingContext* child : NonSyntheticChildren()) {
if (BrowsingContext* found =
child->FindWithNameInSubtree(aName, aRequestingWindow)) {
return found;
}
}
return nullptr;
}
bool BrowsingContext::IsSandboxedFrom(BrowsingContext* aTarget) {
// If no target then not sandboxed.
if (!aTarget) {
return false;
}
// We cannot be sandboxed from ourselves.
if (aTarget == this) {
return false;
}
// Default the sandbox flags to our flags, so that if we can't retrieve the
// active document, we will still enforce our own.
uint32_t sandboxFlags = GetSandboxFlags();
if (mDocShell) {
if (RefPtr<Document> doc = mDocShell->GetExtantDocument()) {
sandboxFlags = doc->GetSandboxFlags();
}
}
// If no flags, we are not sandboxed at all.
if (!sandboxFlags) {
return false;
}
// If aTarget has an ancestor, it is not top level.
if (RefPtr<BrowsingContext> ancestorOfTarget = aTarget->GetParent()) {
do {
// We are not sandboxed if we are an ancestor of target.
if (ancestorOfTarget == this) {
return false;
}
ancestorOfTarget = ancestorOfTarget->GetParent();
} while (ancestorOfTarget);
// Otherwise, we are sandboxed from aTarget.
return true;
}
// aTarget is top level, are we the "one permitted sandboxed
// navigator", i.e. did we open aTarget?
if (aTarget->GetOnePermittedSandboxedNavigatorId() == Id()) {
return false;
}
// If SANDBOXED_TOPLEVEL_NAVIGATION flag is not on, we are not sandboxed
// from our top.
if (!(sandboxFlags & SANDBOXED_TOPLEVEL_NAVIGATION) && aTarget == Top()) {
return false;
}
// If SANDBOXED_TOPLEVEL_NAVIGATION_USER_ACTIVATION flag is not on, we are not
// sandboxed from our top if we have user interaction. We assume there is a
// valid transient user gesture interaction if this check happens in the
// target process given that we have checked in the triggering process
// already.
if (!(sandboxFlags & SANDBOXED_TOPLEVEL_NAVIGATION_USER_ACTIVATION) &&
mCurrentWindowContext &&
(!mCurrentWindowContext->IsInProcess() ||
mCurrentWindowContext->HasValidTransientUserGestureActivation()) &&
aTarget == Top()) {
return false;
}
// Otherwise, we are sandboxed from aTarget.
return true;
}
RefPtr<SessionStorageManager> BrowsingContext::GetSessionStorageManager() {
RefPtr<SessionStorageManager>& manager = Top()->mSessionStorageManager;
if (!manager) {
manager = new SessionStorageManager(this);
}
return manager;
}
bool BrowsingContext::CrossOriginIsolated() {
MOZ_ASSERT(NS_IsMainThread());
return StaticPrefs::
dom_postMessage_sharedArrayBuffer_withCOOP_COEP_AtStartup() &&
Top()->GetOpenerPolicy() ==
nsILoadInfo::
OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP &&
XRE_IsContentProcess() &&
StringBeginsWith(ContentChild::GetSingleton()->GetRemoteType(),
WITH_COOP_COEP_REMOTE_TYPE_PREFIX);
}
void BrowsingContext::SetTriggeringAndInheritPrincipals(
nsIPrincipal* aTriggeringPrincipal, nsIPrincipal* aPrincipalToInherit,
uint64_t aLoadIdentifier) {
mTriggeringPrincipal = Some(
PrincipalWithLoadIdentifierTuple(aTriggeringPrincipal, aLoadIdentifier));
if (aPrincipalToInherit) {
mPrincipalToInherit = Some(
PrincipalWithLoadIdentifierTuple(aPrincipalToInherit, aLoadIdentifier));
}
}
std::tuple<nsCOMPtr<nsIPrincipal>, nsCOMPtr<nsIPrincipal>>
BrowsingContext::GetTriggeringAndInheritPrincipalsForCurrentLoad() {
nsCOMPtr<nsIPrincipal> triggeringPrincipal =
GetSavedPrincipal(mTriggeringPrincipal);
nsCOMPtr<nsIPrincipal> principalToInherit =
GetSavedPrincipal(mPrincipalToInherit);
return std::make_tuple(triggeringPrincipal, principalToInherit);
}
nsIPrincipal* BrowsingContext::GetSavedPrincipal(
Maybe<PrincipalWithLoadIdentifierTuple> aPrincipalTuple) {
if (aPrincipalTuple) {
nsCOMPtr<nsIPrincipal> principal;
uint64_t loadIdentifier;
std::tie(principal, loadIdentifier) = *aPrincipalTuple;
// We want to return a principal only if the load identifier for it
// matches the current one for this BC.
if (auto current = GetCurrentLoadIdentifier();
current && *current == loadIdentifier) {
return principal;
}
}
return nullptr;
}
BrowsingContext::~BrowsingContext() {
MOZ_DIAGNOSTIC_ASSERT(!mParentWindow ||
!mParentWindow->mChildren.Contains(this));
MOZ_DIAGNOSTIC_ASSERT(!mGroup || !mGroup->Toplevels().Contains(this));
mDeprioritizedLoadRunner.clear();
if (sBrowsingContexts) {
sBrowsingContexts->Remove(Id());
}
UnregisterBrowserId(this);
ClearCachedValuesOfLocations();
mLocations.clear();
}
/* static */
void BrowsingContext::DiscardFromContentParent(ContentParent* aCP) {
MOZ_ASSERT(XRE_IsParentProcess());
if (sBrowsingContexts) {
AutoTArray<RefPtr<BrowsingContext>, 8> toDiscard;
for (const auto& data : sBrowsingContexts->Values()) {
auto* bc = data->Canonical();
if (!bc->IsDiscarded() && bc->IsEmbeddedInProcess(aCP->ChildID())) {
toDiscard.AppendElement(bc);
}
}
for (BrowsingContext* bc : toDiscard) {
bc->Detach(/* aFromIPC */ true);
}
}
}
nsISupports* BrowsingContext::GetParentObject() const {
return xpc::NativeGlobal(xpc::PrivilegedJunkScope());
}
JSObject* BrowsingContext::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return BrowsingContext_Binding::Wrap(aCx, this, aGivenProto);
}
bool BrowsingContext::WriteStructuredClone(JSContext* aCx,
JSStructuredCloneWriter* aWriter,
StructuredCloneHolder* aHolder) {
MOZ_DIAGNOSTIC_ASSERT(mEverAttached);
return (JS_WriteUint32Pair(aWriter, SCTAG_DOM_BROWSING_CONTEXT, 0) &&
JS_WriteUint32Pair(aWriter, uint32_t(Id()), uint32_t(Id() >> 32)));
}
/* static */
JSObject* BrowsingContext::ReadStructuredClone(JSContext* aCx,
JSStructuredCloneReader* aReader,
StructuredCloneHolder* aHolder) {
uint32_t idLow = 0;
uint32_t idHigh = 0;
if (!JS_ReadUint32Pair(aReader, &idLow, &idHigh)) {
return nullptr;
}
uint64_t id = uint64_t(idHigh) << 32 | idLow;
// Note: Do this check after reading our ID data. Returning null will abort
// the decode operation anyway, but we should at least be as safe as possible.
if (NS_WARN_IF(!NS_IsMainThread())) {
MOZ_DIAGNOSTIC_CRASH(
"We shouldn't be trying to decode a BrowsingContext "
"on a background thread.");
return nullptr;
}
JS::Rooted<JS::Value> val(aCx, JS::NullValue());
// We'll get rooting hazard errors from the RefPtr destructor if it isn't
// destroyed before we try to return a raw JSObject*, so create it in its own
// scope.
if (RefPtr<BrowsingContext> context = Get(id)) {
if (!GetOrCreateDOMReflector(aCx, context, &val) || !val.isObject()) {
return nullptr;
}
}
return val.toObjectOrNull();
}
bool BrowsingContext::CanSetOriginAttributes() {
// A discarded BrowsingContext has already been destroyed, and cannot modify
// its OriginAttributes.
if (NS_WARN_IF(IsDiscarded())) {
return false;
}
// Before attaching is the safest time to set OriginAttributes, and the only
// allowed time for content BrowsingContexts.
if (!EverAttached()) {
return true;
}
// Attached content BrowsingContexts may have been synced to other processes.
if (NS_WARN_IF(IsContent())) {
MOZ_CRASH();
return false;
}
MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
// Cannot set OriginAttributes after we've created our child BrowsingContext.
if (NS_WARN_IF(!Children().IsEmpty())) {
return false;
}
// Only allow setting OriginAttributes if we have no associated document, or
// the document is still `about:blank`.
// TODO: Bug 1273058 - should have no document when setting origin attributes.
if (WindowGlobalParent* window = Canonical()->GetCurrentWindowGlobal()) {
if (nsIURI* uri = window->GetDocumentURI()) {
MOZ_ASSERT(NS_IsAboutBlank(uri));
return NS_IsAboutBlank(uri);
}
}
return true;
}
Nullable<WindowProxyHolder> BrowsingContext::GetAssociatedWindow() {
// nsILoadContext usually only returns same-process windows,
// so we intentionally return nullptr if this BC is out of
// process.
if (IsInProcess()) {
return WindowProxyHolder(this);
}
return nullptr;
}
Nullable<WindowProxyHolder> BrowsingContext::GetTopWindow() {
return Top()->GetAssociatedWindow();
}
Element* BrowsingContext::GetTopFrameElement() {
return Top()->GetEmbedderElement();
}
void BrowsingContext::SetUsePrivateBrowsing(bool aUsePrivateBrowsing,
ErrorResult& aError) {
nsresult rv = SetUsePrivateBrowsing(aUsePrivateBrowsing);
if (NS_FAILED(rv)) {
aError.Throw(rv);
}
}
void BrowsingContext::SetUseTrackingProtectionWebIDL(
bool aUseTrackingProtection, ErrorResult& aRv) {
SetForceEnableTrackingProtection(aUseTrackingProtection, aRv);
}
void BrowsingContext::GetOriginAttributes(JSContext* aCx,
JS::MutableHandle<JS::Value> aVal,
ErrorResult& aError) {
AssertOriginAttributesMatchPrivateBrowsing();
if (!ToJSValue(aCx, mOriginAttributes, aVal)) {
aError.NoteJSContextException(aCx);
}
}
NS_IMETHODIMP BrowsingContext::GetAssociatedWindow(
mozIDOMWindowProxy** aAssociatedWindow) {
nsCOMPtr<mozIDOMWindowProxy> win = GetDOMWindow();
win.forget(aAssociatedWindow);
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::GetTopWindow(mozIDOMWindowProxy** aTopWindow) {
return Top()->GetAssociatedWindow(aTopWindow);
}
NS_IMETHODIMP BrowsingContext::GetTopFrameElement(Element** aTopFrameElement) {
RefPtr<Element> topFrameElement = GetTopFrameElement();
topFrameElement.forget(aTopFrameElement);
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::GetIsContent(bool* aIsContent) {
*aIsContent = IsContent();
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::GetUsePrivateBrowsing(
bool* aUsePrivateBrowsing) {
*aUsePrivateBrowsing = mPrivateBrowsingId > 0;
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::SetUsePrivateBrowsing(bool aUsePrivateBrowsing) {
if (!CanSetOriginAttributes()) {
bool changed = aUsePrivateBrowsing != (mPrivateBrowsingId > 0);
if (changed) {
NS_WARNING("SetUsePrivateBrowsing when !CanSetOriginAttributes()");
}
return changed ? NS_ERROR_FAILURE : NS_OK;
}
return SetPrivateBrowsing(aUsePrivateBrowsing);
}
NS_IMETHODIMP BrowsingContext::SetPrivateBrowsing(bool aPrivateBrowsing) {
if (!CanSetOriginAttributes()) {
NS_WARNING("Attempt to set PrivateBrowsing when !CanSetOriginAttributes");
return NS_ERROR_FAILURE;
}
bool changed = aPrivateBrowsing != (mPrivateBrowsingId > 0);
if (changed) {
mPrivateBrowsingId = aPrivateBrowsing ? 1 : 0;
if (IsContent()) {
mOriginAttributes.SyncAttributesWithPrivateBrowsing(aPrivateBrowsing);
}
if (XRE_IsParentProcess()) {
Canonical()->AdjustPrivateBrowsingCount(aPrivateBrowsing);
}
}
AssertOriginAttributesMatchPrivateBrowsing();
if (changed && mDocShell) {
nsDocShell::Cast(mDocShell)->NotifyPrivateBrowsingChanged();
}
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::GetUseRemoteTabs(bool* aUseRemoteTabs) {
*aUseRemoteTabs = mUseRemoteTabs;
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::SetRemoteTabs(bool aUseRemoteTabs) {
if (!CanSetOriginAttributes()) {
NS_WARNING("Attempt to set RemoteTabs when !CanSetOriginAttributes");
return NS_ERROR_FAILURE;
}
if (aUseRemoteTabs && !gIPCEnabledAnnotation) {
gIPCEnabledAnnotation = true;
}
// Don't allow non-remote tabs with remote subframes.
if (NS_WARN_IF(!aUseRemoteTabs && mUseRemoteSubframes)) {
return NS_ERROR_UNEXPECTED;
}
mUseRemoteTabs = aUseRemoteTabs;
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::GetUseRemoteSubframes(
bool* aUseRemoteSubframes) {
*aUseRemoteSubframes = mUseRemoteSubframes;
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::SetRemoteSubframes(bool aUseRemoteSubframes) {
if (!CanSetOriginAttributes()) {
NS_WARNING("Attempt to set RemoteSubframes when !CanSetOriginAttributes");
return NS_ERROR_FAILURE;
}
if (aUseRemoteSubframes && !gFissionEnabledAnnotation) {
gFissionEnabledAnnotation = true;
}
// Don't allow non-remote tabs with remote subframes.
if (NS_WARN_IF(aUseRemoteSubframes && !mUseRemoteTabs)) {
return NS_ERROR_UNEXPECTED;
}
mUseRemoteSubframes = aUseRemoteSubframes;
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::GetUseTrackingProtection(
bool* aUseTrackingProtection) {
*aUseTrackingProtection = false;
if (GetForceEnableTrackingProtection() ||
StaticPrefs::privacy_trackingprotection_enabled() ||
(UsePrivateBrowsing() &&
StaticPrefs::privacy_trackingprotection_pbmode_enabled())) {
*aUseTrackingProtection = true;
return NS_OK;
}
if (GetParent()) {
return GetParent()->GetUseTrackingProtection(aUseTrackingProtection);
}
return NS_OK;
}
NS_IMETHODIMP BrowsingContext::SetUseTrackingProtection(
bool aUseTrackingProtection) {
return SetForceEnableTrackingProtection(aUseTrackingProtection);
}
NS_IMETHODIMP BrowsingContext::GetScriptableOriginAttributes(
JSContext* aCx, JS::MutableHandle<JS::Value> aVal) {
AssertOriginAttributesMatchPrivateBrowsing();
bool ok = ToJSValue(aCx, mOriginAttributes, aVal);
NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);
return NS_OK;
}
NS_IMETHODIMP_(void)
BrowsingContext::GetOriginAttributes(OriginAttributes& aAttrs) {
aAttrs = mOriginAttributes;
AssertOriginAttributesMatchPrivateBrowsing();
}
nsresult BrowsingContext::SetOriginAttributes(const OriginAttributes& aAttrs) {
if (!CanSetOriginAttributes()) {
NS_WARNING("Attempt to set OriginAttributes when !CanSetOriginAttributes");
return NS_ERROR_FAILURE;
}
AssertOriginAttributesMatchPrivateBrowsing();
mOriginAttributes = aAttrs;
bool isPrivate = mOriginAttributes.mPrivateBrowsingId !=
nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID;
// Chrome Browsing Context can not contain OriginAttributes.mPrivateBrowsingId
if (IsChrome() && isPrivate) {
mOriginAttributes.mPrivateBrowsingId =
nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID;
}
SetPrivateBrowsing(isPrivate);
AssertOriginAttributesMatchPrivateBrowsing();
return NS_OK;
}
void BrowsingContext::AssertOriginAttributesMatchPrivateBrowsing() {
// Chrome browsing contexts must not have a private browsing OriginAttribute
// Content browsing contexts must maintain the equality:
// mOriginAttributes.mPrivateBrowsingId == mPrivateBrowsingId
if (IsChrome()) {
MOZ_DIAGNOSTIC_ASSERT(mOriginAttributes.mPrivateBrowsingId == 0);
} else {
MOZ_DIAGNOSTIC_ASSERT(mOriginAttributes.mPrivateBrowsingId ==
mPrivateBrowsingId);
}
}
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(BrowsingContext)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsILoadContext)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_CLASS(BrowsingContext)
NS_IMPL_CYCLE_COLLECTING_ADDREF(BrowsingContext)
NS_IMPL_CYCLE_COLLECTING_RELEASE(BrowsingContext)
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(BrowsingContext)
NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(BrowsingContext)
if (sBrowsingContexts) {
sBrowsingContexts->Remove(tmp->Id());
}
UnregisterBrowserId(tmp);
if (tmp->GetIsPopupSpam()) {
PopupBlocker::UnregisterOpenPopupSpam();
// NOTE: Doesn't use SetIsPopupSpam, as it will be set all processes
// automatically.
tmp->mFields.SetWithoutSyncing<IDX_IsPopupSpam>(false);
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(
mDocShell, mParentWindow, mGroup, mEmbedderElement, mWindowContexts,
mCurrentWindowContext, mSessionStorageManager, mChildSessionHistory)
NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(BrowsingContext)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(
mDocShell, mParentWindow, mGroup, mEmbedderElement, mWindowContexts,
mCurrentWindowContext, mSessionStorageManager, mChildSessionHistory)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
static bool IsCertainlyAliveForCC(BrowsingContext* aContext) {
return aContext->HasKnownLiveWrapper() ||
(AppShutdown::GetCurrentShutdownPhase() ==
ShutdownPhase::NotInShutdown &&
aContext->EverAttached() && !aContext->IsDiscarded());
}
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(BrowsingContext)
if (IsCertainlyAliveForCC(tmp)) {
if (tmp->PreservingWrapper()) {
tmp->MarkWrapperLive();
}
return true;
}
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(BrowsingContext)
return IsCertainlyAliveForCC(tmp) && tmp->HasNothingToTrace(tmp);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(BrowsingContext)
return IsCertainlyAliveForCC(tmp);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
class RemoteLocationProxy
: public RemoteObjectProxy<BrowsingContext::LocationProxy,
Location_Binding::sCrossOriginProperties> {
public:
typedef RemoteObjectProxy Base;
constexpr RemoteLocationProxy()
: RemoteObjectProxy(prototypes::id::Location) {}
void NoteChildren(JSObject* aProxy,
nsCycleCollectionTraversalCallback& aCb) const override {
auto location =
static_cast<BrowsingContext::LocationProxy*>(GetNative(aProxy));
CycleCollectionNoteChild(aCb, location->GetBrowsingContext(),
"JS::GetPrivate(obj)->GetBrowsingContext()");
}
};
static const RemoteLocationProxy sSingleton;
// Give RemoteLocationProxy 2 reserved slots, like the other wrappers,
// so JSObject::swap can swap it with CrossCompartmentWrappers without requiring
// malloc.
template <>
const JSClass RemoteLocationProxy::Base::sClass =
PROXY_CLASS_DEF("Proxy", JSCLASS_HAS_RESERVED_SLOTS(2));
void BrowsingContext::Location(JSContext* aCx,
JS::MutableHandle<JSObject*> aLocation,
ErrorResult& aError) {
aError.MightThrowJSException();
sSingleton.GetProxyObject(aCx, &mLocation, /* aTransplantTo = */ nullptr,
aLocation);
if (!aLocation) {
aError.StealExceptionFromJSContext(aCx);
}
}
bool BrowsingContext::RemoveRootFromBFCacheSync() {
if (WindowContext* wc = GetParentWindowContext()) {
if (RefPtr<Document> doc = wc->TopWindowContext()->GetDocument()) {
return doc->RemoveFromBFCacheSync();
}
}
return false;
}
nsresult BrowsingContext::CheckSandboxFlags(nsDocShellLoadState* aLoadState) {
const auto& sourceBC = aLoadState->SourceBrowsingContext();
if (sourceBC.IsNull()) {
return NS_OK;
}
// We might be called after the source BC has been discarded, but before we've
// destroyed our in-process instance of the BrowsingContext object in some
// situations (e.g. after creating a new pop-up with window.open while the
// window is being closed). In these situations we want to still perform the
// sandboxing check against our in-process copy. If we've forgotten about the
// context already, assume it is sanboxed. (bug 1643450)
BrowsingContext* bc = sourceBC.GetMaybeDiscarded();
if (!bc || bc->IsSandboxedFrom(this)) {
return NS_ERROR_DOM_SECURITY_ERR;
}
return NS_OK;
}
nsresult BrowsingContext::CheckFramebusting(nsDocShellLoadState* aLoadState) {
if (!StaticPrefs::dom_security_framebusting_intervention_enabled()) {
return NS_OK;
}
// Only applies to top-level navigations.
if (!IsTop()) {
return NS_OK;
}
if (aLoadState->HasValidUserGestureActivation()) {
return NS_OK;
}
const auto& sourceBC = aLoadState->SourceBrowsingContext();
if (sourceBC.IsNull()) {
return NS_OK;
}
if (BrowsingContext* bc = sourceBC.GetMaybeDiscarded()) {
if (bc->IsFramebustingAllowed(this)) {
return NS_OK;
}
if (bc->GetDOMWindow()) {
nsGlobalWindowOuter::Cast(bc->GetDOMWindow())
->FireRedirectBlockedEvent(aLoadState->URI());
}
nsAutoCString frameURL;
if (bc->GetDocument() &&
NS_SUCCEEDED(
bc->GetDocument()->GetPrincipal()->GetAsciiSpec(frameURL))) {
nsContentUtils::ReportToConsoleNonLocalized(
NS_ConvertUTF8toUTF16(nsPrintfCString(
R"(Attempting to navigate the top-level browsing context from )"
R"(frame with url "%s" which is neither same-origin nor has )"
R"(the required user interaction.)",
frameURL.get())),
nsIScriptError::errorFlag, "DOM"_ns, bc->GetDocument());
}
}
return NS_ERROR_DOM_SECURITY_ERR;
}
bool BrowsingContext::IsFramebustingAllowed(BrowsingContext* aTarget) {
MOZ_ASSERT(aTarget->IsTop());
if (aTarget->BrowserId() == BrowserId()) {
return IsFramebustingAllowedInner() || IsPopupAllowed();
}
// We should be able to safely assume that the SOP has our back here
// already. How else would this BrowsingContext have a reference?
return true;
}
bool BrowsingContext::IsFramebustingAllowedInner() {
if (IsInProcess() && SameOriginWithTop()) {
return true;
}
// We get the sandbox flags from the load info since the CSP header
// hasn't yet been processed at that time. The CSP sandbox directive makes
// it possible for a document to grant itself "allow-top-navigation"
// permissions by sending the appropiate header and we don't like that.
Document* doc;
nsIChannel* channel;
if ((doc = GetExtantDocument()) && (channel = doc->GetChannel())) {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
uint32_t sandboxFlags = loadInfo->GetSandboxFlags();
if (sandboxFlags && !(sandboxFlags & SANDBOXED_TOPLEVEL_NAVIGATION)) {
BrowsingContext* parent = GetParent();
return !parent || parent->IsFramebustingAllowedInner();
}
}
return false;
}
nsresult BrowsingContext::LoadURI(nsDocShellLoadState* aLoadState,
bool aSetNavigating) {
// Per spec, most load attempts are silently ignored when a BrowsingContext is
// null (which in our code corresponds to discarded), so we simply fail
// silently in those cases. Regardless, we cannot trigger loads in/from
// discarded BrowsingContexts via IPC, so we need to abort in any case.
if (IsDiscarded()) {
return NS_OK;
}
MOZ_DIAGNOSTIC_ASSERT(aLoadState->TargetBrowsingContext().IsNull(),
"Targeting occurs in InternalLoad");
aLoadState->AssertProcessCouldTriggerLoadIfSystem();
// When this tab sets these load flags, we disable or force TRR for the
// browsing context ensuring subsequent navigations will keep the same
// TRR mode.
if (aLoadState->HasLoadFlags(nsIWebNavigation::LOAD_FLAGS_DISABLE_TRR)) {
(void)SetDefaultLoadFlags(GetDefaultLoadFlags() |
nsIRequest::LOAD_TRR_DISABLED_MODE);
} else if (aLoadState->HasLoadFlags(nsIWebNavigation::LOAD_FLAGS_FORCE_TRR)) {
(void)SetDefaultLoadFlags(GetDefaultLoadFlags() |
nsIRequest::LOAD_TRR_ONLY_MODE);
}
if (mDocShell) {
nsCOMPtr<nsIDocShell> docShell = mDocShell;
return docShell->LoadURI(aLoadState, aSetNavigating);
}
// Note: We do this check both here and in `nsDocShell::InternalLoad`, since
// document-specific sandbox flags are only available in the process
// triggering the load, and we don't want the target process to have to trust
// the triggering process to do the appropriate checks for the
// BrowsingContext's sandbox flags.
MOZ_TRY(CheckSandboxFlags(aLoadState));
SetTriggeringAndInheritPrincipals(aLoadState->TriggeringPrincipal(),
aLoadState->PrincipalToInherit(),
aLoadState->GetLoadIdentifier());
const auto& sourceBC = aLoadState->SourceBrowsingContext();
if (aLoadState->URI()->SchemeIs("javascript")) {
if (!XRE_IsParentProcess()) {
// Web content should only be able to load javascript: URIs into documents
// whose principals the caller principal subsumes, which by definition
// excludes any document in a cross-process BrowsingContext.
return NS_ERROR_DOM_BAD_CROSS_ORIGIN_URI;
}
MOZ_DIAGNOSTIC_ASSERT(!sourceBC,
"Should never see a cross-process javascript: load "
"triggered from content");
}
// Note: We do this check both here and in `nsDocShell::InternalLoad`.
// Same reason as for the sandbox flags.
MOZ_TRY(CheckFramebusting(aLoadState));
MOZ_DIAGNOSTIC_ASSERT(!sourceBC || sourceBC->Group() == Group());
if (sourceBC && sourceBC->IsInProcess()) {
nsCOMPtr<nsPIDOMWindowOuter> win(sourceBC->GetDOMWindow());
if (WindowGlobalChild* wgc =
win->GetCurrentInnerWindow()->GetWindowGlobalChild()) {
if (!wgc->CanNavigate(this)) {
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
wgc->SendLoadURI(this, mozilla::WrapNotNull(aLoadState), aSetNavigating);
}
} else if (XRE_IsParentProcess()) {
if (Canonical()->LoadInParent(aLoadState, aSetNavigating)) {
return NS_OK;
}
if (ContentParent* cp = Canonical()->GetContentParent()) {
// Attempt to initiate this load immediately in the parent, if it succeeds
// it'll return a unique identifier so that we can find it later.
uint64_t loadIdentifier = 0;
if (Canonical()->AttemptSpeculativeLoadInParent(aLoadState)) {
MOZ_DIAGNOSTIC_ASSERT(GetCurrentLoadIdentifier().isSome());
loadIdentifier = GetCurrentLoadIdentifier().value();
aLoadState->SetChannelInitialized(true);
}
cp->TransmitBlobDataIfBlobURL(aLoadState->URI());
#ifdef ANDROID
// Generate a unique android load identifier for this url load
// Used to map back to the app link launch type in
// ContentParent::RecordAndroidAppLinkTelemetry() so we can avoid
// sending the app link launch type to the content process
uint64_t androidLoadIdentifier = nsContentUtils::GenerateTabId();
MOZ_ALWAYS_SUCCEEDS(
SetAndroidAppLinkLoadIdentifier(Some(androidLoadIdentifier)));
uint32_t appLinkLaunchType = aLoadState->GetAppLinkLaunchType();
cp->SetAndroidAppLinkLaunchType(androidLoadIdentifier, appLinkLaunchType);
// Record timing for cold app link launches
constexpr uint32_t APPLINK_COLD = 1;
if (appLinkLaunchType == APPLINK_COLD) {
const TimeStamp loadUriTime = TimeStamp::Now();
// Process creation to load URI timing
const TimeStamp processCreationTime = TimeStamp::ProcessCreation();
if (!processCreationTime.IsNull()) {
const TimeDuration delta = loadUriTime - processCreationTime;
mozilla::glean::perf::cold_applink_process_launch_to_load_uri
.AccumulateRawDuration(delta);
PROFILER_MARKER("Cold App Link Process Creation to Load URI", NETWORK,
MarkerOptions(MarkerTiming::Interval(
processCreationTime, loadUriTime)),
Tracing, "AppLink");
}
// StartupTimeline::MAIN to load URI timing
const TimeStamp mainTime = StartupTimeline::Get(StartupTimeline::MAIN);
if (!mainTime.IsNull()) {
const TimeDuration mainDelta = loadUriTime - mainTime;
mozilla::glean::perf::cold_applink_main_to_load_uri
.AccumulateRawDuration(mainDelta);
PROFILER_MARKER(
"Cold App Link Main to Load URI", NETWORK,
MarkerOptions(MarkerTiming::Interval(mainTime, loadUriTime)),
Tracing, "AppLink");
}
}
PROFILER_MARKER_FMT("BrowsingContext::LoadURI", NETWORK, {},
"android appLinkLaunchType {} URL {}",
appLinkLaunchType,
aLoadState->URI()->GetSpecOrDefault().get());
#endif
// Setup a confirmation callback once the content process receives this
// load. Normally we'd expect a PDocumentChannel actor to have been
// created to claim the load identifier by that time. If not, then it
// won't be coming, so make sure we clean up and deregister.
cp->SendLoadURI(this, mozilla::WrapNotNull(aLoadState), aSetNavigating)
->Then(GetMainThreadSerialEventTarget(), __func__,
[loadIdentifier](
const PContentParent::LoadURIPromise::ResolveOrRejectValue&
aValue) {
if (loadIdentifier) {
net::DocumentLoadListener::CleanupParentLoadAttempt(
loadIdentifier);
}
});
}
} else {
MOZ_DIAGNOSTIC_ASSERT(sourceBC);
if (!sourceBC) {
return NS_ERROR_UNEXPECTED;
}
// If we're in a content process and the source BC is no longer in-process,
// just fail silently.
}
return NS_OK;
}
nsresult BrowsingContext::InternalLoad(nsDocShellLoadState* aLoadState) {
if (IsDiscarded()) {
return NS_OK;
}
SetTriggeringAndInheritPrincipals(aLoadState->TriggeringPrincipal(),
aLoadState->PrincipalToInherit(),
aLoadState->GetLoadIdentifier());
MOZ_DIAGNOSTIC_ASSERT(aLoadState->Target().IsEmpty(),
"should already have retargeted");
MOZ_DIAGNOSTIC_ASSERT(!aLoadState->TargetBrowsingContext().IsNull(),
"should have target bc set");
MOZ_DIAGNOSTIC_ASSERT(aLoadState->TargetBrowsingContext() == this,
"must be targeting this BrowsingContext");
aLoadState->AssertProcessCouldTriggerLoadIfSystem();
if (mDocShell) {
RefPtr<nsDocShell> docShell = nsDocShell::Cast(mDocShell);
return docShell->InternalLoad(aLoadState);
}
// Note: We do this check both here and in `nsDocShell::InternalLoad`, since
// document-specific sandbox flags are only available in the process
// triggering the load, and we don't want the target process to have to trust
// the triggering process to do the appropriate checks for the
// BrowsingContext's sandbox flags.
MOZ_TRY(CheckSandboxFlags(aLoadState));
const auto& sourceBC = aLoadState->SourceBrowsingContext();
if (aLoadState->URI()->SchemeIs("javascript")) {
if (!XRE_IsParentProcess()) {
// Web content should only be able to load javascript: URIs into documents
// whose principals the caller principal subsumes, which by definition
// excludes any document in a cross-process BrowsingContext.
return NS_ERROR_DOM_BAD_CROSS_ORIGIN_URI;
}
MOZ_DIAGNOSTIC_ASSERT(!sourceBC,
"Should never see a cross-process javascript: load "
"triggered from content");
}
// Note: We do this check both here and in `nsDocShell::InternalLoad`.
// Same reason as for the sandbox flags.
MOZ_TRY(CheckFramebusting(aLoadState));
if (XRE_IsParentProcess()) {
ContentParent* cp = Canonical()->GetContentParent();
if (!cp || !cp->CanSend()) {
return NS_ERROR_FAILURE;
}
MOZ_ALWAYS_SUCCEEDS(
SetCurrentLoadIdentifier(Some(aLoadState->GetLoadIdentifier())));
(void)cp->SendInternalLoad(mozilla::WrapNotNull(aLoadState));
} else {
MOZ_DIAGNOSTIC_ASSERT(sourceBC);
MOZ_DIAGNOSTIC_ASSERT(sourceBC->Group() == Group());
nsCOMPtr<nsPIDOMWindowOuter> win(sourceBC->GetDOMWindow());
WindowGlobalChild* wgc =
win->GetCurrentInnerWindow()->GetWindowGlobalChild();
if (!wgc || !wgc->CanSend()) {
return NS_ERROR_FAILURE;
}
if (!wgc->CanNavigate(this)) {
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
MOZ_ALWAYS_SUCCEEDS(
SetCurrentLoadIdentifier(Some(aLoadState->GetLoadIdentifier())));
wgc->SendInternalLoad(mozilla::WrapNotNull(aLoadState));
}
return NS_OK;
}
already_AddRefed<nsDocShellLoadState>
BrowsingContext::CheckURLAndCreateLoadState(nsIURI* aURI,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aRv) {
nsCOMPtr<nsIPrincipal> triggeringPrincipal;
nsCOMPtr<nsIURI> sourceURI;
ReferrerPolicy referrerPolicy = ReferrerPolicy::_empty;
nsCOMPtr<nsIReferrerInfo> referrerInfo;
// Get security manager.
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
if (NS_WARN_IF(!ssm)) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
// Check to see if URI is allowed. We're not going to worry about a
// window ID here because it's not 100% clear which window's id we
// would want, and we're throwing a content-visible exception
// anyway.
nsresult rv = ssm->CheckLoadURIWithPrincipal(
&aSubjectPrincipal, aURI, nsIScriptSecurityManager::STANDARD, 0);
if (NS_WARN_IF(NS_FAILED(rv))) {
nsAutoCString spec;
aURI->GetSpec(spec);
aRv.ThrowTypeError<MSG_URL_NOT_LOADABLE>(spec);
return nullptr;
}
// Make the load's referrer reflect changes to the document's URI caused by
// push/replaceState, if possible. First, get the document corresponding to
// fp. If the document's original URI (i.e. its URI before
// push/replaceState) matches the principal's URI, use the document's
// current URI as the referrer. If they don't match, use the principal's
// URI.
//
// The triggering principal for this load should be the principal of the
// incumbent document (which matches where the referrer information is
// coming from) when there is an incumbent document, and the subject
// principal otherwise. Note that the URI in the triggering principal
// may not match the referrer URI in various cases, notably including
// the cases when the incumbent document's document URI was modified
// after the document was loaded.
nsCOMPtr<nsPIDOMWindowInner> incumbent =
do_QueryInterface(mozilla::dom::GetIncumbentGlobal());
nsCOMPtr<Document> doc = incumbent ? incumbent->GetDoc() : nullptr;
// Create load info
RefPtr<nsDocShellLoadState> loadState = new nsDocShellLoadState(aURI);
if (!doc) {
// No document; just use our subject principal as the triggering principal.
loadState->SetTriggeringPrincipal(&aSubjectPrincipal);
return loadState.forget();
}
nsCOMPtr<nsIURI> docOriginalURI, docCurrentURI, principalURI;
docOriginalURI = doc->GetOriginalURI();
docCurrentURI = doc->GetDocumentURI();
nsCOMPtr<nsIPrincipal> principal = doc->NodePrincipal();
triggeringPrincipal = doc->NodePrincipal();
referrerPolicy = doc->GetReferrerPolicy();
bool urisEqual = false;
if (docOriginalURI && docCurrentURI && principal) {
principal->EqualsURI(docOriginalURI, &urisEqual);
}
if (urisEqual) {
referrerInfo = new ReferrerInfo(docCurrentURI, referrerPolicy);
} else {
principal->CreateReferrerInfo(referrerPolicy, getter_AddRefs(referrerInfo));
}
loadState->SetTriggeringPrincipal(triggeringPrincipal);
loadState->SetTriggeringSandboxFlags(doc->GetSandboxFlags());
loadState->SetPolicyContainer(doc->GetPolicyContainer());
if (referrerInfo) {
loadState->SetReferrerInfo(referrerInfo);
}
loadState->SetHasValidUserGestureActivation(
doc->HasValidTransientUserGestureActivation());
loadState->SetTextDirectiveUserActivation(
doc->ConsumeTextDirectiveUserActivation() ||
loadState->HasValidUserGestureActivation());
loadState->SetTriggeringWindowId(doc->InnerWindowID());
loadState->SetTriggeringStorageAccess(doc->UsingStorageAccess());
loadState->SetTriggeringClassificationFlags(doc->GetScriptTrackingFlags());
return loadState.forget();
}
// https://html.spec.whatwg.org/#navigate
// In its current state, this method is not closely following the spec.
// https://bugzil.la/1974717 tracks the work to align this method with the spec.
void BrowsingContext::Navigate(
nsIURI* aURI, nsIPrincipal& aSubjectPrincipal, ErrorResult& aRv,
NavigationHistoryBehavior aHistoryHandling,
bool aNeedsCompletelyLoadedDocument,
nsIStructuredCloneContainer* aNavigationAPIState,
dom::NavigationAPIMethodTracker* aNavigationAPIMethodTracker) {
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Debug, "Navigate to {} as {}", *aURI,
aHistoryHandling);
CallerType callerType = aSubjectPrincipal.IsSystemPrincipal()
? CallerType::System
: CallerType::NonSystem;
nsresult rv = CheckNavigationRateLimit(callerType);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return;
}
RefPtr<nsDocShellLoadState> loadState =
CheckURLAndCreateLoadState(aURI, aSubjectPrincipal, aRv);
if (aRv.Failed()) {
return;
}
if (mozilla::SessionHistoryInParent()) {
loadState->SetNeedsCompletelyLoadedDocument(aNeedsCompletelyLoadedDocument);
loadState->SetHistoryBehavior(aHistoryHandling);
}
if (aHistoryHandling == NavigationHistoryBehavior::Replace) {
loadState->SetLoadType(LOAD_STOP_CONTENT_AND_REPLACE);
} else {
loadState->SetLoadType(LOAD_STOP_CONTENT);
}
// Get the incumbent script's browsing context to set as source.
nsCOMPtr<nsPIDOMWindowInner> sourceWindow =
nsContentUtils::IncumbentInnerWindow();
if (sourceWindow) {
WindowContext* context = sourceWindow->GetWindowContext();
loadState->SetSourceBrowsingContext(sourceWindow->GetBrowsingContext());
loadState->SetHasValidUserGestureActivation(
context && context->HasValidTransientUserGestureActivation());
}
loadState->SetLoadFlags(nsIWebNavigation::LOAD_FLAGS_NONE);
loadState->SetFirstParty(true);
loadState->SetNavigationAPIState(aNavigationAPIState);
loadState->SetNavigationAPIMethodTracker(aNavigationAPIMethodTracker);
rv = LoadURI(loadState);
if (NS_WARN_IF(NS_FAILED(rv))) {
if (rv == NS_ERROR_DOM_BAD_CROSS_ORIGIN_URI &&
loadState->URI()->SchemeIs("javascript")) {
// Per spec[1], attempting to load a javascript: URI into a cross-origin
// BrowsingContext is a no-op, and should not raise an exception.
// Technically, Location setters run with exceptions enabled should only
// throw an exception[2] when the caller is not allowed to navigate[3] the
// target browsing context due to sandboxing flags or not being
// closely-related enough, though in practice we currently throw for other
// reasons as well.
//
// [1]:
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#javascript-protocol
// [2]:
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
// [3]:
// https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate
return;
}
aRv.Throw(rv);
return;
}
Document* doc = GetDocument();
if (doc && nsContentUtils::IsExternalProtocol(aURI)) {
doc->EnsureNotEnteringAndExitFullscreen();
}
}
void BrowsingContext::DisplayLoadError(const nsAString& aURI) {
MOZ_LOG(GetLog(), LogLevel::Debug, ("DisplayLoadError"));
MOZ_DIAGNOSTIC_ASSERT(!IsDiscarded());
MOZ_DIAGNOSTIC_ASSERT(mDocShell || XRE_IsParentProcess());
if (mDocShell) {
bool didDisplayLoadError = false;
nsCOMPtr<nsIDocShell> docShell = mDocShell;
docShell->DisplayLoadError(NS_ERROR_MALFORMED_URI, nullptr,
PromiseFlatString(aURI).get(), nullptr,
&didDisplayLoadError);
} else {
if (ContentParent* cp = Canonical()->GetContentParent()) {
(void)cp->SendDisplayLoadError(this, PromiseFlatString(aURI));
}
}
}
WindowProxyHolder BrowsingContext::Window() {
return WindowProxyHolder(Self());
}
WindowProxyHolder BrowsingContext::GetFrames(ErrorResult& aError) {
return Window();
}
void BrowsingContext::Close(CallerType aCallerType, ErrorResult& aError) {
if (mIsDiscarded) {
return;
}
if (IsSubframe()) {
// .close() on frames is a no-op.
return;
}
if (GetDOMWindow()) {
nsGlobalWindowOuter::Cast(GetDOMWindow())
->CloseOuter(aCallerType == CallerType::System);
return;
}
// This is a bit of a hack for webcompat. Content needs to see an updated
// |window.closed| value as early as possible, so we set this before we
// actually send the DOMWindowClose event, which happens in the process where
// the document for this browsing context is loaded.
MOZ_ALWAYS_SUCCEEDS(SetClosed(true));
if (ContentChild* cc = ContentChild::GetSingleton()) {
cc->SendWindowClose(this, aCallerType == CallerType::System);
} else if (ContentParent* cp = Canonical()->GetContentParent()) {
(void)cp->SendWindowClose(this, aCallerType == CallerType::System);
}
}
template <typename FuncT>
inline bool ApplyToDocumentsForPopup(Document* doc, FuncT func) {
// HACK: Some pages using bogus library + UA sniffing call window.open()
// from a blank iframe, only on Firefox, see bug 1685056.
//
// This is a hack-around to preserve behavior in that particular and
// specific case, by consuming activation on the parent document, so we
// don't care about the InProcessParent bits not being fission-safe or what
// not.
if (func(doc)) {
return true;
}
if (!doc->IsInitialDocument()) {
return false;
}
Document* parentDoc = doc->GetInProcessParentDocument();
if (!parentDoc || !parentDoc->NodePrincipal()->Equals(doc->NodePrincipal())) {
return false;
}
return func(parentDoc);
}
PopupBlocker::PopupControlState BrowsingContext::RevisePopupAbuseLevel(
PopupBlocker::PopupControlState aControl) {
if (!IsContent()) {
return PopupBlocker::openAllowed;
}
RefPtr<Document> doc = GetExtantDocument();
PopupBlocker::PopupControlState abuse = aControl;
switch (abuse) {
case PopupBlocker::openControlled:
case PopupBlocker::openOverridden:
if (IsPopupAllowed()) {
// Go down one state enum step:
// openControlled (1) -> openAllowed (0)
// openOverridden (4) -> openAbused (3)
abuse = PopupBlocker::PopupControlState(abuse - 1);
}
break;
case PopupBlocker::openAbused:
if (IsPopupAllowed() ||
(doc && doc->HasValidTransientUserGestureActivation())) {
// Always go down to openControlled:
// openAbused (3) -> openControlled (1), skip openBlocked (2)
abuse = PopupBlocker::openControlled;
}
break;
case PopupBlocker::openAllowed:
break;
case PopupBlocker::openBlocked:
if (IsPopupAllowed() ||
(doc && doc->HasValidTransientUserGestureActivation())) {
// Go down one state enum step:
// openBlocked (2) -> openControlled (1)
abuse = PopupBlocker::openControlled;
}
break;
default:
NS_WARNING("Strange PopupControlState!");
}
// limit the number of simultaneously open popups
if (abuse == PopupBlocker::openAbused || abuse == PopupBlocker::openBlocked ||
abuse == PopupBlocker::openControlled) {
int32_t popupMax = StaticPrefs::dom_popup_maximum();
if (popupMax >= 0 &&
PopupBlocker::GetOpenPopupSpamCount() >= (uint32_t)popupMax) {
abuse = PopupBlocker::openOverridden;
}
}
// If we're currently in-process, attempt to consume transient user gesture
// activations.
if (doc) {
auto ConsumeTransientUserActivationForMultiplePopupBlocking =
[&]() -> bool {
return ApplyToDocumentsForPopup(doc, [](Document* doc) {
return doc->ConsumeTransientUserGestureActivation();
});
};
// If this popup is allowed, let's block any other for this event, forcing
// PopupBlocker::openBlocked state.
if ((abuse == PopupBlocker::openAllowed ||
abuse == PopupBlocker::openControlled) &&
!IsPopupAllowed() &&
!ConsumeTransientUserActivationForMultiplePopupBlocking()) {
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns,
doc, nsContentUtils::eDOM_PROPERTIES,
"MultiplePopupsBlockedNoUserActivation");
abuse = PopupBlocker::openBlocked;
}
}
return abuse;
}
void BrowsingContext::GetUserActivationModifiersForPopup(
UserActivation::Modifiers* aModifiers) {
RefPtr<Document> doc = GetExtantDocument();
if (doc) {
// Unlike RevisePopupAbuseLevel, modifiers can always be used regardless
// of PopupControlState.
(void)ApplyToDocumentsForPopup(doc, [&](Document* doc) {
return doc->GetTransientUserGestureActivationModifiers(aModifiers);
});
}
}
void BrowsingContext::IncrementHistoryEntryCountForBrowsingContext() {
(void)SetHistoryEntryCount(GetHistoryEntryCount() + 1);
}
std::tuple<bool, bool> BrowsingContext::CanFocusCheck(CallerType aCallerType) {
nsFocusManager* fm = nsFocusManager::GetFocusManager();
if (!fm) {
return {false, false};
}
nsCOMPtr<nsPIDOMWindowInner> caller = do_QueryInterface(GetEntryGlobal());
BrowsingContext* callerBC = caller ? caller->GetBrowsingContext() : nullptr;
RefPtr<BrowsingContext> openerBC = GetOpener();
MOZ_DIAGNOSTIC_ASSERT(!openerBC || openerBC->Group() == Group());
// Enforce dom.disable_window_flip (for non-chrome), but still allow the
// window which opened us to raise us at times when popups are allowed
// (bugs 355482 and 369306).
bool canFocus = aCallerType == CallerType::System ||
!Preferences::GetBool("dom.disable_window_flip", true);
if (!canFocus && openerBC == callerBC) {
canFocus =
(callerBC ? callerBC : this)
->RevisePopupAbuseLevel(PopupBlocker::GetPopupControlState()) <
PopupBlocker::openBlocked;
}
bool isActive = false;
if (XRE_IsParentProcess()) {
CanonicalBrowsingContext* chromeTop = Canonical()->TopCrossChromeBoundary();
nsCOMPtr<nsPIDOMWindowOuter> activeWindow = fm->GetActiveWindow();
isActive = activeWindow == chromeTop->GetDOMWindow();
} else {
isActive = fm->GetActiveBrowsingContext() == Top();
}
return {canFocus, isActive};
}
void BrowsingContext::Focus(CallerType aCallerType, ErrorResult& aError) {
// These checks need to happen before the RequestFrameFocus call, which
// is why they are done in an untrusted process. If we wanted to enforce
// these in the parent, we'd need to do the checks there _also_.
// These should be kept in sync with nsGlobalWindowOuter::FocusOuter.
auto [canFocus, isActive] = CanFocusCheck(aCallerType);
if (!(canFocus || isActive)) {
return;
}
// Permission check passed
if (mEmbedderElement) {
// Make the activeElement in this process update synchronously.
nsContentUtils::RequestFrameFocus(*mEmbedderElement, true, aCallerType);
}
uint64_t actionId = nsFocusManager::GenerateFocusActionId();
if (ContentChild* cc = ContentChild::GetSingleton()) {
cc->SendWindowFocus(this, aCallerType, actionId);
} else if (ContentParent* cp = Canonical()->GetContentParent()) {
(void)cp->SendWindowFocus(this, aCallerType, actionId);
}
}
bool BrowsingContext::CanBlurCheck(CallerType aCallerType) {
// If dom.disable_window_flip == true, then content should not be allowed
// to do blur (this would allow popunders, bug 369306)
return aCallerType == CallerType::System ||
!Preferences::GetBool("dom.disable_window_flip", true);
}
void BrowsingContext::Blur(CallerType aCallerType, ErrorResult& aError) {
if (!CanBlurCheck(aCallerType)) {
return;
}
if (ContentChild* cc = ContentChild::GetSingleton()) {
cc->SendWindowBlur(this, aCallerType);
} else if (ContentParent* cp = Canonical()->GetContentParent()) {
(void)cp->SendWindowBlur(this, aCallerType);
}
}
Nullable<WindowProxyHolder> BrowsingContext::GetWindow() {
if (XRE_IsParentProcess() && !IsInProcess()) {
return nullptr;
}
return WindowProxyHolder(this);
}
Nullable<WindowProxyHolder> BrowsingContext::GetTop(ErrorResult& aError) {
if (mIsDiscarded) {
return nullptr;
}
// We never return null or throw an error, but the implementation in
// nsGlobalWindow does and we need to use the same signature.
return WindowProxyHolder(Top());
}
void BrowsingContext::GetOpener(JSContext* aCx,
JS::MutableHandle<JS::Value> aOpener,
ErrorResult& aError) const {
RefPtr<BrowsingContext> opener = GetOpener();
if (!opener) {
aOpener.setNull();
return;
}
if (!ToJSValue(aCx, WindowProxyHolder(opener), aOpener)) {
aError.NoteJSContextException(aCx);
}
}
// We never throw an error, but the implementation in nsGlobalWindow does and
// we need to use the same signature.
Nullable<WindowProxyHolder> BrowsingContext::GetParent(ErrorResult& aError) {
if (mIsDiscarded) {
return nullptr;
}
if (GetParent()) {
return WindowProxyHolder(GetParent());
}
return WindowProxyHolder(this);
}
void BrowsingContext::PostMessageMoz(JSContext* aCx,
JS::Handle<JS::Value> aMessage,
const nsAString& aTargetOrigin,
const Sequence<JSObject*>& aTransfer,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
if (mIsDiscarded) {
return;
}
RefPtr<BrowsingContext> sourceBc;
PostMessageData data;
data.targetOrigin() = aTargetOrigin;
data.subjectPrincipal() = &aSubjectPrincipal;
RefPtr<nsGlobalWindowInner> callerInnerWindow;
nsAutoCString scriptLocation;
// We don't need to get the caller's agentClusterId since that is used for
// checking whether it's okay to sharing memory (and it's not allowed to share
// memory cross processes)
if (!nsGlobalWindowOuter::GatherPostMessageData(
aCx, aTargetOrigin, getter_AddRefs(sourceBc), data.origin(),
getter_AddRefs(data.targetOriginURI()),
getter_AddRefs(data.callerPrincipal()),
getter_AddRefs(callerInnerWindow), getter_AddRefs(data.callerURI()),
/* aCallerAgentClusterId */ nullptr, &scriptLocation, aError)) {
return;
}
if (sourceBc && sourceBc->IsDiscarded()) {
return;
}
data.source() = sourceBc;
data.isFromPrivateWindow() =
callerInnerWindow &&
nsScriptErrorBase::ComputeIsFromPrivateWindow(callerInnerWindow);
data.innerWindowId() = callerInnerWindow ? callerInnerWindow->WindowID() : 0;
data.scriptLocation() = scriptLocation;
JS::Rooted<JS::Value> transferArray(aCx);
aError = nsContentUtils::CreateJSValueFromSequenceOfObject(aCx, aTransfer,
&transferArray);
if (NS_WARN_IF(aError.Failed())) {
return;
}
JS::CloneDataPolicy clonePolicy;
if (callerInnerWindow && callerInnerWindow->IsSharedMemoryAllowed()) {
clonePolicy.allowSharedMemoryObjects();
}
// We will see if the message is required to be in the same process or it can
// be in the different process after Write().
ipc::StructuredCloneData message = ipc::StructuredCloneData(
StructuredCloneHolder::StructuredCloneScope::UnknownDestination,
StructuredCloneHolder::TransferringSupported);
message.Write(aCx, aMessage, transferArray, clonePolicy, aError);
if (NS_WARN_IF(aError.Failed())) {
return;
}
ClonedOrErrorMessageData messageData;
if (ContentChild* cc = ContentChild::GetSingleton()) {
// The clone scope gets set when we write the message data based on the
// requirements of that data that we're writing.
// If the message data contains a shared memory object, then CloneScope
// would return SameProcess. Otherwise, it returns DifferentProcess.
if (message.CloneScope() ==
StructuredCloneHolder::StructuredCloneScope::DifferentProcess) {
ClonedMessageData clonedMessageData;
if (!message.BuildClonedMessageData(clonedMessageData)) {
aError.Throw(NS_ERROR_FAILURE);
return;
}
messageData = std::move(clonedMessageData);
} else {
MOZ_ASSERT(message.CloneScope() ==
StructuredCloneHolder::StructuredCloneScope::SameProcess);
messageData = ErrorMessageData();
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "DOM Window"_ns,
callerInnerWindow ? callerInnerWindow->GetDocument() : nullptr,
nsContentUtils::eDOM_PROPERTIES,
"PostMessageSharedMemoryObjectToCrossOriginWarning");
}
cc->SendWindowPostMessage(this, messageData, data);
} else if (ContentParent* cp = Canonical()->GetContentParent()) {
if (message.CloneScope() ==
StructuredCloneHolder::StructuredCloneScope::DifferentProcess) {
ClonedMessageData clonedMessageData;
if (!message.BuildClonedMessageData(clonedMessageData)) {
aError.Throw(NS_ERROR_FAILURE);
return;
}
messageData = std::move(clonedMessageData);
} else {
MOZ_ASSERT(message.CloneScope() ==
StructuredCloneHolder::StructuredCloneScope::SameProcess);
messageData = ErrorMessageData();
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "DOM Window"_ns,
callerInnerWindow ? callerInnerWindow->GetDocument() : nullptr,
nsContentUtils::eDOM_PROPERTIES,
"PostMessageSharedMemoryObjectToCrossOriginWarning");
}
(void)cp->SendWindowPostMessage(this, messageData, data);
}
}
void BrowsingContext::PostMessageMoz(JSContext* aCx,
JS::Handle<JS::Value> aMessage,
const WindowPostMessageOptions& aOptions,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
PostMessageMoz(aCx, aMessage, aOptions.mTargetOrigin, aOptions.mTransfer,
aSubjectPrincipal, aError);
}
void BrowsingContext::SendCommitTransaction(ContentParent* aParent,
const BaseTransaction& aTxn,
uint64_t aEpoch) {
(void)aParent->SendCommitBrowsingContextTransaction(this, aTxn, aEpoch);
}
void BrowsingContext::SendCommitTransaction(ContentChild* aChild,
const BaseTransaction& aTxn,
uint64_t aEpoch) {
aChild->SendCommitBrowsingContextTransaction(this, aTxn, aEpoch);
}
BrowsingContext::IPCInitializer BrowsingContext::GetIPCInitializer() {
MOZ_DIAGNOSTIC_ASSERT(mEverAttached);
MOZ_DIAGNOSTIC_ASSERT(mType == Type::Content);
IPCInitializer init;
init.mId = Id();
init.mParentId = mParentWindow ? mParentWindow->Id() : 0;
init.mWindowless = mWindowless;
init.mUseRemoteTabs = mUseRemoteTabs;
init.mUseRemoteSubframes = mUseRemoteSubframes;
init.mCreatedDynamically = mCreatedDynamically;
init.mChildOffset = mChildOffset;
init.mOriginAttributes = mOriginAttributes;
if (mChildSessionHistory && mozilla::SessionHistoryInParent()) {
init.mSessionHistoryIndex = mChildSessionHistory->Index();
init.mSessionHistoryCount = mChildSessionHistory->Count();
}
init.mRequestContextId = mRequestContextId;
init.mFields = mFields.RawValues();
return init;
}
already_AddRefed<WindowContext> BrowsingContext::IPCInitializer::GetParent() {
RefPtr<WindowContext> parent;
if (mParentId != 0) {
parent = WindowContext::GetById(mParentId);
MOZ_RELEASE_ASSERT(parent);
}
return parent.forget();
}
already_AddRefed<BrowsingContext> BrowsingContext::IPCInitializer::GetOpener() {
RefPtr<BrowsingContext> opener;
if (GetOpenerId() != 0) {
opener = BrowsingContext::Get(GetOpenerId());
MOZ_RELEASE_ASSERT(opener);
}
return opener.forget();
}
void BrowsingContext::StartDelayedAutoplayMediaComponents() {
if (!mDocShell) {
return;
}
AUTOPLAY_LOG("%s : StartDelayedAutoplayMediaComponents for bc 0x%08" PRIx64,
XRE_IsParentProcess() ? "Parent" : "Child", Id());
mDocShell->StartDelayedAutoplayMediaComponents();
}
nsresult BrowsingContext::ResetGVAutoplayRequestStatus() {
MOZ_ASSERT(IsTop(),
"Should only set GVAudibleAutoplayRequestStatus in the top-level "
"browsing context");
Transaction txn;
txn.SetGVAudibleAutoplayRequestStatus(GVAutoplayRequestStatus::eUNKNOWN);
txn.SetGVInaudibleAutoplayRequestStatus(GVAutoplayRequestStatus::eUNKNOWN);
return txn.Commit(this);
}
template <typename Callback>
void BrowsingContext::WalkPresContexts(Callback&& aCallback) {
PreOrderWalk([&](BrowsingContext* aContext) {
if (nsIDocShell* shell = aContext->GetDocShell()) {
if (RefPtr pc = shell->GetPresContext()) {
aCallback(pc.get());
}
}
});
}
void BrowsingContext::PresContextAffectingFieldChanged() {
WalkPresContexts([&](nsPresContext* aPc) {
aPc->RecomputeBrowsingContextDependentData();
});
}
void BrowsingContext::DidSet(FieldIndex<IDX_SessionStoreEpoch>,
uint32_t aOldValue) {
if (!mCurrentWindowContext) {
return;
}
SessionStoreChild* sessionStoreChild =
SessionStoreChild::From(mCurrentWindowContext->GetWindowGlobalChild());
if (!sessionStoreChild) {
return;
}
sessionStoreChild->SetEpoch(GetSessionStoreEpoch());
}
void BrowsingContext::DidSet(FieldIndex<IDX_GVAudibleAutoplayRequestStatus>) {
MOZ_ASSERT(IsTop(),
"Should only set GVAudibleAutoplayRequestStatus in the top-level "
"browsing context");
}
void BrowsingContext::DidSet(FieldIndex<IDX_GVInaudibleAutoplayRequestStatus>) {
MOZ_ASSERT(IsTop(),
"Should only set GVAudibleAutoplayRequestStatus in the top-level "
"browsing context");
}
bool BrowsingContext::CanSet(FieldIndex<IDX_ExplicitActive>,
const ExplicitActiveStatus&,
ContentParent* aSource) {
return XRE_IsParentProcess() && IsTop() && !aSource;
}
void BrowsingContext::DidSet(FieldIndex<IDX_ExplicitActive>,
ExplicitActiveStatus aOldValue) {
MOZ_ASSERT(IsTop());
const bool isActive = IsActive();
const bool wasActive = [&] {
if (aOldValue != ExplicitActiveStatus::None) {
return aOldValue == ExplicitActiveStatus::Active;
}
return GetParent() && GetParent()->IsActive();
}();
if (isActive == wasActive) {
return;
}
Group()->UpdateToplevelsSuspendedIfNeeded();
if (XRE_IsParentProcess()) {
if (BrowserParent* bp = Canonical()->GetBrowserParent()) {
bp->RecomputeProcessPriority();
#if defined(XP_WIN) && defined(ACCESSIBILITY)
if (a11y::Compatibility::IsDolphin()) {
// update active accessible documents on windows
if (a11y::DocAccessibleParent* tabDoc =
bp->GetTopLevelDocAccessible()) {
HWND window = tabDoc->GetEmulatedWindowHandle();
MOZ_ASSERT(window);
if (window) {
if (isActive) {
a11y::nsWinUtils::ShowNativeWindow(window);
} else {
a11y::nsWinUtils::HideNativeWindow(window);
}
}
}
}
#endif
}
// NOTE(emilio): Ideally we'd want to reuse the ExplicitActiveStatus::None
// set-up, but that's non-trivial to do because in content processes we
// can't access the top-cross-chrome-boundary bc.
auto manageTopDescendant = [&](auto* aChild) {
if (!aChild->ManuallyManagesActiveness()) {
aChild->SetIsActiveInternal(isActive, IgnoreErrors());
if (BrowserParent* bp = aChild->GetBrowserParent()) {
bp->SetRenderLayers(isActive);
}
}
return CallState::Continue;
};
Canonical()->CallOnTopDescendants(
manageTopDescendant,
CanonicalBrowsingContext::TopDescendantKind::NonNested);
}
PreOrderWalk([&](BrowsingContext* aContext) {
if (nsCOMPtr<nsIDocShell> ds = aContext->GetDocShell()) {
if (auto* bc = BrowserChild::GetFrom(ds)) {
bc->UpdateVisibility();
}
nsDocShell::Cast(ds)->ActivenessMaybeChanged();
}
});
}
void BrowsingContext::DidSet(FieldIndex<IDX_InRDMPane>, bool aOldValue) {
MOZ_ASSERT(IsTop(),
"Should only set InRDMPane in the top-level browsing context");
if (GetInRDMPane() == aOldValue) {
return;
}
// Reset screen orientation override when disabling RDM.
if (!GetInRDMPane()) {
ResetOrientationOverride();
}
PresContextAffectingFieldChanged();
}
void BrowsingContext::DidSet(FieldIndex<IDX_HasOrientationOverride>,
bool aOldValue) {
bool hasOrientationOverride = GetHasOrientationOverride();
OrientationType type = GetCurrentOrientationType();
float angle = GetCurrentOrientationAngle();
PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
if (RefPtr<WindowContext> windowContext =
aBrowsingContext->GetCurrentWindowContext()) {
if (nsCOMPtr<nsPIDOMWindowInner> window =
windowContext->GetInnerWindow()) {
ScreenOrientation* orientation =
nsGlobalWindowInner::Cast(window)->Screen()->Orientation();
float screenOrientationAngle =
orientation->DeviceAngle(CallerType::System);
OrientationType screenOrientationType =
orientation->DeviceType(CallerType::System);
bool overrideIsDifferentThanDevice =
screenOrientationType != type || screenOrientationAngle != angle;
// Reset orientation override.
if (!hasOrientationOverride && aOldValue) {
(void)aBrowsingContext->SetCurrentOrientation(screenOrientationType,
screenOrientationAngle);
} else if (!aBrowsingContext->IsTop()) {
// Sync orientation override in the existing frames.
(void)aBrowsingContext->SetCurrentOrientation(type, angle);
}
orientation->MaybeDispatchEventsForOverride(
aBrowsingContext, aOldValue, overrideIsDifferentThanDevice);
}
}
});
}
void BrowsingContext::DidSet(FieldIndex<IDX_ForceDesktopViewport>,
bool aOldValue) {
MOZ_ASSERT(IsTop(), "Should only set in the top-level browsing context");
if (ForceDesktopViewport() == aOldValue) {
return;
}
PresContextAffectingFieldChanged();
if (nsIDocShell* shell = GetDocShell()) {
if (RefPtr ps = shell->GetPresShell()) {
ps->MaybeRecreateMobileViewportManager(/* aAfterInitialization= */ true);
}
}
}
bool BrowsingContext::CanSet(FieldIndex<IDX_PageAwakeRequestCount>,
uint32_t aNewValue, ContentParent* aSource) {
return IsTop() && XRE_IsParentProcess() && !aSource;
}
void BrowsingContext::DidSet(FieldIndex<IDX_PageAwakeRequestCount>,
uint32_t aOldValue) {
if (!IsTop() || aOldValue == GetPageAwakeRequestCount()) {
return;
}
Group()->UpdateToplevelsSuspendedIfNeeded();
}
auto BrowsingContext::CanSet(FieldIndex<IDX_AllowJavascript>, bool aValue,
ContentParent* aSource) -> CanSetResult {
if (mozilla::SessionHistoryInParent()) {
return XRE_IsParentProcess() && !aSource ? CanSetResult::Allow
: CanSetResult::Deny;
}
// Without Session History in Parent, session restore code still needs to set
// this from content processes.
return LegacyRevertIfNotOwningOrParentProcess(aSource);
}
void BrowsingContext::DidSet(FieldIndex<IDX_AllowJavascript>, bool aOldValue) {
RecomputeCanExecuteScripts();
}
void BrowsingContext::RecomputeCanExecuteScripts() {
const bool old = mCanExecuteScripts;
if (!AllowJavascript()) {
// Scripting has been explicitly disabled on our BrowsingContext.
mCanExecuteScripts = false;
} else if (GetParentWindowContext()) {
// Otherwise, inherit parent.
mCanExecuteScripts = GetParentWindowContext()->CanExecuteScripts();
} else {
// Otherwise, we're the root of the tree, and we haven't explicitly disabled
// script. Allow.
mCanExecuteScripts = true;
}
if (old != mCanExecuteScripts) {
for (WindowContext* wc : GetWindowContexts()) {
wc->RecomputeCanExecuteScripts();
}
}
}
bool BrowsingContext::InactiveForSuspend() const {
if (!StaticPrefs::dom_suspend_inactive_enabled()) {
return false;
}
// We should suspend a page only when it's inactive and doesn't have any awake
// request that is used to prevent page from being suspended because web page
// might still need to run their script. Eg. waiting for media keys to resume
// media, playing web audio, waiting in a video call conference room.
return !IsActive() && GetPageAwakeRequestCount() == 0;
}
bool BrowsingContext::CanSet(FieldIndex<IDX_TouchEventsOverrideInternal>,
dom::TouchEventsOverride, ContentParent* aSource) {
return XRE_IsParentProcess() && !aSource;
}
void BrowsingContext::DidSet(FieldIndex<IDX_TouchEventsOverrideInternal>,
dom::TouchEventsOverride&& aOldValue) {
if (GetTouchEventsOverrideInternal() == aOldValue) {
return;
}
WalkPresContexts([&](nsPresContext* aPc) {
aPc->MediaFeatureValuesChanged(
{MediaFeatureChangeReason::SystemMetricsChange},
// We're already iterating through sub documents, so we don't need to
// propagate the change again.
MediaFeatureChangePropagation::JustThisDocument);
});
}
void BrowsingContext::DidSet(FieldIndex<IDX_EmbedderColorSchemes>,
EmbedderColorSchemes&& aOldValue) {
if (GetEmbedderColorSchemes() == aOldValue) {
return;
}
PresContextAffectingFieldChanged();
}
void BrowsingContext::DidSet(FieldIndex<IDX_PrefersColorSchemeOverride>,
dom::PrefersColorSchemeOverride aOldValue) {
MOZ_ASSERT(IsTop());
if (PrefersColorSchemeOverride() == aOldValue) {
return;
}
PresContextAffectingFieldChanged();
}
void BrowsingContext::DidSet(FieldIndex<IDX_ForcedColorsOverride>,
dom::ForcedColorsOverride aOldValue) {
MOZ_ASSERT(IsTop());
if (ForcedColorsOverride() == aOldValue) {
return;
}
PresContextAffectingFieldChanged();
}
void BrowsingContext::DidSet(FieldIndex<IDX_LanguageOverride>,
nsCString&& aOldValue) {
MOZ_ASSERT(IsTop());
const nsCString& languageOverride = GetLanguageOverride();
PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
if (RefPtr<WindowContext> windowContext =
aBrowsingContext->GetCurrentWindowContext()) {
if (nsCOMPtr<nsPIDOMWindowInner> window =
windowContext->GetInnerWindow()) {
JSObject* global =
nsGlobalWindowInner::Cast(window)->GetGlobalJSObject();
JS::Realm* realm = JS::GetObjectRealmOrNull(global);
if (mDefaultLocale == nullptr) {
AutoJSAPI jsapi;
if (jsapi.Init(window)) {
JSContext* context = jsapi.cx();
mDefaultLocale = JS_GetDefaultLocale(context);
}
}
if (languageOverride.IsEmpty()) {
JS::SetRealmLocaleOverride(realm, mDefaultLocale.get());
mDefaultLocale = nullptr;
} else {
JS::SetRealmLocaleOverride(
realm, PromiseFlatCString(languageOverride).get());
}
if (Navigator* navigator = window->Navigator()) {
navigator->ClearLanguageCache();
}
}
}
});
}
void BrowsingContext::DidSet(FieldIndex<IDX_MediumOverride>,
nsString&& aOldValue) {
MOZ_ASSERT(IsTop());
if (GetMediumOverride() == aOldValue) {
return;
}
PresContextAffectingFieldChanged();
}
void BrowsingContext::DidSet(FieldIndex<IDX_DisplayMode>,
enum DisplayMode aOldValue) {
MOZ_ASSERT(IsTop());
if (GetDisplayMode() == aOldValue) {
return;
}
WalkPresContexts([&](nsPresContext* aPc) {
aPc->MediaFeatureValuesChanged(
{MediaFeatureChangeReason::DisplayModeChange},
// We're already iterating through sub documents, so we don't need
// to propagate the change again.
//
// Images and other resources don't change their display-mode
// evaluation, display-mode is a property of the browsing context.
MediaFeatureChangePropagation::JustThisDocument);
});
}
void BrowsingContext::DidSet(FieldIndex<IDX_Muted>) {
MOZ_ASSERT(IsTop(), "Set muted flag on non top-level context!");
USER_ACTIVATION_LOG("Set audio muted %d for %s browsing context 0x%08" PRIx64,
GetMuted(), XRE_IsParentProcess() ? "Parent" : "Child",
Id());
PreOrderWalk([&](BrowsingContext* aContext) {
nsPIDOMWindowOuter* win = aContext->GetDOMWindow();
if (win) {
win->RefreshMediaElementsVolume();
}
});
}
bool BrowsingContext::CanSet(FieldIndex<IDX_IsAppTab>, const bool& aValue,
ContentParent* aSource) {
return XRE_IsParentProcess() && !aSource && IsTop();
}
bool BrowsingContext::CanSet(FieldIndex<IDX_HasSiblings>, const bool& aValue,
ContentParent* aSource) {
return XRE_IsParentProcess() && !aSource && IsTop();
}
bool BrowsingContext::CanSet(FieldIndex<IDX_ShouldDelayMediaFromStart>,
const bool& aValue, ContentParent* aSource) {
return IsTop();
}
void BrowsingContext::DidSet(FieldIndex<IDX_ShouldDelayMediaFromStart>,
bool aOldValue) {
MOZ_ASSERT(IsTop(), "Set attribute on non top-level context!");
if (aOldValue == GetShouldDelayMediaFromStart()) {
return;
}
if (!GetShouldDelayMediaFromStart()) {
PreOrderWalk([&](BrowsingContext* aContext) {
if (nsPIDOMWindowOuter* win = aContext->GetDOMWindow()) {
win->ActivateMediaComponents();
}
});
}
}
bool BrowsingContext::CanSet(FieldIndex<IDX_OverrideDPPX>, const float& aValue,
ContentParent* aSource) {
return XRE_IsParentProcess() && !aSource && IsTop();
}
void BrowsingContext::DidSet(FieldIndex<IDX_OverrideDPPX>, float aOldValue) {
MOZ_ASSERT(IsTop());
if (GetOverrideDPPX() == aOldValue) {
return;
}
PresContextAffectingFieldChanged();
}
void BrowsingContext::SetCustomUserAgent(const nsAString& aUserAgent,
ErrorResult& aRv) {
Top()->SetUserAgentOverride(aUserAgent, aRv);
}
nsresult BrowsingContext::SetCustomUserAgent(const nsAString& aUserAgent) {
return Top()->SetUserAgentOverride(aUserAgent);
}
void BrowsingContext::DidSet(FieldIndex<IDX_UserAgentOverride>) {
MOZ_ASSERT(IsTop());
PreOrderWalk([&](BrowsingContext* aContext) {
nsIDocShell* shell = aContext->GetDocShell();
if (shell) {
shell->ClearCachedUserAgent();
}
if (nsCOMPtr<Document> doc = aContext->GetExtantDocument()) {
if (nsCOMPtr<nsIHttpChannel> httpChannel =
do_QueryInterface(doc->GetChannel())) {
(void)httpChannel->SetIsUserAgentHeaderOutdated(true);
}
}
});
}
bool BrowsingContext::CanSet(FieldIndex<IDX_IsInBFCache>, bool,
ContentParent* aSource) {
return IsTop() && !aSource && mozilla::BFCacheInParent();
}
void BrowsingContext::DidSet(FieldIndex<IDX_IsInBFCache>) {
MOZ_RELEASE_ASSERT(mozilla::BFCacheInParent());
MOZ_DIAGNOSTIC_ASSERT(IsTop());
const bool isInBFCache = GetIsInBFCache();
if (!isInBFCache) {
UpdateCurrentTopByBrowserId(this);
PreOrderWalk([&](BrowsingContext* aContext) {
aContext->mIsInBFCache = false;
nsCOMPtr<nsIDocShell> shell = aContext->GetDocShell();
if (shell) {
nsDocShell::Cast(shell)->ThawFreezeNonRecursive(true);
}
});
}
if (isInBFCache && XRE_IsContentProcess() && mDocShell) {
nsDocShell::Cast(mDocShell)->MaybeDisconnectChildListenersOnPageHide();
}
if (isInBFCache) {
PreOrderWalk([&](BrowsingContext* aContext) {
nsCOMPtr<nsIDocShell> shell = aContext->GetDocShell();
if (shell) {
nsDocShell::Cast(shell)->FirePageHideShowNonRecursive(false);
}
});
} else {
PostOrderWalk([&](BrowsingContext* aContext) {
nsCOMPtr<nsIDocShell> shell = aContext->GetDocShell();
if (shell) {
nsDocShell::Cast(shell)->FirePageHideShowNonRecursive(true);
}
});
}
if (isInBFCache) {
PreOrderWalk([&](BrowsingContext* aContext) {
nsCOMPtr<nsIDocShell> shell = aContext->GetDocShell();
if (shell) {
nsDocShell::Cast(shell)->ThawFreezeNonRecursive(false);
if (nsPresContext* pc = shell->GetPresContext()) {
pc->EventStateManager()->ResetHoverState();
}
}
aContext->mIsInBFCache = true;
Document* doc = aContext->GetDocument();
if (doc) {
// Notifying needs to happen after mIsInBFCache is set to true.
doc->NotifyActivityChanged();
}
});
if (XRE_IsParentProcess()) {
if (mCurrentWindowContext &&
mCurrentWindowContext->Canonical()->Fullscreen()) {
mCurrentWindowContext->Canonical()->ExitTopChromeDocumentFullscreen();
}
}
}
}
void BrowsingContext::DidSet(FieldIndex<IDX_IsSyntheticDocumentContainer>) {
if (WindowContext* parentWindowContext = GetParentWindowContext()) {
parentWindowContext->UpdateChildSynthetic(
this, GetIsSyntheticDocumentContainer());
}
}
void BrowsingContext::SetCustomPlatform(const nsAString& aPlatform,
ErrorResult& aRv) {
Top()->SetPlatformOverride(aPlatform, aRv);
}
void BrowsingContext::DidSet(FieldIndex<IDX_PlatformOverride>) {
MOZ_ASSERT(IsTop());
PreOrderWalk([&](BrowsingContext* aContext) {
nsIDocShell* shell = aContext->GetDocShell();
if (shell) {
shell->ClearCachedPlatform();
}
});
}
auto BrowsingContext::LegacyRevertIfNotOwningOrParentProcess(
ContentParent* aSource) -> CanSetResult {
if (aSource) {
MOZ_ASSERT(XRE_IsParentProcess());
if (!Canonical()->IsOwnedByProcess(aSource->ChildID())) {
return CanSetResult::Revert;
}
} else if (!IsInProcess() && !XRE_IsParentProcess()) {
// Don't allow this to be set from content processes that
// don't own the BrowsingContext.
return CanSetResult::Deny;
}
return CanSetResult::Allow;
}
bool BrowsingContext::CanSet(FieldIndex<IDX_IsActiveBrowserWindowInternal>,
const bool& aValue, ContentParent* aSource) {
// Should only be set in the parent process.
return XRE_IsParentProcess() && !aSource && IsTop();
}
void BrowsingContext::DidSet(FieldIndex<IDX_IsActiveBrowserWindowInternal>,
bool aOldValue) {
bool isActivateEvent = GetIsActiveBrowserWindowInternal();
// The browser window containing this context has changed
// activation state so update window inactive document states
// for all in-process documents.
PreOrderWalk([isActivateEvent](BrowsingContext* aContext) {
if (RefPtr<Document> doc = aContext->GetExtantDocument()) {
doc->UpdateDocumentStates(DocumentState::WINDOW_INACTIVE, true);
RefPtr<nsPIDOMWindowInner> win = doc->GetInnerWindow();
if (win) {
RefPtr<MediaDevices> devices;
if (isActivateEvent && (devices = win->GetExtantMediaDevices())) {
devices->BrowserWindowBecameActive();
}
if (XRE_IsContentProcess() &&
(!aContext->GetParent() || !aContext->GetParent()->IsInProcess())) {
// Send the inner window an activate/deactivate event if
// the context is the top of a sub-tree of in-process
// contexts.
nsContentUtils::DispatchEventOnlyToChrome(
doc, nsGlobalWindowInner::Cast(win),
isActivateEvent ? u"activate"_ns : u"deactivate"_ns,
CanBubble::eYes, Cancelable::eYes, nullptr);
}
}
}
});
}
bool BrowsingContext::CanSet(FieldIndex<IDX_OpenerPolicy>,
nsILoadInfo::CrossOriginOpenerPolicy aPolicy,
ContentParent* aSource) {
// A potentially cross-origin isolated BC can't change opener policy, nor can
// a BC become potentially cross-origin isolated. An unchanged policy is
// always OK.
return GetOpenerPolicy() == aPolicy ||
(GetOpenerPolicy() !=
nsILoadInfo::
OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP &&
aPolicy !=
nsILoadInfo::
OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP);
}
auto BrowsingContext::CanSet(FieldIndex<IDX_AllowContentRetargeting>,
const bool& aAllowContentRetargeting,
ContentParent* aSource) -> CanSetResult {
return LegacyRevertIfNotOwningOrParentProcess(aSource);
}
auto BrowsingContext::CanSet(FieldIndex<IDX_AllowContentRetargetingOnChildren>,
const bool& aAllowContentRetargetingOnChildren,
ContentParent* aSource) -> CanSetResult {
return LegacyRevertIfNotOwningOrParentProcess(aSource);
}
bool BrowsingContext::CanSet(FieldIndex<IDX_FullscreenAllowedByOwner>,
const bool& aAllowed, ContentParent* aSource) {
return CheckOnlyEmbedderCanSet(aSource);
}
bool BrowsingContext::CanSet(FieldIndex<IDX_UseErrorPages>,
const bool& aUseErrorPages,
ContentParent* aSource) {
return CheckOnlyEmbedderCanSet(aSource);
}
TouchEventsOverride BrowsingContext::TouchEventsOverride() const {
for (const auto* bc = this; bc; bc = bc->GetParent()) {
auto tev = bc->GetTouchEventsOverrideInternal();
if (tev != dom::TouchEventsOverride::None) {
return tev;
}
}
return dom::TouchEventsOverride::None;
}
bool BrowsingContext::TargetTopLevelLinkClicksToBlank() const {
return Top()->GetTargetTopLevelLinkClicksToBlankInternal();
}
// We map `watchedByDevTools` WebIDL attribute to `watchedByDevToolsInternal`
// BC field. And we map it to the top level BrowsingContext.
bool BrowsingContext::WatchedByDevTools() {
return Top()->GetWatchedByDevToolsInternal();
}
// Enforce that the watchedByDevTools BC field can only be set on the top level
// Browsing Context.
bool BrowsingContext::CanSet(FieldIndex<IDX_WatchedByDevToolsInternal>,
const bool& aWatchedByDevTools,
ContentParent* aSource) {
return IsTop();
}
void BrowsingContext::SetWatchedByDevTools(bool aWatchedByDevTools,
ErrorResult& aRv) {
if (!IsTop()) {
aRv.ThrowInvalidModificationError(
"watchedByDevTools can only be set on top BrowsingContext");
return;
}
SetWatchedByDevToolsInternal(aWatchedByDevTools, aRv);
}
RefPtr<nsGeolocationService> BrowsingContext::GetGeolocationServiceOverride() {
// Override can be set only to the top-level browsing context,
// but when the geolocation coordinates are requested for iframe,
// we should return the override which is set for its top-level context.
return Top()->mGeolocationServiceOverride;
}
void BrowsingContext::SetGeolocationServiceOverride(
const Optional<nsIDOMGeoPosition*>& aGeolocationOverride) {
MOZ_ASSERT(
IsTop(),
"Should only set GeolocationServiceOverride in the top browsing context");
if (aGeolocationOverride.WasPassed()) {
if (!mGeolocationServiceOverride) {
mGeolocationServiceOverride = new nsGeolocationService();
mGeolocationServiceOverride->Init();
}
mGeolocationServiceOverride->Update(aGeolocationOverride.Value());
} else if (RefPtr<nsGeolocationService> serviceOverride =
mGeolocationServiceOverride.forget()) {
// Create an original service and move the locators.
RefPtr<nsGeolocationService> service =
nsGeolocationService::GetGeolocationService();
serviceOverride->MoveLocators(service);
}
}
void BrowsingContext::DidSet(FieldIndex<IDX_TimezoneOverride>,
nsString&& aOldValue) {
MOZ_ASSERT(IsTop());
PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
if (RefPtr<WindowContext> windowContext =
aBrowsingContext->GetCurrentWindowContext()) {
if (nsCOMPtr<nsPIDOMWindowInner> window =
windowContext->GetInnerWindow()) {
JSObject* global =
nsGlobalWindowInner::Cast(window)->GetGlobalJSObject();
JS::Realm* realm = JS::GetObjectRealmOrNull(global);
if (GetTimezoneOverride().IsEmpty()) {
JS::SetRealmTimezoneOverride(realm, nullptr);
} else {
JS::SetRealmTimezoneOverride(
realm, NS_ConvertUTF16toUTF8(GetTimezoneOverride()).get());
}
}
}
});
}
auto BrowsingContext::CanSet(FieldIndex<IDX_DefaultLoadFlags>,
const uint32_t& aDefaultLoadFlags,
ContentParent* aSource) -> CanSetResult {
// Bug 1623565 - Are these flags only used by the debugger, which makes it
// possible that this field can only be settable by the parent process?
return LegacyRevertIfNotOwningOrParentProcess(aSource);
}
void BrowsingContext::DidSet(FieldIndex<IDX_DefaultLoadFlags>) {
auto loadFlags = GetDefaultLoadFlags();
if (GetDocShell()) {
nsDocShell::Cast(GetDocShell())->SetLoadGroupDefaultLoadFlags(loadFlags);
}
if (XRE_IsParentProcess()) {
PreOrderWalk([&](BrowsingContext* aContext) {
if (aContext != this) {
// Setting load flags on a discarded context has no effect.
(void)aContext->SetDefaultLoadFlags(loadFlags);
}
});
}
}
bool BrowsingContext::CanSet(FieldIndex<IDX_UseGlobalHistory>,
const bool& aUseGlobalHistory,
ContentParent* aSource) {
// Should only be set in the parent process.
// return XRE_IsParentProcess() && !aSource;
return true;
}
auto BrowsingContext::CanSet(FieldIndex<IDX_UserAgentOverride>,
const nsString& aUserAgent, ContentParent* aSource)
-> CanSetResult {
if (!IsTop()) {
return CanSetResult::Deny;
}
return LegacyRevertIfNotOwningOrParentProcess(aSource);
}
auto BrowsingContext::CanSet(FieldIndex<IDX_PlatformOverride>,
const nsString& aPlatform, ContentParent* aSource)
-> CanSetResult {
if (!IsTop()) {
return CanSetResult::Deny;
}
return LegacyRevertIfNotOwningOrParentProcess(aSource);
}
bool BrowsingContext::CheckOnlyEmbedderCanSet(ContentParent* aSource) {
if (XRE_IsParentProcess()) {
uint64_t childId = aSource ? aSource->ChildID() : 0;
return Canonical()->IsEmbeddedInProcess(childId);
}
return mEmbeddedByThisProcess;
}
bool BrowsingContext::CanSet(FieldIndex<IDX_EmbedderInnerWindowId>,
const uint64_t& aValue, ContentParent* aSource) {
// If we have a parent window, our embedder inner window ID must match it.
if (mParentWindow) {
return mParentWindow->Id() == aValue;
}
// For toplevel BrowsingContext instances, this value may only be set by the
// parent process, or initialized to `0`.
return CheckOnlyEmbedderCanSet(aSource);
}
bool BrowsingContext::CanSet(FieldIndex<IDX_EmbedderElementType>,
const Maybe<nsString>&, ContentParent* aSource) {
return CheckOnlyEmbedderCanSet(aSource);
}
auto BrowsingContext::CanSet(FieldIndex<IDX_CurrentInnerWindowId>,
const uint64_t& aValue, ContentParent* aSource)
-> CanSetResult {
// Generally allow clearing this. We may want to be more precise about this
// check in the future.
if (aValue == 0) {
return CanSetResult::Allow;
}
// We must have access to the specified context.
RefPtr<WindowContext> window = WindowContext::GetById(aValue);
if (!window || window->GetBrowsingContext() != this) {
return CanSetResult::Deny;
}
if (aSource) {
// If the sending process is no longer the current owner, revert
MOZ_ASSERT(XRE_IsParentProcess());
if (!Canonical()->IsOwnedByProcess(aSource->ChildID())) {
return CanSetResult::Revert;
}
} else if (XRE_IsContentProcess() && !IsOwnedByProcess()) {
return CanSetResult::Deny;
}
return CanSetResult::Allow;
}
bool BrowsingContext::CanSet(FieldIndex<IDX_ParentInitiatedNavigationEpoch>,
const uint64_t& aValue, ContentParent* aSource) {
return XRE_IsParentProcess() && !aSource;
}
void BrowsingContext::DidSet(FieldIndex<IDX_CurrentInnerWindowId>) {
RefPtr<WindowContext> prevWindowContext = mCurrentWindowContext.forget();
mCurrentWindowContext = WindowContext::GetById(GetCurrentInnerWindowId());
MOZ_ASSERT(
!mCurrentWindowContext || mWindowContexts.Contains(mCurrentWindowContext),
"WindowContext not registered?");
// Clear our cached `children` value, to ensure that JS sees the up-to-date
// value.
BrowsingContext_Binding::ClearCachedChildrenValue(this);
if (XRE_IsParentProcess()) {
if (prevWindowContext != mCurrentWindowContext) {
if (prevWindowContext) {
prevWindowContext->Canonical()->DidBecomeCurrentWindowGlobal(false);
}
if (mCurrentWindowContext) {
// We set a timer when we set the current inner window. This
// will then flush the session storage to session store to
// make sure that we don't miss to store session storage to
// session store that is a result of navigation. This is due
// to Bug 1700623. We wish to fix this in Bug 1711886, where
// making sure to store everything would make this timer
// unnecessary.
Canonical()->MaybeScheduleSessionStoreUpdate();
mCurrentWindowContext->Canonical()->DidBecomeCurrentWindowGlobal(true);
}
}
BrowserParent::UpdateFocusFromBrowsingContext();
}
}
bool BrowsingContext::CanSet(FieldIndex<IDX_IsPopupSpam>, const bool& aValue,
ContentParent* aSource) {
// Ensure that we only mark a browsing context as popup spam once and never
// unmark it.
return aValue && !GetIsPopupSpam();
}
void BrowsingContext::DidSet(FieldIndex<IDX_IsPopupSpam>) {
if (GetIsPopupSpam()) {
PopupBlocker::RegisterOpenPopupSpam();
}
}
bool BrowsingContext::CanSet(FieldIndex<IDX_MessageManagerGroup>,
const nsString& aMessageManagerGroup,
ContentParent* aSource) {
// Should only be set in the parent process on toplevel.
return XRE_IsParentProcess() && !aSource && IsTopContent();
}
bool BrowsingContext::CanSet(
FieldIndex<IDX_OrientationLock>,
const mozilla::hal::ScreenOrientation& aOrientationLock,
ContentParent* aSource) {
return IsTop();
}
bool BrowsingContext::IsLoading() {
if (GetLoading()) {
return true;
}
// If we're in the same process as the page, we're possibly just
// updating the flag.
nsIDocShell* shell = GetDocShell();
if (shell) {
Document* doc = shell->GetDocument();
return doc && doc->GetReadyStateEnum() < Document::READYSTATE_COMPLETE;
}
return false;
}
void BrowsingContext::DidSet(FieldIndex<IDX_Loading>) {
if (mFields.Get<IDX_Loading>()) {
return;
}
while (!mDeprioritizedLoadRunner.isEmpty()) {
nsCOMPtr<nsIRunnable> runner = mDeprioritizedLoadRunner.popFirst();
NS_DispatchToCurrentThread(runner.forget());
}
if (IsTop()) {
Group()->FlushPostMessageEvents();
}
}
// Inform the Document for this context of the (potential) change in
// loading state
void BrowsingContext::DidSet(FieldIndex<IDX_AncestorLoading>) {
nsPIDOMWindowOuter* outer = GetDOMWindow();
if (!outer) {
MOZ_LOG(gTimeoutDeferralLog, mozilla::LogLevel::Debug,
("DidSetAncestorLoading BC: %p -- No outer window", (void*)this));
return;
}
Document* document = nsGlobalWindowOuter::Cast(outer)->GetExtantDoc();
if (document) {
MOZ_LOG(gTimeoutDeferralLog, mozilla::LogLevel::Debug,
("DidSetAncestorLoading BC: %p -- NotifyLoading(%d, %d, %d)",
(void*)this, GetAncestorLoading(), document->GetReadyStateEnum(),
document->GetReadyStateEnum()));
document->NotifyLoading(GetAncestorLoading(), document->GetReadyStateEnum(),
document->GetReadyStateEnum());
}
}
void BrowsingContext::DidSet(FieldIndex<IDX_AuthorStyleDisabledDefault>) {
MOZ_ASSERT(IsTop(),
"Should only set AuthorStyleDisabledDefault in the top "
"browsing context");
// We don't need to handle changes to this field, since PageStyleChild.sys.mjs
// will respond to the PageStyle:Disable message in all content processes.
//
// But we store the state here on the top BrowsingContext so that the
// docshell has somewhere to look for the current author style disabling
// state when new iframes are inserted.
}
void BrowsingContext::DidSet(FieldIndex<IDX_TextZoom>, float aOldValue) {
if (GetTextZoom() == aOldValue) {
return;
}
if (IsInProcess()) {
if (nsIDocShell* shell = GetDocShell()) {
if (nsPresContext* pc = shell->GetPresContext()) {
pc->RecomputeBrowsingContextDependentData();
}
}
for (BrowsingContext* child : Children()) {
// Setting text zoom on a discarded context has no effect.
(void)child->SetTextZoom(GetTextZoom());
}
}
if (IsTop() && XRE_IsParentProcess()) {
if (Element* element = GetEmbedderElement()) {
AsyncEventDispatcher::RunDOMEventWhenSafe(*element, u"TextZoomChange"_ns,
CanBubble::eYes,
ChromeOnlyDispatch::eYes);
}
}
}
// TODO(emilio): It'd be potentially nicer and cheaper to allow to set this only
// on the Top() browsing context, but there are a lot of tests that rely on
// zooming a subframe so...
void BrowsingContext::DidSet(FieldIndex<IDX_FullZoom>, float aOldValue) {
if (GetFullZoom() == aOldValue) {
return;
}
if (IsInProcess()) {
if (nsIDocShell* shell = GetDocShell()) {
if (nsPresContext* pc = shell->GetPresContext()) {
pc->RecomputeBrowsingContextDependentData();
}
}
for (BrowsingContext* child : Children()) {
// When passing the outer document's full-zoom down to the inner
// document, scale by the effective CSS 'zoom' on the embedder element:
auto fullZoom = GetFullZoom();
if (auto* elem = child->GetEmbedderElement()) {
if (auto* frame = elem->GetPrimaryFrame()) {
fullZoom = frame->Style()->EffectiveZoom().Zoom(fullZoom);
}
}
// Setting full zoom on a discarded context has no effect.
(void)child->SetFullZoom(fullZoom);
}
}
if (IsTop() && XRE_IsParentProcess()) {
if (Element* element = GetEmbedderElement()) {
AsyncEventDispatcher::RunDOMEventWhenSafe(*element, u"FullZoomChange"_ns,
CanBubble::eYes,
ChromeOnlyDispatch::eYes);
}
}
}
void BrowsingContext::AddDeprioritizedLoadRunner(nsIRunnable* aRunner) {
MOZ_ASSERT(IsLoading());
MOZ_ASSERT(Top() == this);
RefPtr<DeprioritizedLoadRunner> runner = new DeprioritizedLoadRunner(aRunner);
mDeprioritizedLoadRunner.insertBack(runner);
NS_DispatchToCurrentThreadQueue(runner.forget(), EventQueuePriority::Low);
}
bool BrowsingContext::IsDynamic() const {
const BrowsingContext* current = this;
do {
if (current->CreatedDynamically()) {
return true;
}
} while ((current = current->GetParent()));
return false;
}
bool BrowsingContext::GetOffsetPath(nsTArray<uint32_t>& aPath) const {
for (const BrowsingContext* current = this; current && current->GetParent();
current = current->GetParent()) {
if (current->CreatedDynamically()) {
return false;
}
aPath.AppendElement(current->ChildOffset());
}
return true;
}
void BrowsingContext::GetHistoryID(JSContext* aCx,
JS::MutableHandle<JS::Value> aVal,
ErrorResult& aError) {
if (!xpc::ID2JSValue(aCx, GetHistoryID(), aVal)) {
aError.Throw(NS_ERROR_OUT_OF_MEMORY);
}
}
void BrowsingContext::InitSessionHistory() {
MOZ_ASSERT(!IsDiscarded());
MOZ_ASSERT(IsTop());
MOZ_ASSERT(EverAttached());
if (!GetHasSessionHistory()) {
MOZ_ALWAYS_SUCCEEDS(SetHasSessionHistory(true));
}
}
ChildSHistory* BrowsingContext::GetChildSessionHistory() {
if (!mozilla::SessionHistoryInParent()) {
// For now we're checking that the session history object for the child
// process is available before returning the ChildSHistory object, because
// it is the actual implementation that ChildSHistory forwards to. This can
// be removed once session history is stored exclusively in the parent
// process.
return mChildSessionHistory && mChildSessionHistory->IsInProcess()
? mChildSessionHistory.get()
: nullptr;
}
return mChildSessionHistory;
}
void BrowsingContext::CreateChildSHistory() {
MOZ_ASSERT(IsTop());
MOZ_ASSERT(GetHasSessionHistory());
MOZ_ASSERT(!mChildSessionHistory);
// Because session history is global in a browsing context tree, every process
// that has access to a browsing context tree needs access to its session
// history. That is why we create the ChildSHistory object in every process
// where we have access to this browsing context (which is the top one).
mChildSessionHistory = new ChildSHistory(this);
// If the top browsing context (this one) is loaded in this process then we
// also create the session history implementation for the child process.
// This can be removed once session history is stored exclusively in the
// parent process.
mChildSessionHistory->SetIsInProcess(IsInProcess());
}
void BrowsingContext::DidSet(FieldIndex<IDX_HasSessionHistory>,
bool aOldValue) {
MOZ_ASSERT(GetHasSessionHistory() || !aOldValue,
"We don't support turning off session history.");
if (GetHasSessionHistory() && !aOldValue) {
CreateChildSHistory();
}
}
bool BrowsingContext::CanSet(
FieldIndex<IDX_TargetTopLevelLinkClicksToBlankInternal>,
const bool& aTargetTopLevelLinkClicksToBlankInternal,
ContentParent* aSource) {
return XRE_IsParentProcess() && !aSource && IsTop();
}
bool BrowsingContext::CanSet(FieldIndex<IDX_BrowserId>, const uint32_t& aValue,
ContentParent* aSource) {
// We should only be able to set this for toplevel contexts which don't have
// an ID yet.
return GetBrowserId() == 0 && IsTop() && Children().IsEmpty();
}
bool BrowsingContext::CanSet(FieldIndex<IDX_PendingInitialization>,
bool aNewValue, ContentParent* aSource) {
// Can only be cleared from `true` to `false`, and should only ever be set on
// the toplevel BrowsingContext.
return IsTop() && GetPendingInitialization() && !aNewValue;
}
bool BrowsingContext::CanSet(FieldIndex<IDX_TopLevelCreatedByWebContent>,
const bool& aNewValue, ContentParent* aSource) {
// Should only be set after creation in the parent process.
return XRE_IsParentProcess() && !aSource && IsTop();
}
bool BrowsingContext::CanSet(FieldIndex<IDX_HasRestoreData>, bool aNewValue,
ContentParent* aSource) {
return IsTop();
}
bool BrowsingContext::CanSet(FieldIndex<IDX_IsUnderHiddenEmbedderElement>,
const bool& aIsUnderHiddenEmbedderElement,
ContentParent* aSource) {
return true;
}
bool BrowsingContext::CanSet(FieldIndex<IDX_ForceOffline>, bool aNewValue,
ContentParent* aSource) {
return XRE_IsParentProcess() && !aSource;
}
void BrowsingContext::DidSet(FieldIndex<IDX_IsUnderHiddenEmbedderElement>,
bool aOldValue) {
nsIDocShell* shell = GetDocShell();
if (!shell) {
return;
}
const bool newValue = IsUnderHiddenEmbedderElement();
if (NS_WARN_IF(aOldValue == newValue)) {
return;
}
if (auto* bc = BrowserChild::GetFrom(shell)) {
bc->UpdateVisibility();
}
if (PresShell* presShell = shell->GetPresShell()) {
presShell->SetIsUnderHiddenEmbedderElement(newValue);
}
// Propagate to children.
auto PropagateToChild = [&newValue](BrowsingContext* aChild) {
Element* embedderElement = aChild->GetEmbedderElement();
if (!embedderElement) {
// TODO: We shouldn't need to null check here since `child` and the
// element returned by `child->GetEmbedderElement()` are in our
// process (the actual browsing context represented by `child` may not
// be, but that doesn't matter). However, there are currently a very
// small number of crashes due to `embedderElement` being null, somehow
// - see bug 1551241. For now we wallpaper the crash.
return CallState::Continue;
}
bool embedderFrameIsHidden = true;
if (auto* embedderFrame = embedderElement->GetPrimaryFrame()) {
embedderFrameIsHidden = !embedderFrame->StyleVisibility()->IsVisible();
}
bool hidden = newValue || embedderFrameIsHidden;
if (aChild->IsUnderHiddenEmbedderElement() != hidden) {
(void)aChild->SetIsUnderHiddenEmbedderElement(hidden);
}
return CallState::Continue;
};
for (BrowsingContext* child : Children()) {
PropagateToChild(child);
}
if (XRE_IsParentProcess()) {
Canonical()->CallOnTopDescendants(
PropagateToChild,
CanonicalBrowsingContext::TopDescendantKind::ChildrenOnly);
}
}
void BrowsingContext::DidSet(FieldIndex<IDX_ForceOffline>, bool aOldValue) {
const bool newValue = ForceOffline();
if (newValue == aOldValue) {
return;
}
PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
if (RefPtr<WindowContext> windowContext =
aBrowsingContext->GetCurrentWindowContext()) {
if (nsCOMPtr<nsPIDOMWindowInner> window =
windowContext->GetInnerWindow()) {
nsGlobalWindowInner::Cast(window)->FireOfflineStatusEventIfChanged();
}
}
});
}
bool BrowsingContext::IsPopupAllowed() {
for (auto* context = GetCurrentWindowContext(); context;
context = context->GetParentWindowContext()) {
if (context->CanShowPopup()) {
return true;
}
}
return false;
}
/* static */
bool BrowsingContext::ShouldAddEntryForRefresh(
nsIURI* aPreviousURI, const SessionHistoryInfo& aInfo) {
return ShouldAddEntryForRefresh(aPreviousURI, aInfo.GetURI(),
aInfo.HasPostData());
}
/* static */
bool BrowsingContext::ShouldAddEntryForRefresh(nsIURI* aPreviousURI,
nsIURI* aNewURI,
bool aHasPostData) {
if (aHasPostData) {
return true;
}
bool equalsURI = false;
if (aPreviousURI) {
aPreviousURI->Equals(aNewURI, &equalsURI);
}
return !equalsURI;
}
bool BrowsingContext::AddSHEntryWouldIncreaseLength(
SessionHistoryInfo* aCurrentEntry) const {
// nsSHistory::AddEntry and AddNestedSHEntry do a replace load if the current
// entry is marked as transient.
const bool isCurrentTransientEntry =
aCurrentEntry && aCurrentEntry->IsTransient();
// If this is the first entry for an iframe, it would be added to the parent
// entry instead of creating a new top-level entry.
const bool wouldAddToParentEntry = !IsTop() && !aCurrentEntry;
return !isCurrentTransientEntry && !wouldAddToParentEntry;
}
void BrowsingContext::SessionHistoryCommit(
const LoadingSessionHistoryInfo& aInfo, uint32_t aLoadType,
nsIURI* aPreviousURI, SessionHistoryInfo* aPreviousActiveEntry,
bool aCloneEntryChildren, bool aChannelExpired, uint32_t aCacheKey) {
nsID changeID = {};
if (XRE_IsContentProcess()) {
RefPtr<ChildSHistory> rootSH = Top()->GetChildSessionHistory();
if (rootSH) {
if (!aInfo.mLoadIsFromSessionHistory) {
// We try to mimic as closely as possible whether
// CanonicalBrowsingContext::SessionHistoryCommit will increase
// the session history length.
// It is possible that this leads to wrong length temporarily, but
// so would not having these checks.
// The child process does not have access to the current entry, so we
// use the previous active entry as the best approximation. When that's
// not the current entry then the length might be wrong briefly, until
// the parent process commits the actual length.
const bool isReplaceLoad = LOAD_TYPE_HAS_FLAGS(
aLoadType, nsIWebNavigation::LOAD_FLAGS_REPLACE_HISTORY),
isRefreshLoad = LOAD_TYPE_HAS_FLAGS(
aLoadType, nsIWebNavigation::LOAD_FLAGS_IS_REFRESH);
if (!isReplaceLoad &&
AddSHEntryWouldIncreaseLength(aPreviousActiveEntry) &&
ShouldUpdateSessionHistory(aLoadType) &&
(!isRefreshLoad ||
ShouldAddEntryForRefresh(aPreviousURI, aInfo.mInfo))) {
changeID = rootSH->AddPendingHistoryChange();
}
} else {
// History load doesn't change the length, only index.
changeID = rootSH->AddPendingHistoryChange(aInfo.mOffset, 0);
}
}
ContentChild* cc = ContentChild::GetSingleton();
(void)cc->SendHistoryCommit(this, aInfo.mLoadId, changeID, aLoadType,
aCloneEntryChildren, aChannelExpired,
aCacheKey);
} else {
Canonical()->SessionHistoryCommit(aInfo.mLoadId, changeID, aLoadType,
aCloneEntryChildren, aChannelExpired,
aCacheKey);
}
}
void BrowsingContext::SetActiveSessionHistoryEntry(
const Maybe<nsPoint>& aPreviousScrollPos, SessionHistoryInfo* aInfo,
SessionHistoryInfo* aPreviousActiveEntry, uint32_t aLoadType,
uint32_t aUpdatedCacheKey, bool aUpdateLength) {
if (IsTop() &&
!nsDocShell::ShouldAddToSessionHistory(aInfo->GetURI(), nullptr)) {
aInfo->SetTransient();
}
if (XRE_IsContentProcess()) {
// XXX Why we update cache key only in content process case?
if (aUpdatedCacheKey != 0) {
aInfo->SetCacheKey(aUpdatedCacheKey);
}
nsID changeID = {};
if (aUpdateLength) {
RefPtr<ChildSHistory> shistory = Top()->GetChildSessionHistory();
if (shistory) {
// We try to mimic what will happen in
// CanonicalBrowsingContext::SendSetActiveSessionHistoryEntry
if (AddSHEntryWouldIncreaseLength(aPreviousActiveEntry)) {
changeID = shistory->AddPendingHistoryChange();
}
}
}
ContentChild::GetSingleton()->SendSetActiveSessionHistoryEntry(
this, aPreviousScrollPos, *aInfo, aLoadType, aUpdatedCacheKey,
changeID);
} else {
Canonical()->SetActiveSessionHistoryEntry(
aPreviousScrollPos, aInfo, aLoadType, aUpdatedCacheKey, nsID());
}
}
void BrowsingContext::ReplaceActiveSessionHistoryEntry(
SessionHistoryInfo* aInfo) {
if (XRE_IsContentProcess()) {
ContentChild::GetSingleton()->SendReplaceActiveSessionHistoryEntry(this,
*aInfo);
} else {
Canonical()->ReplaceActiveSessionHistoryEntry(aInfo);
}
}
void BrowsingContext::RemoveDynEntriesFromActiveSessionHistoryEntry() {
if (XRE_IsContentProcess()) {
ContentChild::GetSingleton()
->SendRemoveDynEntriesFromActiveSessionHistoryEntry(this);
} else {
Canonical()->RemoveDynEntriesFromActiveSessionHistoryEntry();
}
}
void BrowsingContext::RemoveFromSessionHistory(const nsID& aChangeID) {
if (XRE_IsContentProcess()) {
ContentChild::GetSingleton()->SendRemoveFromSessionHistory(this, aChangeID);
} else {
Canonical()->RemoveFromSessionHistory(aChangeID);
}
}
void BrowsingContext::HistoryGo(
int32_t aOffset, uint64_t aHistoryEpoch, bool aRequireUserInteraction,
bool aUserActivation, std::function<void(Maybe<int32_t>&&)>&& aResolver) {
// We always pass checkForCancelation as true here, since we'll never call
// HistoryGo in a context where we beforehand know that we want to skip
// onbeforeunload or onnavigate.
bool checkForCancelation = true;
if (XRE_IsContentProcess()) {
ContentChild::GetSingleton()->SendHistoryGo(
this, aOffset, aHistoryEpoch, aRequireUserInteraction, aUserActivation,
checkForCancelation, std::move(aResolver),
[](mozilla::ipc::
ResponseRejectReason) { /* FIXME Is ignoring this fine? */ });
} else {
RefPtr<CanonicalBrowsingContext> self = Canonical();
aResolver(self->HistoryGo(aOffset, aHistoryEpoch, aRequireUserInteraction,
aUserActivation, checkForCancelation,
self->GetContentParent()
? Some(self->GetContentParent()->ChildID())
: Nothing()));
}
}
void BrowsingContext::NavigationTraverse(
const nsID& aKey, uint64_t aHistoryEpoch, bool aUserActivation,
bool aCheckForCancelation, std::function<void(nsresult)>&& aResolver) {
if (XRE_IsContentProcess()) {
ContentChild::GetSingleton()->SendNavigationTraverse(
this, aKey, aHistoryEpoch, aUserActivation, aCheckForCancelation,
std::move(aResolver),
[](mozilla::ipc::
ResponseRejectReason) { /* FIXME Is ignoring this fine? */ });
} else {
RefPtr<CanonicalBrowsingContext> self = Canonical();
self->NavigationTraverse(
aKey, aHistoryEpoch, aUserActivation, aCheckForCancelation,
self->GetContentParent() ? Some(self->GetContentParent()->ChildID())
: Nothing(),
std::move(aResolver));
}
}
void BrowsingContext::SetChildSHistory(ChildSHistory* aChildSHistory) {
mChildSessionHistory = aChildSHistory;
mChildSessionHistory->SetBrowsingContext(this);
mFields.SetWithoutSyncing<IDX_HasSessionHistory>(true);
}
bool BrowsingContext::ShouldUpdateSessionHistory(uint32_t aLoadType) {
// We don't update session history on reload unless we're loading
// an iframe in shift-reload case.
return nsDocShell::ShouldUpdateGlobalHistory(aLoadType) &&
(!(aLoadType & nsIDocShell::LOAD_CMD_RELOAD) ||
(IsForceReloadType(aLoadType) && IsSubframe()));
}
nsresult BrowsingContext::CheckNavigationRateLimit(CallerType aCallerType) {
// We only rate limit non system callers
if (aCallerType == CallerType::System) {
return NS_OK;
}
// Fetch rate limiting preferences
uint32_t limitCount = StaticPrefs::dom_navigation_navigationRateLimit_count();
uint32_t timeSpanSeconds =
StaticPrefs::dom_navigation_navigationRateLimit_timespan();
// Disable throttling if either of the preferences is set to 0.
if (limitCount == 0 || timeSpanSeconds == 0) {
return NS_OK;
}
TimeDuration throttleSpan = TimeDuration::FromSeconds(timeSpanSeconds);
if (mNavigationRateLimitSpanStart.IsNull() ||
((TimeStamp::Now() - mNavigationRateLimitSpanStart) > throttleSpan)) {
// Initial call or timespan exceeded, reset counter and timespan.
mNavigationRateLimitSpanStart = TimeStamp::Now();
mNavigationRateLimitCount = 1;
return NS_OK;
}
if (mNavigationRateLimitCount >= limitCount) {
// Rate limit reached
Document* doc = GetDocument();
if (doc) {
nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, "DOM"_ns, doc,
nsContentUtils::eDOM_PROPERTIES,
"LocChangeFloodingPrevented");
}
return NS_ERROR_DOM_SECURITY_ERR;
}
mNavigationRateLimitCount++;
return NS_OK;
}
void BrowsingContext::ResetNavigationRateLimit() {
// Resetting the timestamp object will cause the check function to
// init again and reset the rate limit.
mNavigationRateLimitSpanStart = TimeStamp();
}
void BrowsingContext::LocationCreated(dom::Location* aLocation) {
MOZ_ASSERT(!aLocation->isInList());
mLocations.insertBack(aLocation);
}
void BrowsingContext::ClearCachedValuesOfLocations() {
for (dom::Location* loc = mLocations.getFirst(); loc; loc = loc->getNext()) {
loc->ClearCachedValues();
}
}
// https://html.spec.whatwg.org/multipage/interaction.html#consume-history-action-user-activation
// Step 3 onward
void BrowsingContext::ConsumeHistoryActivation() {
// 3. Let navigables be the inclusive descendant navigables of top's active
// document.
// 4. Let windows be the list of Window objects constructed by taking the
// active window of each item in navigables.
PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
RefPtr<WindowContext> windowContext =
aBrowsingContext->GetCurrentWindowContext();
// 5. For each window in windows, set window's last history-action
// activation timestamp to window's last activation timestamp.
if (aBrowsingContext->IsInProcess() && windowContext &&
windowContext->GetUserActivationState() ==
UserActivation::State::FullActivated) {
windowContext->UpdateLastHistoryActivation();
}
});
}
void BrowsingContext::SynchronizeNavigationAPIState(
nsIStructuredCloneContainer* aState) {
if (!aState) {
return;
}
if (XRE_IsContentProcess()) {
ClonedMessageData data;
DebugOnly<bool> result = static_cast<nsStructuredCloneContainer*>(aState)
->BuildClonedMessageData(data);
MOZ_ASSERT(result);
MOZ_ASSERT(ContentChild::GetSingleton());
ContentChild::GetSingleton()->SendSynchronizeNavigationAPIState(this, data);
} else {
Canonical()->SynchronizeNavigationAPIState(aState);
}
}
} // namespace dom
} // namespace mozilla
namespace IPC {
using mozilla::dom::BrowsingContext;
using mozilla::dom::MaybeDiscarded;
void ParamTraits<MaybeDiscarded<BrowsingContext>>::Write(
IPC::MessageWriter* aWriter,
const MaybeDiscarded<BrowsingContext>& aParam) {
MOZ_DIAGNOSTIC_ASSERT(!aParam.GetMaybeDiscarded() ||
aParam.GetMaybeDiscarded()->EverAttached());
uint64_t id = aParam.ContextId();
WriteParam(aWriter, id);
}
bool ParamTraits<MaybeDiscarded<BrowsingContext>>::Read(
IPC::MessageReader* aReader, MaybeDiscarded<BrowsingContext>* aResult) {
uint64_t id = 0;
if (!ReadParam(aReader, &id)) {
return false;
}
if (id == 0) {
*aResult = nullptr;
} else if (RefPtr<BrowsingContext> bc = BrowsingContext::Get(id)) {
*aResult = std::move(bc);
} else {
aResult->SetDiscarded(id);
}
return true;
}
void ParamTraits<BrowsingContext::IPCInitializer>::Write(
IPC::MessageWriter* aWriter, const paramType& aInit) {
// Write actor ID parameters.
WriteParam(aWriter, aInit.mId);
WriteParam(aWriter, aInit.mParentId);
WriteParam(aWriter, aInit.mWindowless);
WriteParam(aWriter, aInit.mUseRemoteTabs);
WriteParam(aWriter, aInit.mUseRemoteSubframes);
WriteParam(aWriter, aInit.mCreatedDynamically);
WriteParam(aWriter, aInit.mChildOffset);
WriteParam(aWriter, aInit.mOriginAttributes);
WriteParam(aWriter, aInit.mRequestContextId);
WriteParam(aWriter, aInit.mSessionHistoryIndex);
WriteParam(aWriter, aInit.mSessionHistoryCount);
WriteParam(aWriter, aInit.mFields);
}
bool ParamTraits<BrowsingContext::IPCInitializer>::Read(
IPC::MessageReader* aReader, paramType* aInit) {
// Read actor ID parameters.
return ReadParam(aReader, &aInit->mId) &&
ReadParam(aReader, &aInit->mParentId) &&
ReadParam(aReader, &aInit->mWindowless) &&
ReadParam(aReader, &aInit->mUseRemoteTabs) &&
ReadParam(aReader, &aInit->mUseRemoteSubframes) &&
ReadParam(aReader, &aInit->mCreatedDynamically) &&
ReadParam(aReader, &aInit->mChildOffset) &&
ReadParam(aReader, &aInit->mOriginAttributes) &&
ReadParam(aReader, &aInit->mRequestContextId) &&
ReadParam(aReader, &aInit->mSessionHistoryIndex) &&
ReadParam(aReader, &aInit->mSessionHistoryCount) &&
ReadParam(aReader, &aInit->mFields);
}
template struct ParamTraits<BrowsingContext::BaseTransaction>;
} // namespace IPC
|