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 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et 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/. */
// HttpLog.h should generally be included first
#include "mozilla/net/HttpBaseChannel.h"
#include <algorithm>
#include <utility>
#include "HttpBaseChannel.h"
#include "HttpLog.h"
#include "LoadInfo.h"
#include "ReferrerInfo.h"
#include "mozIRemoteLazyInputStream.h"
#include "mozIThirdPartyUtil.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/AntiTrackingUtils.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/CompactPair.h"
#include "mozilla/ConsoleReportCollector.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/InputStreamLengthHelper.h"
#include "mozilla/Mutex.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/PermissionManager.h"
#include "mozilla/Components.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_fission.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/glean/NetwerkProtocolHttpMetrics.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Tokenizer.h"
#include "mozilla/browser/NimbusFeatures.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/FetchPriority.h"
#include "mozilla/dom/LoadURIOptionsBinding.h"
#include "mozilla/dom/nsHTTPSOnlyUtils.h"
#include "mozilla/dom/nsMixedContentBlocker.h"
#include "mozilla/dom/Performance.h"
#include "mozilla/dom/PerformanceStorage.h"
#include "mozilla/dom/PolicyContainer.h"
#include "mozilla/dom/ProcessIsolation.h"
#include "mozilla/dom/RequestBinding.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/net/OpaqueResponseUtils.h"
#include "mozilla/net/UrlClassifierCommon.h"
#include "mozilla/net/UrlClassifierFeatureFactory.h"
#include "nsBufferedStreams.h"
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include "nsContentSecurityManager.h"
#include "nsContentSecurityUtils.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsEscape.h"
#include "nsGlobalWindowInner.h"
#include "nsGlobalWindowOuter.h"
#include "nsHttpChannel.h"
#include "nsHTTPCompressConv.h"
#include "nsHttpHandler.h"
#include "nsICacheInfoChannel.h"
#include "nsICachingChannel.h"
#include "nsIChannelEventSink.h"
#include "nsIConsoleService.h"
#include "nsIContentPolicy.h"
#include "nsICookieService.h"
#include "nsIDOMWindowUtils.h"
#include "nsIDocShell.h"
#include "nsIDNSService.h"
#include "nsIEncodedChannel.h"
#include "nsIHttpHeaderVisitor.h"
#include "nsILoadGroupChild.h"
#include "nsIMIMEInputStream.h"
#include "nsIMultiplexInputStream.h"
#include "nsIMutableArray.h"
#include "nsINetworkInterceptController.h"
#include "nsIObserverService.h"
#include "nsIPrincipal.h"
#include "nsIProtocolProxyService.h"
#include "nsIScriptError.h"
#include "nsIScriptSecurityManager.h"
#include "nsISecurityConsoleMessage.h"
#include "nsISeekableStream.h"
#include "nsIStorageStream.h"
#include "nsIStreamConverterService.h"
#include "nsITimedChannel.h"
#include "nsITransportSecurityInfo.h"
#include "nsIURIMutator.h"
#include "nsMimeTypes.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsPIDOMWindow.h"
#include "nsProxyRelease.h"
#include "nsReadableUtils.h"
#include "nsRedirectHistoryEntry.h"
#include "nsServerTiming.h"
#include "nsStreamListenerWrapper.h"
#include "nsStreamUtils.h"
#include "nsString.h"
#include "nsThreadUtils.h"
#include "nsURLHelper.h"
#include "mozilla/RemoteLazyInputStreamChild.h"
#include "mozilla/net/SFVService.h"
#include "mozilla/dom/ContentChild.h"
#include "nsQueryObject.h"
using mozilla::dom::ForceMediaDocument;
using mozilla::dom::RequestMode;
#define LOGORB(msg, ...) \
MOZ_LOG(GetORBLog(), LogLevel::Debug, \
("%s: %p " msg, __func__, this, ##__VA_ARGS__))
namespace mozilla {
namespace net {
static bool IsHeaderBlacklistedForRedirectCopy(nsHttpAtom const& aHeader) {
// IMPORTANT: keep this list ASCII-code sorted
static nsHttpAtomLiteral const* blackList[] = {
&nsHttp::Accept,
&nsHttp::Accept_Encoding,
&nsHttp::Accept_Language,
&nsHttp::Alternate_Service_Used,
&nsHttp::Authentication,
&nsHttp::Authorization,
&nsHttp::Connection,
&nsHttp::Content_Length,
&nsHttp::Cookie,
&nsHttp::Host,
&nsHttp::If,
&nsHttp::If_Match,
&nsHttp::If_Modified_Since,
&nsHttp::If_None_Match,
&nsHttp::If_None_Match_Any,
&nsHttp::If_Range,
&nsHttp::If_Unmodified_Since,
&nsHttp::Proxy_Authenticate,
&nsHttp::Proxy_Authorization,
&nsHttp::Range,
&nsHttp::TE,
&nsHttp::Transfer_Encoding,
&nsHttp::Upgrade,
&nsHttp::User_Agent,
&nsHttp::WWW_Authenticate};
class HttpAtomComparator {
nsHttpAtom const& mTarget;
public:
explicit HttpAtomComparator(nsHttpAtom const& aTarget) : mTarget(aTarget) {}
int operator()(nsHttpAtom const* aVal) const {
if (mTarget == *aVal) {
return 0;
}
return strcmp(mTarget.get(), aVal->get());
}
int operator()(nsHttpAtomLiteral const* aVal) const {
if (mTarget == *aVal) {
return 0;
}
return strcmp(mTarget.get(), aVal->get());
}
};
size_t unused;
return BinarySearchIf(blackList, 0, std::size(blackList),
HttpAtomComparator(aHeader), &unused);
}
class AddHeadersToChannelVisitor final : public nsIHttpHeaderVisitor {
public:
NS_DECL_ISUPPORTS
explicit AddHeadersToChannelVisitor(nsIHttpChannel* aChannel)
: mChannel(aChannel) {}
NS_IMETHOD VisitHeader(const nsACString& aHeader,
const nsACString& aValue) override {
nsHttpAtom atom = nsHttp::ResolveAtom(aHeader);
if (!IsHeaderBlacklistedForRedirectCopy(atom)) {
DebugOnly<nsresult> rv =
mChannel->SetRequestHeader(aHeader, aValue, false);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
return NS_OK;
}
private:
~AddHeadersToChannelVisitor() = default;
nsCOMPtr<nsIHttpChannel> mChannel;
};
NS_IMPL_ISUPPORTS(AddHeadersToChannelVisitor, nsIHttpHeaderVisitor)
static OpaqueResponseFilterFetch ConfiguredFilterFetchResponseBehaviour() {
uint32_t pref = StaticPrefs::
browser_opaqueResponseBlocking_filterFetchResponse_DoNotUseDirectly();
if (NS_WARN_IF(pref >
static_cast<uint32_t>(OpaqueResponseFilterFetch::All))) {
return OpaqueResponseFilterFetch::All;
}
return static_cast<OpaqueResponseFilterFetch>(pref);
}
HttpBaseChannel::HttpBaseChannel()
: mReportCollector(new ConsoleReportCollector()),
mHttpHandler(gHttpHandler),
mClassOfService(0, false),
mRequestMode(RequestMode::No_cors),
mRedirectionLimit(gHttpHandler->RedirectionLimit()),
mCachedOpaqueResponseBlockingPref(
StaticPrefs::browser_opaqueResponseBlocking()) {
StoreApplyConversion(true);
StoreAllowSTS(true);
StoreTracingEnabled(true);
StoreReportTiming(true);
StoreAllowSpdy(true);
StoreAllowHttp3(true);
StoreAllowAltSvc(true);
StoreResponseTimeoutEnabled(true);
StoreAllRedirectsSameOrigin(true);
StoreAllRedirectsPassTimingAllowCheck(true);
StoreUpgradableToSecure(true);
StoreIsUserAgentHeaderModified(false);
this->mSelfAddr.inet = {};
this->mPeerAddr.inet = {};
LOG(("Creating HttpBaseChannel @%p\n", this));
// Subfields of unions cannot be targeted in an initializer list.
#ifdef MOZ_VALGRIND
// Zero the entire unions so that Valgrind doesn't complain when we send them
// to another process.
memset(&mSelfAddr, 0, sizeof(NetAddr));
memset(&mPeerAddr, 0, sizeof(NetAddr));
#endif
mSelfAddr.raw.family = PR_AF_UNSPEC;
mPeerAddr.raw.family = PR_AF_UNSPEC;
}
HttpBaseChannel::~HttpBaseChannel() {
LOG(("Destroying HttpBaseChannel @%p\n", this));
// Make sure we don't leak
CleanRedirectCacheChainIfNecessary();
ReleaseMainThreadOnlyReferences();
}
namespace { // anon
class NonTailRemover : public nsISupports {
NS_DECL_THREADSAFE_ISUPPORTS
explicit NonTailRemover(nsIRequestContext* rc) : mRequestContext(rc) {}
private:
virtual ~NonTailRemover() {
MOZ_ASSERT(NS_IsMainThread());
mRequestContext->RemoveNonTailRequest();
}
nsCOMPtr<nsIRequestContext> mRequestContext;
};
NS_IMPL_ISUPPORTS0(NonTailRemover)
} // namespace
void HttpBaseChannel::ReleaseMainThreadOnlyReferences() {
if (NS_IsMainThread()) {
// Already on main thread, let dtor to
// take care of releasing references
RemoveAsNonTailRequest();
return;
}
nsTArray<nsCOMPtr<nsISupports>> arrayToRelease;
arrayToRelease.AppendElement(mLoadGroup.forget());
arrayToRelease.AppendElement(mLoadInfo.forget());
arrayToRelease.AppendElement(mCallbacks.forget());
arrayToRelease.AppendElement(mProgressSink.forget());
arrayToRelease.AppendElement(mPrincipal.forget());
arrayToRelease.AppendElement(mListener.forget());
arrayToRelease.AppendElement(mCompressListener.forget());
arrayToRelease.AppendElement(mORB.forget());
if (LoadAddedAsNonTailRequest()) {
// RemoveNonTailRequest() on our request context must be called on the main
// thread
MOZ_RELEASE_ASSERT(mRequestContext,
"Someone released rc or set flags w/o having it?");
nsCOMPtr<nsISupports> nonTailRemover(new NonTailRemover(mRequestContext));
arrayToRelease.AppendElement(nonTailRemover.forget());
}
NS_DispatchToMainThread(new ProxyReleaseRunnable(std::move(arrayToRelease)));
}
void HttpBaseChannel::AddClassificationFlags(uint32_t aClassificationFlags,
bool aIsThirdParty) {
LOG(
("HttpBaseChannel::AddClassificationFlags classificationFlags=%d "
"thirdparty=%d %p",
aClassificationFlags, static_cast<int>(aIsThirdParty), this));
if (aIsThirdParty) {
mThirdPartyClassificationFlags |= aClassificationFlags;
} else {
mFirstPartyClassificationFlags |= aClassificationFlags;
}
}
static bool isSecureOrTrustworthyURL(nsIURI* aURI) {
return aURI->SchemeIs("https") ||
(StaticPrefs::network_http_encoding_trustworthy_is_https() &&
nsMixedContentBlocker::IsPotentiallyTrustworthyLoopbackURL(aURI));
}
nsresult HttpBaseChannel::Init(nsIURI* aURI, uint32_t aCaps,
nsProxyInfo* aProxyInfo,
uint32_t aProxyResolveFlags, nsIURI* aProxyURI,
uint64_t aChannelId, nsILoadInfo* aLoadInfo) {
LOG1(("HttpBaseChannel::Init [this=%p]\n", this));
MOZ_ASSERT(aURI, "null uri");
mURI = aURI;
mOriginalURI = aURI;
mDocumentURI = nullptr;
mCaps = aCaps;
mProxyResolveFlags = aProxyResolveFlags;
mProxyURI = aProxyURI;
mChannelId = aChannelId;
mLoadInfo = aLoadInfo;
// Construct connection info object
nsAutoCString host;
int32_t port = -1;
bool isHTTPS = isSecureOrTrustworthyURL(mURI);
nsresult rv = mURI->GetAsciiHost(host);
if (NS_FAILED(rv)) return rv;
// Reject the URL if it doesn't specify a host
if (host.IsEmpty()) return NS_ERROR_MALFORMED_URI;
rv = mURI->GetPort(&port);
if (NS_FAILED(rv)) return rv;
LOG1(("host=%s port=%d\n", host.get(), port));
rv = mURI->GetAsciiSpec(mSpec);
if (NS_FAILED(rv)) return rv;
LOG1(("uri=%s\n", mSpec.get()));
// Assert default request method
MOZ_ASSERT(mRequestHead.EqualsMethod(nsHttpRequestHead::kMethod_Get));
// Set request headers
nsAutoCString hostLine;
rv = nsHttpHandler::GenerateHostPort(host, port, hostLine);
if (NS_FAILED(rv)) return rv;
rv = mRequestHead.SetHeader(nsHttp::Host, hostLine);
if (NS_FAILED(rv)) return rv;
// Override the Accept header if a specific MediaDocument kind is forced.
ExtContentPolicy contentPolicyType =
mLoadInfo->GetExternalContentPolicyType();
// TRRLoadInfo doesn't implement GetForceMediaDocument.
ForceMediaDocument forceMediaDocument;
if (NS_SUCCEEDED(mLoadInfo->GetForceMediaDocument(&forceMediaDocument))) {
switch (forceMediaDocument) {
case ForceMediaDocument::Image:
contentPolicyType = ExtContentPolicy::TYPE_IMAGE;
break;
case ForceMediaDocument::Video:
contentPolicyType = ExtContentPolicy::TYPE_MEDIA;
break;
case ForceMediaDocument::None:
break;
}
}
RefPtr<mozilla::dom::BrowsingContext> browsingContext;
mLoadInfo->GetBrowsingContext(getter_AddRefs(browsingContext));
const nsCString& languageOverride =
browsingContext ? browsingContext->Top()->GetLanguageOverride()
: EmptyCString();
rv = gHttpHandler->AddStandardRequestHeaders(
&mRequestHead, aURI, isHTTPS, contentPolicyType,
nsContentUtils::ShouldResistFingerprinting(this,
RFPTarget::HttpUserAgent),
languageOverride);
if (NS_FAILED(rv)) return rv;
nsAutoCString type;
if (aProxyInfo && NS_SUCCEEDED(aProxyInfo->GetType(type)) &&
!type.EqualsLiteral("unknown")) {
mProxyInfo = aProxyInfo;
}
mCurrentThread = GetCurrentSerialEventTarget();
return rv;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsISupports
//-----------------------------------------------------------------------------
NS_IMPL_ADDREF(HttpBaseChannel)
NS_IMPL_RELEASE(HttpBaseChannel)
NS_INTERFACE_MAP_BEGIN(HttpBaseChannel)
NS_INTERFACE_MAP_ENTRY(nsIRequest)
NS_INTERFACE_MAP_ENTRY(nsIChannel)
NS_INTERFACE_MAP_ENTRY(nsIIdentChannel)
NS_INTERFACE_MAP_ENTRY(nsIEncodedChannel)
NS_INTERFACE_MAP_ENTRY(nsIHttpChannel)
NS_INTERFACE_MAP_ENTRY(nsIHttpChannelInternal)
NS_INTERFACE_MAP_ENTRY(nsIForcePendingChannel)
NS_INTERFACE_MAP_ENTRY(nsIUploadChannel)
NS_INTERFACE_MAP_ENTRY(nsIFormPOSTActionChannel)
NS_INTERFACE_MAP_ENTRY(nsIUploadChannel2)
NS_INTERFACE_MAP_ENTRY(nsISupportsPriority)
NS_INTERFACE_MAP_ENTRY(nsITraceableChannel)
NS_INTERFACE_MAP_ENTRY(nsIPrivateBrowsingChannel)
NS_INTERFACE_MAP_ENTRY(nsITimedChannel)
NS_INTERFACE_MAP_ENTRY(nsIConsoleReportCollector)
NS_INTERFACE_MAP_ENTRY(nsIThrottledInputChannel)
NS_INTERFACE_MAP_ENTRY(nsIClassifiedChannel)
NS_INTERFACE_MAP_ENTRY_CONCRETE(HttpBaseChannel)
NS_INTERFACE_MAP_END_INHERITING(nsHashPropertyBag)
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIRequest
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetName(nsACString& aName) {
aName = mSpec;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::IsPending(bool* aIsPending) {
NS_ENSURE_ARG_POINTER(aIsPending);
*aIsPending = LoadIsPending() || LoadForcePending();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetStatus(nsresult* aStatus) {
NS_ENSURE_ARG_POINTER(aStatus);
*aStatus = mStatus;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLoadGroup(nsILoadGroup** aLoadGroup) {
NS_ENSURE_ARG_POINTER(aLoadGroup);
*aLoadGroup = do_AddRef(mLoadGroup).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetLoadGroup(nsILoadGroup* aLoadGroup) {
MOZ_ASSERT(NS_IsMainThread(), "Should only be called on the main thread.");
if (!CanSetLoadGroup(aLoadGroup)) {
return NS_ERROR_FAILURE;
}
mLoadGroup = aLoadGroup;
mProgressSink = nullptr;
UpdatePrivateBrowsing();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLoadFlags(nsLoadFlags* aLoadFlags) {
NS_ENSURE_ARG_POINTER(aLoadFlags);
*aLoadFlags = mLoadFlags;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetLoadFlags(nsLoadFlags aLoadFlags) {
mLoadFlags = aLoadFlags;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetTRRMode(nsIRequest::TRRMode* aTRRMode) {
if (!LoadIsOCSP()) {
return GetTRRModeImpl(aTRRMode);
}
nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
nsIDNSService::ResolverMode trrMode = nsIDNSService::MODE_NATIVEONLY;
// If this is an OCSP channel, and the global TRR mode is TRR_ONLY (3)
// then we set the mode for this channel as TRR_DISABLED_MODE.
// We do this to prevent a TRR service channel's OCSP validation from
// blocking DNS resolution completely.
if (dns && NS_SUCCEEDED(dns->GetCurrentTrrMode(&trrMode)) &&
trrMode == nsIDNSService::MODE_TRRONLY) {
*aTRRMode = nsIRequest::TRR_DISABLED_MODE;
return NS_OK;
}
return GetTRRModeImpl(aTRRMode);
}
NS_IMETHODIMP
HttpBaseChannel::SetTRRMode(nsIRequest::TRRMode aTRRMode) {
return SetTRRModeImpl(aTRRMode);
}
NS_IMETHODIMP
HttpBaseChannel::SetDocshellUserAgentOverride() {
RefPtr<dom::BrowsingContext> bc;
MOZ_ALWAYS_SUCCEEDS(mLoadInfo->GetBrowsingContext(getter_AddRefs(bc)));
if (!bc) {
return NS_OK;
}
nsAutoString customUserAgent;
bc->GetCustomUserAgent(customUserAgent);
if (customUserAgent.IsEmpty() || customUserAgent.IsVoid()) {
return NS_OK;
}
NS_ConvertUTF16toUTF8 utf8CustomUserAgent(customUserAgent);
nsresult rv = SetRequestHeaderInternal(
"User-Agent"_ns, utf8CustomUserAgent, false,
nsHttpHeaderArray::eVarietyRequestEnforceDefault);
if (NS_FAILED(rv)) {
return rv;
}
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetOriginalURI(nsIURI** aOriginalURI) {
NS_ENSURE_ARG_POINTER(aOriginalURI);
*aOriginalURI = do_AddRef(mOriginalURI).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetOriginalURI(nsIURI* aOriginalURI) {
ENSURE_CALLED_BEFORE_CONNECT();
NS_ENSURE_ARG_POINTER(aOriginalURI);
mOriginalURI = aOriginalURI;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetURI(nsIURI** aURI) {
NS_ENSURE_ARG_POINTER(aURI);
*aURI = do_AddRef(mURI).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetOwner(nsISupports** aOwner) {
NS_ENSURE_ARG_POINTER(aOwner);
*aOwner = do_AddRef(mOwner).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetOwner(nsISupports* aOwner) {
mOwner = aOwner;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetLoadInfo(nsILoadInfo* aLoadInfo) {
MOZ_RELEASE_ASSERT(aLoadInfo, "loadinfo can't be null");
mLoadInfo = aLoadInfo;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLoadInfo(nsILoadInfo** aLoadInfo) {
*aLoadInfo = do_AddRef(mLoadInfo).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsDocument(bool* aIsDocument) {
return NS_GetIsDocumentChannel(this, aIsDocument);
}
NS_IMETHODIMP
HttpBaseChannel::GetNotificationCallbacks(nsIInterfaceRequestor** aCallbacks) {
*aCallbacks = do_AddRef(mCallbacks).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aCallbacks) {
MOZ_ASSERT(NS_IsMainThread(), "Should only be called on the main thread.");
if (!CanSetCallbacks(aCallbacks)) {
return NS_ERROR_FAILURE;
}
mCallbacks = aCallbacks;
mProgressSink = nullptr;
UpdatePrivateBrowsing();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetContentType(nsACString& aContentType) {
if (!mResponseHead) {
aContentType.Truncate();
return NS_ERROR_NOT_AVAILABLE;
}
mResponseHead->ContentType(aContentType);
if (!aContentType.IsEmpty()) {
return NS_OK;
}
aContentType.AssignLiteral(UNKNOWN_CONTENT_TYPE);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetContentType(const nsACString& aContentType) {
if (mListener || LoadWasOpened() || mDummyChannelForCachedResource) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
nsAutoCString contentTypeBuf, charsetBuf;
bool hadCharset;
net_ParseContentType(aContentType, contentTypeBuf, charsetBuf, &hadCharset);
mResponseHead->SetContentType(contentTypeBuf);
// take care not to stomp on an existing charset
if (hadCharset) mResponseHead->SetContentCharset(charsetBuf);
} else {
// We are being given a content-type hint.
bool dummy;
net_ParseContentType(aContentType, mContentTypeHint, mContentCharsetHint,
&dummy);
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetContentCharset(nsACString& aContentCharset) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
mResponseHead->ContentCharset(aContentCharset);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetContentCharset(const nsACString& aContentCharset) {
if (mListener) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
mResponseHead->SetContentCharset(aContentCharset);
} else {
// Charset hint
mContentCharsetHint = aContentCharset;
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetContentDisposition(uint32_t* aContentDisposition) {
if (mLoadInfo->GetForceMediaDocument() != ForceMediaDocument::None) {
*aContentDisposition = nsIChannel::DISPOSITION_FORCE_INLINE;
return NS_OK;
}
// See bug 1658877. If mContentDispositionHint is already
// DISPOSITION_ATTACHMENT, it means this channel is created from a
// download attribute. In this case, we should prefer the value from the
// download attribute rather than the value in content disposition header.
// DISPOSITION_FORCE_INLINE is used to explicitly set inline, used by
// the pdf reader when loading a attachment pdf without having to
// download it.
if (mContentDispositionHint == nsIChannel::DISPOSITION_ATTACHMENT ||
mContentDispositionHint == nsIChannel::DISPOSITION_FORCE_INLINE) {
*aContentDisposition = mContentDispositionHint;
return NS_OK;
}
nsresult rv;
nsCString header;
rv = GetContentDispositionHeader(header);
if (NS_FAILED(rv)) {
if (mContentDispositionHint == UINT32_MAX) return rv;
*aContentDisposition = mContentDispositionHint;
return NS_OK;
}
*aContentDisposition = NS_GetContentDispositionFromHeader(header, this);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetContentDisposition(uint32_t aContentDisposition) {
mContentDispositionHint = aContentDisposition;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetContentDispositionFilename(
nsAString& aContentDispositionFilename) {
aContentDispositionFilename.Truncate();
nsresult rv;
nsCString header;
rv = GetContentDispositionHeader(header);
if (NS_SUCCEEDED(rv)) {
rv = NS_GetFilenameFromDisposition(aContentDispositionFilename, header);
}
// If we failed to get the filename from header, we should use
// mContentDispositionFilename, since mContentDispositionFilename is set from
// the download attribute.
if (NS_FAILED(rv)) {
if (!mContentDispositionFilename) {
return rv;
}
aContentDispositionFilename = *mContentDispositionFilename;
return NS_OK;
}
return rv;
}
NS_IMETHODIMP
HttpBaseChannel::SetContentDispositionFilename(
const nsAString& aContentDispositionFilename) {
mContentDispositionFilename =
MakeUnique<nsString>(aContentDispositionFilename);
// For safety reasons ensure the filename doesn't contain null characters and
// replace them with underscores. We may later pass the extension to system
// MIME APIs that expect null terminated strings.
mContentDispositionFilename->ReplaceChar(char16_t(0), '_');
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetContentDispositionHeader(
nsACString& aContentDispositionHeader) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
nsresult rv = mResponseHead->GetHeader(nsHttp::Content_Disposition,
aContentDispositionHeader);
if (NS_FAILED(rv) || aContentDispositionHeader.IsEmpty()) {
return NS_ERROR_NOT_AVAILABLE;
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetContentLength(int64_t* aContentLength) {
NS_ENSURE_ARG_POINTER(aContentLength);
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
if (LoadDeliveringAltData()) {
MOZ_ASSERT(!mAvailableCachedAltDataType.IsEmpty());
*aContentLength = mAltDataLength;
return NS_OK;
}
*aContentLength = mResponseHead->ContentLength();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetContentLength(int64_t value) {
if (!mDummyChannelForCachedResource) {
MOZ_ASSERT_UNREACHABLE("HttpBaseChannel::SetContentLength");
return NS_ERROR_NOT_IMPLEMENTED;
}
MOZ_ASSERT(mResponseHead);
mResponseHead->SetContentLength(value);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::Open(nsIInputStream** aStream) {
if (!gHttpHandler->Active()) {
LOG(("HttpBaseChannel::Open after HTTP shutdown..."));
return NS_ERROR_NOT_AVAILABLE;
}
nsCOMPtr<nsIStreamListener> listener;
nsresult rv =
nsContentSecurityManager::doContentSecurityCheck(this, listener);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(!LoadWasOpened(), NS_ERROR_IN_PROGRESS);
if (!gHttpHandler->Active()) {
LOG(("HttpBaseChannel::Open after HTTP shutdown..."));
return NS_ERROR_NOT_AVAILABLE;
}
return NS_ImplementChannelOpen(this, aStream);
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIUploadChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetUploadStream(nsIInputStream** stream) {
NS_ENSURE_ARG_POINTER(stream);
*stream = do_AddRef(mUploadStream).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetUploadStream(nsIInputStream* stream,
const nsACString& contentTypeArg,
int64_t contentLength) {
// NOTE: for backwards compatibility and for compatibility with old style
// plugins, |stream| may include headers, specifically Content-Type and
// Content-Length headers. in this case, |contentType| and |contentLength|
// would be unspecified. this is traditionally the case of a POST request,
// and so we select POST as the request method if contentType and
// contentLength are unspecified.
if (stream) {
nsAutoCString method;
bool hasHeaders = false;
// This method and ExplicitSetUploadStream mean different things by "empty
// content type string". This method means "no header", but
// ExplicitSetUploadStream means "header with empty value". So we have to
// massage the contentType argument into the form ExplicitSetUploadStream
// expects.
nsCOMPtr<nsIMIMEInputStream> mimeStream;
nsCString contentType(contentTypeArg);
if (contentType.IsEmpty()) {
contentType.SetIsVoid(true);
method = "POST"_ns;
// MIME streams are a special case, and include headers which need to be
// copied to the channel.
mimeStream = do_QueryInterface(stream);
if (mimeStream) {
// Copy non-origin related headers to the channel.
nsCOMPtr<nsIHttpHeaderVisitor> visitor =
new AddHeadersToChannelVisitor(this);
mimeStream->VisitHeaders(visitor);
return ExplicitSetUploadStream(stream, contentType, contentLength,
method, hasHeaders);
}
hasHeaders = true;
} else {
method = "PUT"_ns;
MOZ_ASSERT(
NS_FAILED(CallQueryInterface(stream, getter_AddRefs(mimeStream))),
"nsIMIMEInputStream should not be set with an explicit content type");
}
return ExplicitSetUploadStream(stream, contentType, contentLength, method,
hasHeaders);
}
// if stream is null, ExplicitSetUploadStream returns error.
// So we need special case for GET method.
StoreUploadStreamHasHeaders(false);
SetRequestMethod("GET"_ns); // revert to GET request
mUploadStream = nullptr;
return NS_OK;
}
namespace {
class MIMEHeaderCopyVisitor final : public nsIHttpHeaderVisitor {
public:
explicit MIMEHeaderCopyVisitor(nsIMIMEInputStream* aDest) : mDest(aDest) {}
NS_DECL_ISUPPORTS
NS_IMETHOD VisitHeader(const nsACString& aName,
const nsACString& aValue) override {
return mDest->AddHeader(PromiseFlatCString(aName).get(),
PromiseFlatCString(aValue).get());
}
private:
~MIMEHeaderCopyVisitor() = default;
nsCOMPtr<nsIMIMEInputStream> mDest;
};
NS_IMPL_ISUPPORTS(MIMEHeaderCopyVisitor, nsIHttpHeaderVisitor)
static void NormalizeCopyComplete(void* aClosure, nsresult aStatus) {
#ifdef DEBUG
// Called on the STS thread by NS_AsyncCopy
nsCOMPtr<nsIEventTarget> sts =
do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
bool result = false;
sts->IsOnCurrentThread(&result);
MOZ_ASSERT(result, "Should only be called on the STS thread.");
#endif
RefPtr<GenericPromise::Private> ready =
already_AddRefed(static_cast<GenericPromise::Private*>(aClosure));
if (NS_SUCCEEDED(aStatus)) {
ready->Resolve(true, __func__);
} else {
ready->Reject(aStatus, __func__);
}
}
// Normalize the upload stream for a HTTP channel, so that is one of the
// expected and compatible types. Components like WebExtensions and DevTools
// expect that upload streams in the parent process are cloneable, seekable, and
// synchronous to read, which this function helps guarantee somewhat efficiently
// and without loss of information.
//
// If the replacement stream outparameter is not initialized to `nullptr`, the
// returned stream should be used instead of `aUploadStream` as the upload
// stream for the HTTP channel, and the previous stream should not be touched
// again.
//
// If aReadyPromise is non-nullptr after the function is called, it is a promise
// which should be awaited before continuing to `AsyncOpen` the HTTP channel,
// as the replacement stream will not be ready until it is resolved.
static nsresult NormalizeUploadStream(nsIInputStream* aUploadStream,
nsIInputStream** aReplacementStream,
GenericPromise** aReadyPromise) {
MOZ_ASSERT(XRE_IsParentProcess());
*aReplacementStream = nullptr;
*aReadyPromise = nullptr;
// Unwrap RemoteLazyInputStream and normalize the contents as we're in the
// parent process.
if (nsCOMPtr<mozIRemoteLazyInputStream> lazyStream =
do_QueryInterface(aUploadStream)) {
nsCOMPtr<nsIInputStream> internal;
if (NS_SUCCEEDED(
lazyStream->TakeInternalStream(getter_AddRefs(internal)))) {
nsCOMPtr<nsIInputStream> replacement;
nsresult rv = NormalizeUploadStream(internal, getter_AddRefs(replacement),
aReadyPromise);
NS_ENSURE_SUCCESS(rv, rv);
if (replacement) {
replacement.forget(aReplacementStream);
} else {
internal.forget(aReplacementStream);
}
return NS_OK;
}
}
// Preserve MIME information on the stream when normalizing.
if (nsCOMPtr<nsIMIMEInputStream> mime = do_QueryInterface(aUploadStream)) {
nsCOMPtr<nsIInputStream> data;
nsresult rv = mime->GetData(getter_AddRefs(data));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIInputStream> replacement;
rv =
NormalizeUploadStream(data, getter_AddRefs(replacement), aReadyPromise);
NS_ENSURE_SUCCESS(rv, rv);
if (replacement) {
nsCOMPtr<nsIMIMEInputStream> replacementMime(
do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIHttpHeaderVisitor> visitor =
new MIMEHeaderCopyVisitor(replacementMime);
rv = mime->VisitHeaders(visitor);
NS_ENSURE_SUCCESS(rv, rv);
rv = replacementMime->SetData(replacement);
NS_ENSURE_SUCCESS(rv, rv);
replacementMime.forget(aReplacementStream);
}
return NS_OK;
}
// Preserve "real" buffered input streams which wrap data (i.e. are backed by
// nsBufferedInputStream), but normalize the wrapped stream.
if (nsCOMPtr<nsIBufferedInputStream> buffered =
do_QueryInterface(aUploadStream)) {
nsCOMPtr<nsIInputStream> data;
if (NS_SUCCEEDED(buffered->GetData(getter_AddRefs(data)))) {
nsCOMPtr<nsIInputStream> replacement;
nsresult rv = NormalizeUploadStream(data, getter_AddRefs(replacement),
aReadyPromise);
NS_ENSURE_SUCCESS(rv, rv);
if (replacement) {
// This buffer size should be kept in sync with HTMLFormSubmission.
rv = NS_NewBufferedInputStream(aReplacementStream, replacement.forget(),
8192);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
}
// Preserve multiplex input streams, normalizing each individual inner stream
// to avoid unnecessary copying.
if (nsCOMPtr<nsIMultiplexInputStream> multiplex =
do_QueryInterface(aUploadStream)) {
uint32_t count = multiplex->GetCount();
nsTArray<nsCOMPtr<nsIInputStream>> streams(count);
nsTArray<RefPtr<GenericPromise>> promises(count);
bool replace = false;
for (uint32_t i = 0; i < count; ++i) {
nsCOMPtr<nsIInputStream> inner;
nsresult rv = multiplex->GetStream(i, getter_AddRefs(inner));
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<GenericPromise> promise;
nsCOMPtr<nsIInputStream> replacement;
rv = NormalizeUploadStream(inner, getter_AddRefs(replacement),
getter_AddRefs(promise));
NS_ENSURE_SUCCESS(rv, rv);
if (promise) {
promises.AppendElement(promise);
}
if (replacement) {
streams.AppendElement(replacement);
replace = true;
} else {
streams.AppendElement(inner);
}
}
// If any of the inner streams needed to be replaced, replace the entire
// nsIMultiplexInputStream.
if (replace) {
nsresult rv;
nsCOMPtr<nsIMultiplexInputStream> replacement =
do_CreateInstance("@mozilla.org/io/multiplex-input-stream;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
for (auto& stream : streams) {
rv = replacement->AppendStream(stream);
NS_ENSURE_SUCCESS(rv, rv);
}
MOZ_ALWAYS_SUCCEEDS(CallQueryInterface(replacement, aReplacementStream));
}
// Wait for all inner promises to settle before resolving the final promise.
if (!promises.IsEmpty()) {
RefPtr<GenericPromise> ready =
GenericPromise::AllSettled(GetCurrentSerialEventTarget(), promises)
->Then(GetCurrentSerialEventTarget(), __func__,
[](GenericPromise::AllSettledPromiseType::
ResolveOrRejectValue&& aResults)
-> RefPtr<GenericPromise> {
MOZ_ASSERT(aResults.IsResolve(),
"AllSettled never rejects");
for (auto& result : aResults.ResolveValue()) {
if (result.IsReject()) {
return GenericPromise::CreateAndReject(
result.RejectValue(), __func__);
}
}
return GenericPromise::CreateAndResolve(true, __func__);
});
ready.forget(aReadyPromise);
}
return NS_OK;
}
// If the stream is cloneable, seekable and non-async, we can allow it. Async
// input streams can cause issues, as various consumers of input streams
// expect the payload to be synchronous and `Available()` to be the length of
// the stream, which is not true for asynchronous streams.
nsCOMPtr<nsIAsyncInputStream> async = do_QueryInterface(aUploadStream);
nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(aUploadStream);
if (NS_InputStreamIsCloneable(aUploadStream) && seekable && !async) {
return NS_OK;
}
// Asynchronously copy our non-normalized stream into a StorageStream so that
// it is seekable, cloneable, and synchronous once the copy completes.
NS_WARNING("Upload Stream is being copied into StorageStream");
nsCOMPtr<nsIStorageStream> storageStream;
nsresult rv =
NS_NewStorageStream(4096, UINT32_MAX, getter_AddRefs(storageStream));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIOutputStream> sink;
rv = storageStream->GetOutputStream(0, getter_AddRefs(sink));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIInputStream> replacementStream;
rv = storageStream->NewInputStream(0, getter_AddRefs(replacementStream));
NS_ENSURE_SUCCESS(rv, rv);
// Ensure the source stream is buffered before starting the copy so we can use
// ReadSegments, as nsStorageStream doesn't implement WriteSegments.
nsCOMPtr<nsIInputStream> source = aUploadStream;
if (!NS_InputStreamIsBuffered(aUploadStream)) {
nsCOMPtr<nsIInputStream> bufferedSource;
rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedSource),
source.forget(), 4096);
NS_ENSURE_SUCCESS(rv, rv);
source = bufferedSource.forget();
}
// Perform an AsyncCopy into the input stream on the STS.
nsCOMPtr<nsIEventTarget> target =
do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
RefPtr<GenericPromise::Private> ready = new GenericPromise::Private(__func__);
rv = NS_AsyncCopy(source, sink, target, NS_ASYNCCOPY_VIA_READSEGMENTS, 4096,
NormalizeCopyComplete, do_AddRef(ready).take());
if (NS_WARN_IF(NS_FAILED(rv))) {
ready.get()->Release();
return rv;
}
replacementStream.forget(aReplacementStream);
ready.forget(aReadyPromise);
return NS_OK;
}
} // anonymous namespace
NS_IMETHODIMP
HttpBaseChannel::CloneUploadStream(int64_t* aContentLength,
nsIInputStream** aClonedStream) {
NS_ENSURE_ARG_POINTER(aContentLength);
NS_ENSURE_ARG_POINTER(aClonedStream);
*aClonedStream = nullptr;
if (!XRE_IsParentProcess()) {
NS_WARNING("CloneUploadStream is only supported in the parent process");
return NS_ERROR_NOT_AVAILABLE;
}
if (!mUploadStream) {
return NS_OK;
}
nsCOMPtr<nsIInputStream> clonedStream;
nsresult rv =
NS_CloneInputStream(mUploadStream, getter_AddRefs(clonedStream));
NS_ENSURE_SUCCESS(rv, rv);
clonedStream.forget(aClonedStream);
*aContentLength = mReqContentLength;
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIUploadChannel2
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::ExplicitSetUploadStream(nsIInputStream* aStream,
const nsACString& aContentType,
int64_t aContentLength,
const nsACString& aMethod,
bool aStreamHasHeaders) {
// Ensure stream is set and method is valid
NS_ENSURE_TRUE(aStream, NS_ERROR_FAILURE);
{
DebugOnly<nsCOMPtr<nsIMIMEInputStream>> mimeStream;
MOZ_ASSERT(
!aStreamHasHeaders || NS_FAILED(CallQueryInterface(
aStream, getter_AddRefs(mimeStream.value))),
"nsIMIMEInputStream should not include headers");
}
nsresult rv = SetRequestMethod(aMethod);
NS_ENSURE_SUCCESS(rv, rv);
if (!aStreamHasHeaders && !aContentType.IsVoid()) {
if (aContentType.IsEmpty()) {
SetEmptyRequestHeader("Content-Type"_ns);
} else {
SetRequestHeader("Content-Type"_ns, aContentType, false);
}
}
StoreUploadStreamHasHeaders(aStreamHasHeaders);
return InternalSetUploadStream(aStream, aContentLength, !aStreamHasHeaders);
}
nsresult HttpBaseChannel::InternalSetUploadStream(
nsIInputStream* aUploadStream, int64_t aContentLength,
bool aSetContentLengthHeader) {
// If we're not on the main thread, such as for TRR, the content length must
// be provided, as we can't normalize our upload stream.
if (!NS_IsMainThread()) {
if (aContentLength < 0) {
MOZ_ASSERT_UNREACHABLE(
"Upload content length must be explicit off-main-thread");
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(aUploadStream);
if (!NS_InputStreamIsCloneable(aUploadStream) || !seekable) {
MOZ_ASSERT_UNREACHABLE(
"Upload stream must be cloneable & seekable off-main-thread");
return NS_ERROR_INVALID_ARG;
}
mUploadStream = aUploadStream;
ExplicitSetUploadStreamLength(aContentLength, aSetContentLengthHeader);
return NS_OK;
}
// Normalize the upload stream we're provided to ensure that it is cloneable,
// seekable, and synchronous when in the parent process.
//
// This might be an async operation, in which case ready will be returned and
// resolved when the operation is complete.
nsCOMPtr<nsIInputStream> replacement;
RefPtr<GenericPromise> ready;
if (XRE_IsParentProcess()) {
nsresult rv = NormalizeUploadStream(
aUploadStream, getter_AddRefs(replacement), getter_AddRefs(ready));
NS_ENSURE_SUCCESS(rv, rv);
}
mUploadStream = replacement ? replacement.get() : aUploadStream;
// Once the upload stream is ready, fetch its length before proceeding with
// AsyncOpen.
auto onReady = [self = RefPtr{this}, aContentLength, aSetContentLengthHeader,
stream = mUploadStream]() {
auto setLengthAndResume = [self, aSetContentLengthHeader](int64_t aLength) {
self->StorePendingUploadStreamNormalization(false);
self->ExplicitSetUploadStreamLength(aLength >= 0 ? aLength : 0,
aSetContentLengthHeader);
self->MaybeResumeAsyncOpen();
};
if (aContentLength >= 0) {
setLengthAndResume(aContentLength);
return;
}
int64_t length;
if (InputStreamLengthHelper::GetSyncLength(stream, &length)) {
setLengthAndResume(length);
return;
}
InputStreamLengthHelper::GetAsyncLength(stream, setLengthAndResume);
};
StorePendingUploadStreamNormalization(true);
// Resolve onReady synchronously unless a promise is returned.
if (ready) {
ready->Then(GetCurrentSerialEventTarget(), __func__,
[onReady = std::move(onReady)](
GenericPromise::ResolveOrRejectValue&&) { onReady(); });
} else {
onReady();
}
return NS_OK;
}
void HttpBaseChannel::ExplicitSetUploadStreamLength(
uint64_t aContentLength, bool aSetContentLengthHeader) {
// We already have the content length. We don't need to determinate it.
mReqContentLength = aContentLength;
if (!aSetContentLengthHeader) {
return;
}
nsAutoCString header;
header.AssignLiteral("Content-Length");
// Maybe the content-length header has been already set.
nsAutoCString value;
nsresult rv = GetRequestHeader(header, value);
if (NS_SUCCEEDED(rv) && !value.IsEmpty()) {
return;
}
nsAutoCString contentLengthStr;
contentLengthStr.AppendInt(aContentLength);
SetRequestHeader(header, contentLengthStr, false);
}
NS_IMETHODIMP
HttpBaseChannel::GetUploadStreamHasHeaders(bool* hasHeaders) {
NS_ENSURE_ARG(hasHeaders);
*hasHeaders = LoadUploadStreamHasHeaders();
return NS_OK;
}
bool HttpBaseChannel::MaybeWaitForUploadStreamNormalization(
nsIStreamListener* aListener, nsISupports* aContext) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(!LoadAsyncOpenWaitingForStreamNormalization(),
"AsyncOpen() called twice?");
if (!LoadPendingUploadStreamNormalization()) {
return false;
}
mListener = aListener;
StoreAsyncOpenWaitingForStreamNormalization(true);
return true;
}
void HttpBaseChannel::MaybeResumeAsyncOpen() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(!LoadPendingUploadStreamNormalization());
if (!LoadAsyncOpenWaitingForStreamNormalization()) {
return;
}
nsCOMPtr<nsIStreamListener> listener;
listener.swap(mListener);
StoreAsyncOpenWaitingForStreamNormalization(false);
nsresult rv = AsyncOpen(listener);
if (NS_WARN_IF(NS_FAILED(rv))) {
DoAsyncAbort(rv);
}
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIEncodedChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetApplyConversion(bool* value) {
*value = LoadApplyConversion();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetApplyConversion(bool value) {
LOG(("HttpBaseChannel::SetApplyConversion [this=%p value=%d]\n", this,
value));
StoreApplyConversion(value);
return NS_OK;
}
nsresult HttpBaseChannel::DoApplyContentConversions(
nsIStreamListener* aNextListener, nsIStreamListener** aNewNextListener) {
return DoApplyContentConversionsInternal(aNextListener, aNewNextListener,
false, nullptr);
}
// create a listener chain that looks like this
// http-channel -> decompressor (n times) -> InterceptFailedOnSTop ->
// channel-creator-listener
//
// we need to do this because not every decompressor has fully streamed output
// so may need a call to OnStopRequest to identify its completion state.. and if
// it creates an error there the channel status code needs to be updated before
// calling the terminal listener. Having the decompress do it via cancel() means
// channels cannot effectively be used in two contexts (specifically this one
// and a peek context for sniffing)
//
class InterceptFailedOnStop : public nsIThreadRetargetableStreamListener {
virtual ~InterceptFailedOnStop() = default;
nsCOMPtr<nsIStreamListener> mNext;
HttpBaseChannel* mChannel;
public:
InterceptFailedOnStop(nsIStreamListener* arg, HttpBaseChannel* chan)
: mNext(arg), mChannel(chan) {}
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
NS_IMETHOD OnStartRequest(nsIRequest* aRequest) override {
return mNext->OnStartRequest(aRequest);
}
NS_IMETHOD OnStopRequest(nsIRequest* aRequest,
nsresult aStatusCode) override {
if (NS_FAILED(aStatusCode) && NS_SUCCEEDED(mChannel->mStatus)) {
LOG(("HttpBaseChannel::InterceptFailedOnStop %p seting status %" PRIx32,
mChannel, static_cast<uint32_t>(aStatusCode)));
mChannel->mStatus = aStatusCode;
}
return mNext->OnStopRequest(aRequest, aStatusCode);
}
NS_IMETHOD OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInputStream,
uint64_t aOffset, uint32_t aCount) override {
return mNext->OnDataAvailable(aRequest, aInputStream, aOffset, aCount);
}
};
NS_IMPL_ADDREF(InterceptFailedOnStop)
NS_IMPL_RELEASE(InterceptFailedOnStop)
NS_INTERFACE_MAP_BEGIN(InterceptFailedOnStop)
NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableStreamListener)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRequestObserver)
NS_INTERFACE_MAP_END
NS_IMETHODIMP
InterceptFailedOnStop::CheckListenerChain() {
nsCOMPtr<nsIThreadRetargetableStreamListener> listener =
do_QueryInterface(mNext);
if (!listener) {
return NS_ERROR_NO_INTERFACE;
}
return listener->CheckListenerChain();
}
NS_IMETHODIMP
InterceptFailedOnStop::OnDataFinished(nsresult aStatus) {
nsCOMPtr<nsIThreadRetargetableStreamListener> listener =
do_QueryInterface(mNext);
if (listener) {
return listener->OnDataFinished(aStatus);
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::DoApplyContentConversions(nsIStreamListener* aNextListener,
nsIStreamListener** aNewNextListener,
nsISupports* aCtxt) {
return DoApplyContentConversionsInternal(aNextListener, aNewNextListener,
false, aCtxt);
}
nsresult HttpBaseChannel::DoApplyContentConversionsInternal(
nsIStreamListener* aNextListener, nsIStreamListener** aNewNextListener,
bool aRemoveEncodings, nsISupports* aCtxt) {
*aNewNextListener = nullptr;
if (!mResponseHead || !aNextListener) {
return NS_OK;
}
LOG(
("HttpBaseChannel::DoApplyContentConversions [this=%p], "
"removeEncodings=%d\n",
this, aRemoveEncodings));
#ifdef DEBUG
{
nsAutoCString contentEncoding;
nsresult rv =
mResponseHead->GetHeader(nsHttp::Content_Encoding, contentEncoding);
if (NS_SUCCEEDED(rv) && !contentEncoding.IsEmpty()) {
nsAutoCString newEncoding;
char* cePtr = contentEncoding.BeginWriting();
while (char* val = nsCRT::strtok(cePtr, HTTP_LWS ",", &cePtr)) {
if (strcmp(val, "dcb") == 0 || strcmp(val, "dcz") == 0) {
MOZ_ASSERT(LoadApplyConversion() && !LoadHasAppliedConversion());
}
}
}
}
#endif
if (!LoadApplyConversion()) {
LOG(("not applying conversion per ApplyConversion\n"));
return NS_OK;
}
if (LoadHasAppliedConversion()) {
LOG(("not applying conversion because HasAppliedConversion is true\n"));
return NS_OK;
}
if (LoadDeliveringAltData()) {
MOZ_ASSERT(!mAvailableCachedAltDataType.IsEmpty());
LOG(("not applying conversion because delivering alt-data\n"));
return NS_OK;
}
nsAutoCString contentEncoding;
nsresult rv =
mResponseHead->GetHeader(nsHttp::Content_Encoding, contentEncoding);
if (NS_FAILED(rv) || contentEncoding.IsEmpty()) return NS_OK;
nsCOMPtr<nsIStreamListener> nextListener =
new InterceptFailedOnStop(aNextListener, this);
// The encodings are listed in the order they were applied
// (see rfc 2616 section 14.11), so they need to removed in reverse
// order. This is accomplished because the converter chain ends up
// being a stack with the last converter created being the first one
// to accept the raw network data.
char* cePtr = contentEncoding.BeginWriting();
uint32_t count = 0;
while (char* val = nsCRT::strtok(cePtr, HTTP_LWS ",", &cePtr)) {
if (++count > 16) {
// For compatibility with old code, we will just carry on without
// removing the encodings
LOG(("Too many Content-Encodings. Ignoring remainder.\n"));
break;
}
if (gHttpHandler->IsAcceptableEncoding(val,
isSecureOrTrustworthyURL(mURI))) {
RefPtr<nsHTTPCompressConv> converter = new nsHTTPCompressConv();
nsAutoCString from(val);
ToLowerCase(from);
rv = converter->AsyncConvertData(from.get(), "uncompressed", nextListener,
aCtxt);
if (NS_FAILED(rv)) {
LOG(("Unexpected failure of AsyncConvertData %s\n", val));
return rv;
}
LOG(("Adding converter for content-encoding '%s'", val));
if (Telemetry::CanRecordPrereleaseData()) {
int mode = 0;
if (from.EqualsLiteral("gzip") || from.EqualsLiteral("x-gzip")) {
mode = 1;
} else if (from.EqualsLiteral("deflate") ||
from.EqualsLiteral("x-deflate")) {
mode = 2;
} else if (from.EqualsLiteral("br")) {
mode = 3;
} else if (from.EqualsLiteral("zstd")) {
mode = 4;
} else if (from.EqualsLiteral("dcb")) {
mode = 5;
} else if (from.EqualsLiteral("dcz")) {
mode = 6;
}
glean::http::content_encoding.AccumulateSingleSample(mode);
}
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
if (from.EqualsLiteral("dcb") || from.EqualsLiteral("dcz")) {
MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
}
#endif
nextListener = converter;
} else {
if (val) {
LOG(("Unknown content encoding '%s'\n", val));
}
// we *should* return NS_ERROR_UNEXPECTED here, but that will break sites
// that use things like content-encoding: x-gzip, x-gzip (or any other
// weird encoding)
}
}
// dcb and dcz encodings are removed when it's decompressed (always in
// the parent process). However, in theory you could have
// Content-Encoding: dcb,gzip
// in which case we could pass it down to the content process as
// Content-Encoding: gzip. We won't do that; we'll remove all compressors
// if we need to remove any.
// This double compression of course is silly, but supported by the spec.
if (aRemoveEncodings) {
// If we have dcb or dcz, all content-encodings in the header should be
// removed as we're decompressing before the tee in the parent
// process. Also we should remove any encodings if it's a dictionary
// so we can load it quickly
LOG(("Changing Content-Encoding from '%s' to ''", contentEncoding.get()));
// Can't use SetHeader; we need to overwrite the current value
rv = mResponseHead->SetHeaderOverride(nsHttp::Content_Encoding, ""_ns);
}
*aNewNextListener = do_AddRef(nextListener).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetContentEncodings(nsIUTF8StringEnumerator** aEncodings) {
if (!mResponseHead) {
*aEncodings = nullptr;
return NS_OK;
}
nsAutoCString encoding;
(void)mResponseHead->GetHeader(nsHttp::Content_Encoding, encoding);
if (encoding.IsEmpty()) {
*aEncodings = nullptr;
return NS_OK;
}
RefPtr<nsContentEncodings> enumerator =
new nsContentEncodings(this, encoding.get());
enumerator.forget(aEncodings);
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsContentEncodings <public>
//-----------------------------------------------------------------------------
HttpBaseChannel::nsContentEncodings::nsContentEncodings(
nsIHttpChannel* aChannel, const char* aEncodingHeader)
: mEncodingHeader(aEncodingHeader), mChannel(aChannel), mReady(false) {
mCurEnd = aEncodingHeader + strlen(aEncodingHeader);
mCurStart = mCurEnd;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsContentEncodings::nsISimpleEnumerator
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::nsContentEncodings::HasMore(bool* aMoreEncodings) {
if (mReady) {
*aMoreEncodings = true;
return NS_OK;
}
nsresult rv = PrepareForNext();
*aMoreEncodings = NS_SUCCEEDED(rv);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::nsContentEncodings::GetNext(nsACString& aNextEncoding) {
aNextEncoding.Truncate();
if (!mReady) {
nsresult rv = PrepareForNext();
if (NS_FAILED(rv)) {
return NS_ERROR_FAILURE;
}
}
const nsACString& encoding = Substring(mCurStart, mCurEnd);
nsACString::const_iterator start, end;
encoding.BeginReading(start);
encoding.EndReading(end);
bool haveType = false;
if (CaseInsensitiveFindInReadable("gzip"_ns, start, end)) {
aNextEncoding.AssignLiteral(APPLICATION_GZIP);
haveType = true;
}
if (!haveType) {
encoding.BeginReading(start);
if (CaseInsensitiveFindInReadable("compress"_ns, start, end)) {
aNextEncoding.AssignLiteral(APPLICATION_COMPRESS);
haveType = true;
}
}
if (!haveType) {
encoding.BeginReading(start);
if (CaseInsensitiveFindInReadable("deflate"_ns, start, end)) {
aNextEncoding.AssignLiteral(APPLICATION_ZIP);
haveType = true;
}
}
if (!haveType) {
encoding.BeginReading(start);
if (CaseInsensitiveFindInReadable("br"_ns, start, end)) {
aNextEncoding.AssignLiteral(APPLICATION_BROTLI);
haveType = true;
}
}
if (!haveType) {
encoding.BeginReading(start);
if (CaseInsensitiveFindInReadable("zstd"_ns, start, end)) {
aNextEncoding.AssignLiteral(APPLICATION_ZSTD);
haveType = true;
}
}
// Prepare to fetch the next encoding
mCurEnd = mCurStart;
mReady = false;
if (haveType) return NS_OK;
NS_WARNING("Unknown encoding type");
return NS_ERROR_FAILURE;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsContentEncodings::nsISupports
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS(HttpBaseChannel::nsContentEncodings, nsIUTF8StringEnumerator,
nsIStringEnumerator)
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsContentEncodings <private>
//-----------------------------------------------------------------------------
nsresult HttpBaseChannel::nsContentEncodings::PrepareForNext(void) {
MOZ_ASSERT(mCurStart == mCurEnd, "Indeterminate state");
// At this point both mCurStart and mCurEnd point to somewhere
// past the end of the next thing we want to return
while (mCurEnd != mEncodingHeader) {
--mCurEnd;
if (*mCurEnd != ',' && !nsCRT::IsAsciiSpace(*mCurEnd)) break;
}
if (mCurEnd == mEncodingHeader) {
return NS_ERROR_NOT_AVAILABLE; // no more encodings
}
++mCurEnd;
// At this point mCurEnd points to the first char _after_ the
// header we want. Furthermore, mCurEnd - 1 != mEncodingHeader
mCurStart = mCurEnd - 1;
while (mCurStart != mEncodingHeader && *mCurStart != ',' &&
!nsCRT::IsAsciiSpace(*mCurStart)) {
--mCurStart;
}
if (*mCurStart == ',' || nsCRT::IsAsciiSpace(*mCurStart)) {
++mCurStart; // we stopped because of a weird char, so move up one
}
// At this point mCurStart and mCurEnd bracket the encoding string
// we want. Check that it's not "identity"
if (Substring(mCurStart, mCurEnd)
.Equals("identity", nsCaseInsensitiveCStringComparator)) {
mCurEnd = mCurStart;
return PrepareForNext();
}
mReady = true;
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIHttpChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetChannelId(uint64_t* aChannelId) {
NS_ENSURE_ARG_POINTER(aChannelId);
*aChannelId = mChannelId;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetChannelId(uint64_t aChannelId) {
mChannelId = aChannelId;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::GetTopLevelContentWindowId(uint64_t* aWindowId) {
if (!mContentWindowId) {
nsCOMPtr<nsILoadContext> loadContext;
GetCallback(loadContext);
if (loadContext) {
nsCOMPtr<mozIDOMWindowProxy> topWindow;
loadContext->GetTopWindow(getter_AddRefs(topWindow));
if (topWindow) {
if (nsPIDOMWindowInner* inner =
nsPIDOMWindowOuter::From(topWindow)->GetCurrentInnerWindow()) {
mContentWindowId = inner->WindowID();
}
}
}
}
*aWindowId = mContentWindowId;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::SetBrowserId(uint64_t aId) {
mBrowserId = aId;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::GetBrowserId(uint64_t* aId) {
EnsureBrowserId();
*aId = mBrowserId;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::SetTopLevelContentWindowId(uint64_t aWindowId) {
mContentWindowId = aWindowId;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::IsThirdPartyTrackingResource(bool* aIsTrackingResource) {
MOZ_ASSERT(
!(mFirstPartyClassificationFlags && mThirdPartyClassificationFlags));
*aIsTrackingResource = UrlClassifierCommon::IsTrackingClassificationFlag(
mThirdPartyClassificationFlags,
mLoadInfo->GetOriginAttributes().IsPrivateBrowsing());
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::IsThirdPartySocialTrackingResource(
bool* aIsThirdPartySocialTrackingResource) {
MOZ_ASSERT(!mFirstPartyClassificationFlags ||
!mThirdPartyClassificationFlags);
*aIsThirdPartySocialTrackingResource =
UrlClassifierCommon::IsSocialTrackingClassificationFlag(
mThirdPartyClassificationFlags);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetClassificationFlags(uint32_t* aFlags) {
if (mThirdPartyClassificationFlags) {
*aFlags = mThirdPartyClassificationFlags;
} else {
*aFlags = mFirstPartyClassificationFlags;
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetFirstPartyClassificationFlags(uint32_t* aFlags) {
*aFlags = mFirstPartyClassificationFlags;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetThirdPartyClassificationFlags(uint32_t* aFlags) {
*aFlags = mThirdPartyClassificationFlags;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetTransferSize(uint64_t* aTransferSize) {
MutexAutoLock lock(mOnDataFinishedMutex);
*aTransferSize = mTransferSize;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestSize(uint64_t* aRequestSize) {
*aRequestSize = mRequestSize;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetDecodedBodySize(uint64_t* aDecodedBodySize) {
MutexAutoLock lock(mOnDataFinishedMutex);
*aDecodedBodySize = mDecodedBodySize;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetEncodedBodySize(uint64_t* aEncodedBodySize) {
MutexAutoLock lock(mOnDataFinishedMutex);
*aEncodedBodySize = mEncodedBodySize;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetSupportsHTTP3(bool* aSupportsHTTP3) {
*aSupportsHTTP3 = mSupportsHTTP3;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetHasHTTPSRR(bool* aHasHTTPSRR) {
*aHasHTTPSRR = LoadHasHTTPSRR();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestMethod(nsACString& aMethod) {
mRequestHead.Method(aMethod);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRequestMethod(const nsACString& aMethod) {
ENSURE_CALLED_BEFORE_CONNECT();
mLoadInfo->SetIsGETRequest(aMethod.Equals("GET"));
const nsCString& flatMethod = PromiseFlatCString(aMethod);
// Method names are restricted to valid HTTP tokens.
if (!nsHttp::IsValidToken(flatMethod)) return NS_ERROR_INVALID_ARG;
mRequestHead.SetMethod(flatMethod);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetReferrerInfo(nsIReferrerInfo** aReferrerInfo) {
NS_ENSURE_ARG_POINTER(aReferrerInfo);
*aReferrerInfo = do_AddRef(mReferrerInfo).take();
return NS_OK;
}
nsresult HttpBaseChannel::SetReferrerInfoInternal(
nsIReferrerInfo* aReferrerInfo, bool aClone, bool aCompute,
bool aRespectBeforeConnect) {
LOG(
("HttpBaseChannel::SetReferrerInfoInternal [this=%p aClone(%d) "
"aCompute(%d)]\n",
this, aClone, aCompute));
if (aRespectBeforeConnect) {
ENSURE_CALLED_BEFORE_CONNECT();
}
mReferrerInfo = aReferrerInfo;
// clear existing referrer, if any
nsresult rv = ClearReferrerHeader();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (!mReferrerInfo) {
return NS_OK;
}
if (aClone) {
mReferrerInfo = static_cast<dom::ReferrerInfo*>(aReferrerInfo)->Clone();
}
dom::ReferrerInfo* referrerInfo =
static_cast<dom::ReferrerInfo*>(mReferrerInfo.get());
// Don't set referrerInfo if it has not been initialized.
if (!referrerInfo->IsInitialized()) {
mReferrerInfo = nullptr;
return NS_ERROR_NOT_INITIALIZED;
}
if (aClone) {
// Record the telemetry once we set the referrer info to the channel
// successfully.
referrerInfo->RecordTelemetry(this);
}
if (aCompute) {
rv = referrerInfo->ComputeReferrer(this);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
nsCOMPtr<nsIURI> computedReferrer = mReferrerInfo->GetComputedReferrer();
if (!computedReferrer) {
return NS_OK;
}
nsAutoCString spec;
rv = computedReferrer->GetSpec(spec);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return SetReferrerHeader(spec, aRespectBeforeConnect);
}
NS_IMETHODIMP
HttpBaseChannel::SetReferrerInfo(nsIReferrerInfo* aReferrerInfo) {
return SetReferrerInfoInternal(aReferrerInfo, true, true, true);
}
NS_IMETHODIMP
HttpBaseChannel::SetReferrerInfoWithoutClone(nsIReferrerInfo* aReferrerInfo) {
return SetReferrerInfoInternal(aReferrerInfo, false, true, true);
}
// Return the channel's proxy URI, or if it doesn't exist, the
// channel's main URI.
NS_IMETHODIMP
HttpBaseChannel::GetProxyURI(nsIURI** aOut) {
NS_ENSURE_ARG_POINTER(aOut);
nsCOMPtr<nsIURI> result(mProxyURI);
result.forget(aOut);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestHeader(const nsACString& aHeader,
nsACString& aValue) {
aValue.Truncate();
// XXX might be better to search the header list directly instead of
// hitting the http atom hash table.
nsHttpAtom atom = nsHttp::ResolveAtom(aHeader);
if (!atom) return NS_ERROR_NOT_AVAILABLE;
return mRequestHead.GetHeader(atom, aValue);
}
NS_IMETHODIMP
HttpBaseChannel::SetRequestHeader(const nsACString& aHeader,
const nsACString& aValue, bool aMerge) {
return SetRequestHeaderInternal(aHeader, aValue, aMerge,
nsHttpHeaderArray::eVarietyRequestOverride);
}
nsresult HttpBaseChannel::SetRequestHeaderInternal(
const nsACString& aHeader, const nsACString& aValue, bool aMerge,
nsHttpHeaderArray::HeaderVariety aVariety) {
const nsCString& flatHeader = PromiseFlatCString(aHeader);
const nsCString& flatValue = PromiseFlatCString(aValue);
LOG(
("HttpBaseChannel::SetRequestHeader [this=%p header=\"%s\" value=\"%s\" "
"merge=%u]\n",
this, flatHeader.get(), flatValue.get(), aMerge));
// Verify header names are valid HTTP tokens and header values are reasonably
// close to whats allowed in RFC 2616.
if (!nsHttp::IsValidToken(flatHeader) ||
!nsHttp::IsReasonableHeaderValue(flatValue)) {
return NS_ERROR_INVALID_ARG;
}
// Mark that the User-Agent header has been modified.
if (nsHttp::ResolveAtom(aHeader) == nsHttp::User_Agent) {
StoreIsUserAgentHeaderModified(true);
}
return mRequestHead.SetHeader(aHeader, flatValue, aMerge);
}
NS_IMETHODIMP
HttpBaseChannel::SetNewReferrerInfo(const nsACString& aUrl,
nsIReferrerInfo::ReferrerPolicyIDL aPolicy,
bool aSendReferrer) {
nsresult rv;
// Create URI from string
nsCOMPtr<nsIURI> aURI;
rv = NS_NewURI(getter_AddRefs(aURI), aUrl);
NS_ENSURE_SUCCESS(rv, rv);
// Create new ReferrerInfo and initialize it.
nsCOMPtr<nsIReferrerInfo> referrerInfo = new mozilla::dom::ReferrerInfo();
rv = referrerInfo->Init(aPolicy, aSendReferrer, aURI);
NS_ENSURE_SUCCESS(rv, rv);
// Set ReferrerInfo
return SetReferrerInfo(referrerInfo);
}
NS_IMETHODIMP
HttpBaseChannel::SetEmptyRequestHeader(const nsACString& aHeader) {
const nsCString& flatHeader = PromiseFlatCString(aHeader);
LOG(("HttpBaseChannel::SetEmptyRequestHeader [this=%p header=\"%s\"]\n", this,
flatHeader.get()));
// Verify header names are valid HTTP tokens and header values are reasonably
// close to whats allowed in RFC 2616.
if (!nsHttp::IsValidToken(flatHeader)) {
return NS_ERROR_INVALID_ARG;
}
// Mark that the User-Agent header has been modified.
if (nsHttp::ResolveAtom(aHeader) == nsHttp::User_Agent) {
StoreIsUserAgentHeaderModified(true);
}
return mRequestHead.SetEmptyHeader(aHeader);
}
NS_IMETHODIMP
HttpBaseChannel::VisitRequestHeaders(nsIHttpHeaderVisitor* visitor) {
return mRequestHead.VisitHeaders(visitor);
}
NS_IMETHODIMP
HttpBaseChannel::VisitNonDefaultRequestHeaders(nsIHttpHeaderVisitor* visitor) {
return mRequestHead.VisitHeaders(visitor,
nsHttpHeaderArray::eFilterSkipDefault);
}
NS_IMETHODIMP
HttpBaseChannel::GetResponseHeader(const nsACString& header,
nsACString& value) {
value.Truncate();
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
nsHttpAtom atom = nsHttp::ResolveAtom(header);
if (!atom) return NS_ERROR_NOT_AVAILABLE;
return mResponseHead->GetHeader(atom, value);
}
NS_IMETHODIMP
HttpBaseChannel::SetResponseHeader(const nsACString& header,
const nsACString& value, bool merge) {
LOG(
("HttpBaseChannel::SetResponseHeader [this=%p header=\"%s\" value=\"%s\" "
"merge=%u]\n",
this, PromiseFlatCString(header).get(), PromiseFlatCString(value).get(),
merge));
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
nsHttpAtom atom = nsHttp::ResolveAtom(header);
if (!atom) return NS_ERROR_NOT_AVAILABLE;
// these response headers must not be changed
if (atom == nsHttp::Content_Type || atom == nsHttp::Content_Length ||
atom == nsHttp::Content_Encoding || atom == nsHttp::Trailer ||
atom == nsHttp::Transfer_Encoding) {
return NS_ERROR_ILLEGAL_VALUE;
}
StoreResponseHeadersModified(true);
return mResponseHead->SetHeader(header, value, merge);
}
NS_IMETHODIMP
HttpBaseChannel::VisitResponseHeaders(nsIHttpHeaderVisitor* visitor) {
if (!mResponseHead) {
return NS_ERROR_NOT_AVAILABLE;
}
return mResponseHead->VisitHeaders(visitor,
nsHttpHeaderArray::eFilterResponse);
}
NS_IMETHODIMP
HttpBaseChannel::GetOriginalResponseHeader(const nsACString& aHeader,
nsIHttpHeaderVisitor* aVisitor) {
if (!mResponseHead) {
return NS_ERROR_NOT_AVAILABLE;
}
nsHttpAtom atom = nsHttp::ResolveAtom(aHeader);
if (!atom) {
return NS_ERROR_NOT_AVAILABLE;
}
return mResponseHead->GetOriginalHeader(atom, aVisitor);
}
NS_IMETHODIMP
HttpBaseChannel::VisitOriginalResponseHeaders(nsIHttpHeaderVisitor* aVisitor) {
if (!mResponseHead) {
return NS_ERROR_NOT_AVAILABLE;
}
return mResponseHead->VisitHeaders(
aVisitor, nsHttpHeaderArray::eFilterResponseOriginal);
}
NS_IMETHODIMP
HttpBaseChannel::GetAllowSTS(bool* value) {
NS_ENSURE_ARG_POINTER(value);
*value = LoadAllowSTS();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetAllowSTS(bool value) {
ENSURE_CALLED_BEFORE_CONNECT();
StoreAllowSTS(value);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsOCSP(bool* value) {
NS_ENSURE_ARG_POINTER(value);
*value = LoadIsOCSP();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetIsOCSP(bool value) {
ENSURE_CALLED_BEFORE_CONNECT();
StoreIsOCSP(value);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsUserAgentHeaderModified(bool* value) {
NS_ENSURE_ARG_POINTER(value);
*value = LoadIsUserAgentHeaderModified();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetIsUserAgentHeaderModified(bool value) {
StoreIsUserAgentHeaderModified(value);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRedirectionLimit(uint32_t* value) {
NS_ENSURE_ARG_POINTER(value);
*value = mRedirectionLimit;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRedirectionLimit(uint32_t value) {
ENSURE_CALLED_BEFORE_CONNECT();
mRedirectionLimit = std::min<uint32_t>(value, 0xff);
return NS_OK;
}
nsresult HttpBaseChannel::OverrideSecurityInfo(
nsITransportSecurityInfo* aSecurityInfo) {
MOZ_ASSERT(!mSecurityInfo,
"This can only be called when we don't have a security info "
"object already");
MOZ_RELEASE_ASSERT(
aSecurityInfo,
"This can only be called with a valid security info object");
MOZ_ASSERT(!BypassServiceWorker(),
"This can only be called on channels that are not bypassing "
"interception");
MOZ_ASSERT(LoadResponseCouldBeSynthesized(),
"This can only be called on channels that can be intercepted");
if (mSecurityInfo) {
LOG(
("HttpBaseChannel::OverrideSecurityInfo mSecurityInfo is null! "
"[this=%p]\n",
this));
return NS_ERROR_UNEXPECTED;
}
if (!LoadResponseCouldBeSynthesized()) {
LOG(
("HttpBaseChannel::OverrideSecurityInfo channel cannot be intercepted! "
"[this=%p]\n",
this));
return NS_ERROR_UNEXPECTED;
}
mSecurityInfo = aSecurityInfo;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::IsNoStoreResponse(bool* value) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
*value = mResponseHead->NoStore();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::IsNoCacheResponse(bool* value) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
*value = mResponseHead->NoCache();
if (!*value) *value = mResponseHead->ExpiresInPast();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetResponseStatus(uint32_t* aValue) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
*aValue = mResponseHead->Status();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetResponseStatusText(nsACString& aValue) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
nsAutoCString version;
// https://fetch.spec.whatwg.org :
// Responses over an HTTP/2 connection will always have the empty byte
// sequence as status message as HTTP/2 does not support them.
if (NS_WARN_IF(NS_FAILED(GetProtocolVersion(version))) ||
!version.EqualsLiteral("h2")) {
mResponseHead->StatusText(aValue);
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestSucceeded(bool* aValue) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
uint32_t status = mResponseHead->Status();
*aValue = (status / 100 == 2);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::RedirectTo(nsIURI* targetURI) {
NS_ENSURE_ARG(targetURI);
nsAutoCString spec;
targetURI->GetAsciiSpec(spec);
LOG(("HttpBaseChannel::RedirectTo [this=%p, uri=%s]", this, spec.get()));
LogCallingScriptLocation(this);
// We cannot redirect after OnStartRequest of the listener
// has been called, since to redirect we have to switch channels
// and the dance with OnStartRequest et al has to start over.
// This would break the nsIStreamListener contract.
NS_ENSURE_FALSE(LoadOnStartRequestCalled(), NS_ERROR_NOT_AVAILABLE);
// The first parameter is the URI we would like to redirect to
// The second parameter should default to false if normal redirect
mAPIRedirectTo =
Some(mozilla::MakeCompactPair(nsCOMPtr<nsIURI>(targetURI), false));
// Only Web Extensions are allowed to redirect a channel to a data:
// URI. To avoid any bypasses after the channel was flagged by
// the WebRequst API, we are dropping the flag here.
mLoadInfo->SetAllowInsecureRedirectToDataURI(false);
// We may want to rewrite origin allowance, hence we need an
// artificial response head.
if (!mResponseHead) {
mResponseHead.reset(new nsHttpResponseHead());
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::TransparentRedirectTo(nsIURI* targetURI) {
LOG(("HttpBaseChannel::TransparentRedirectTo [this=%p]", this));
RedirectTo(targetURI);
MOZ_ASSERT(mAPIRedirectTo, "How did this happen?");
mAPIRedirectTo->second() = true;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::UpgradeToSecure() {
// Upgrades are handled internally between http-on-modify-request and
// http-on-before-connect, which means upgrades are only possible during
// on-modify, or WebRequest.onBeforeRequest in Web Extensions. Once we are
// past the code path where upgrades are handled, attempting an upgrade
// will throw an error.
NS_ENSURE_TRUE(LoadUpgradableToSecure(), NS_ERROR_NOT_AVAILABLE);
StoreUpgradeToSecure(true);
// todo: Currently UpgradeToSecure() is called only by web extensions, if
// that ever changes, we need to update the following telemetry collection
// to reflect any future changes.
mLoadInfo->SetHttpsUpgradeTelemetry(nsILoadInfo::WEB_EXTENSION_UPGRADE);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestObserversCalled(bool* aCalled) {
NS_ENSURE_ARG_POINTER(aCalled);
*aCalled = LoadRequestObserversCalled();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRequestObserversCalled(bool aCalled) {
StoreRequestObserversCalled(aCalled);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestContextID(uint64_t* aRCID) {
NS_ENSURE_ARG_POINTER(aRCID);
*aRCID = mRequestContextID;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRequestContextID(uint64_t aRCID) {
mRequestContextID = aRCID;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsMainDocumentChannel(bool* aValue) {
NS_ENSURE_ARG_POINTER(aValue);
*aValue = IsNavigation();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetIsMainDocumentChannel(bool aValue) {
StoreForceMainDocumentChannel(aValue);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsUserAgentHeaderOutdated(bool* aValue) {
NS_ENSURE_ARG_POINTER(aValue);
*aValue = LoadIsUserAgentHeaderOutdated();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetIsUserAgentHeaderOutdated(bool aValue) {
StoreIsUserAgentHeaderOutdated(aValue);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetProtocolVersion(nsACString& aProtocolVersion) {
// Try to use ALPN if available and if it is not for a proxy, i.e if an
// https proxy was not used or if https proxy was used but the connection to
// the origin server is also https. In the case, an https proxy was used and
// the connection to the origin server was http, mSecurityInfo will be from
// the proxy.
if (!mConnectionInfo || !mConnectionInfo->UsingHttpsProxy() ||
mConnectionInfo->EndToEndSSL()) {
nsAutoCString protocol;
if (mSecurityInfo &&
NS_SUCCEEDED(mSecurityInfo->GetNegotiatedNPN(protocol)) &&
!protocol.IsEmpty()) {
// The negotiated protocol was not empty so we can use it.
aProtocolVersion = protocol;
return NS_OK;
}
}
if (mResponseHead) {
HttpVersion version = mResponseHead->Version();
aProtocolVersion.Assign(nsHttp::GetProtocolVersion(version));
return NS_OK;
}
return NS_ERROR_NOT_AVAILABLE;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIHttpChannelInternal
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::SetTopWindowURIIfUnknown(nsIURI* aTopWindowURI) {
if (!aTopWindowURI) {
return NS_ERROR_INVALID_ARG;
}
if (mTopWindowURI) {
LOG(
("HttpChannelBase::SetTopWindowURIIfUnknown [this=%p] "
"mTopWindowURI is already set.\n",
this));
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIURI> topWindowURI;
(void)GetTopWindowURI(getter_AddRefs(topWindowURI));
// Don't modify |mTopWindowURI| if we can get one from GetTopWindowURI().
if (topWindowURI) {
LOG(
("HttpChannelBase::SetTopWindowURIIfUnknown [this=%p] "
"Return an error since we got a top window uri.\n",
this));
return NS_ERROR_FAILURE;
}
mTopWindowURI = aTopWindowURI;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetTopWindowURI(nsIURI** aTopWindowURI) {
nsCOMPtr<nsIURI> uriBeingLoaded =
AntiTrackingUtils::MaybeGetDocumentURIBeingLoaded(this);
return GetTopWindowURI(uriBeingLoaded, aTopWindowURI);
}
nsresult HttpBaseChannel::GetTopWindowURI(nsIURI* aURIBeingLoaded,
nsIURI** aTopWindowURI) {
nsresult rv = NS_OK;
nsCOMPtr<mozIThirdPartyUtil> util;
// Only compute the top window URI once. In e10s, this must be computed in the
// child. The parent gets the top window URI through HttpChannelOpenArgs.
if (!mTopWindowURI) {
util = components::ThirdPartyUtil::Service();
if (!util) {
return NS_ERROR_NOT_AVAILABLE;
}
nsCOMPtr<mozIDOMWindowProxy> win;
rv = util->GetTopWindowForChannel(this, aURIBeingLoaded,
getter_AddRefs(win));
if (NS_SUCCEEDED(rv)) {
rv = util->GetURIFromWindow(win, getter_AddRefs(mTopWindowURI));
#if DEBUG
if (mTopWindowURI) {
nsCString spec;
if (NS_SUCCEEDED(mTopWindowURI->GetSpec(spec))) {
LOG(("HttpChannelBase::Setting topwindow URI spec %s [this=%p]\n",
spec.get(), this));
}
}
#endif
}
}
*aTopWindowURI = do_AddRef(mTopWindowURI).take();
return rv;
}
NS_IMETHODIMP
HttpBaseChannel::GetDocumentURI(nsIURI** aDocumentURI) {
NS_ENSURE_ARG_POINTER(aDocumentURI);
*aDocumentURI = do_AddRef(mDocumentURI).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetDocumentURI(nsIURI* aDocumentURI) {
ENSURE_CALLED_BEFORE_CONNECT();
mDocumentURI = aDocumentURI;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestVersion(uint32_t* major, uint32_t* minor) {
HttpVersion version = mRequestHead.Version();
if (major) {
*major = static_cast<uint32_t>(version) / 10;
}
if (minor) {
*minor = static_cast<uint32_t>(version) % 10;
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetResponseVersion(uint32_t* major, uint32_t* minor) {
if (!mResponseHead) {
*major = *minor = 0; // we should at least be kind about it
return NS_ERROR_NOT_AVAILABLE;
}
HttpVersion version = mResponseHead->Version();
if (major) {
*major = static_cast<uint32_t>(version) / 10;
}
if (minor) {
*minor = static_cast<uint32_t>(version) % 10;
}
return NS_OK;
}
bool HttpBaseChannel::IsBrowsingContextDiscarded() const {
// If there is no loadGroup attached to the current channel, we check the
// global private browsing state for the private channel instead. For
// non-private channel, we will always return false here.
//
// Note that we can only access the global private browsing state in the
// parent process. So, we will fallback to just return false in the content
// process.
if (!mLoadGroup) {
if (!XRE_IsParentProcess()) {
return false;
}
return mLoadInfo->GetOriginAttributes().IsPrivateBrowsing() &&
!dom::CanonicalBrowsingContext::IsPrivateBrowsingActive();
}
return mLoadGroup->GetIsBrowsingContextDiscarded();
}
// https://mikewest.github.io/corpp/#process-navigation-response
nsresult HttpBaseChannel::ProcessCrossOriginEmbedderPolicyHeader() {
nsresult rv;
if (!StaticPrefs::browser_tabs_remote_useCrossOriginEmbedderPolicy()) {
return NS_OK;
}
// Only consider Cross-Origin-Embedder-Policy for document loads.
if (mLoadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_DOCUMENT &&
mLoadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_SUBDOCUMENT) {
return NS_OK;
}
nsILoadInfo::CrossOriginEmbedderPolicy resultPolicy =
nsILoadInfo::EMBEDDER_POLICY_NULL;
bool isCoepCredentiallessEnabled;
rv = mLoadInfo->GetIsOriginTrialCoepCredentiallessEnabledForTopLevel(
&isCoepCredentiallessEnabled);
NS_ENSURE_SUCCESS(rv, rv);
rv = GetResponseEmbedderPolicy(isCoepCredentiallessEnabled, &resultPolicy);
if (NS_FAILED(rv)) {
return NS_OK;
}
// https://html.spec.whatwg.org/multipage/origin.html#coep
if (mLoadInfo->GetExternalContentPolicyType() ==
ExtContentPolicy::TYPE_SUBDOCUMENT &&
!nsHttpChannel::IsRedirectStatus(mResponseHead->Status()) &&
mLoadInfo->GetLoadingEmbedderPolicy() !=
nsILoadInfo::EMBEDDER_POLICY_NULL &&
resultPolicy != nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP &&
resultPolicy != nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS) {
return NS_ERROR_DOM_COEP_FAILED;
}
return NS_OK;
}
// https://mikewest.github.io/corpp/#corp-check
nsresult HttpBaseChannel::ProcessCrossOriginResourcePolicyHeader() {
// Fetch 4.5.9
dom::RequestMode requestMode;
MOZ_ALWAYS_SUCCEEDS(GetRequestMode(&requestMode));
// XXX this seems wrong per spec? What about navigate
if (requestMode != RequestMode::No_cors) {
return NS_OK;
}
// We only apply this for resources.
auto extContentPolicyType = mLoadInfo->GetExternalContentPolicyType();
if (extContentPolicyType == ExtContentPolicy::TYPE_DOCUMENT ||
extContentPolicyType == ExtContentPolicy::TYPE_WEBSOCKET ||
extContentPolicyType == ExtContentPolicy::TYPE_SAVEAS_DOWNLOAD) {
return NS_OK;
}
if (extContentPolicyType == ExtContentPolicy::TYPE_SUBDOCUMENT) {
// COEP pref off, skip CORP checking for subdocument.
if (!StaticPrefs::browser_tabs_remote_useCrossOriginEmbedderPolicy()) {
return NS_OK;
}
// COEP 3.2.1.2 when request targets a nested browsing context then embedder
// policy value is "unsafe-none", then return allowed.
if (mLoadInfo->GetLoadingEmbedderPolicy() ==
nsILoadInfo::EMBEDDER_POLICY_NULL) {
return NS_OK;
}
}
MOZ_ASSERT(mLoadInfo->GetLoadingPrincipal(),
"Resources should always have a LoadingPrincipal");
if (!mResponseHead) {
return NS_OK;
}
if (mLoadInfo->GetLoadingPrincipal()->IsSystemPrincipal()) {
return NS_OK;
}
nsAutoCString content;
(void)mResponseHead->GetHeader(nsHttp::Cross_Origin_Resource_Policy, content);
if (StaticPrefs::browser_tabs_remote_useCrossOriginEmbedderPolicy()) {
if (content.IsEmpty()) {
if (mLoadInfo->GetLoadingEmbedderPolicy() ==
nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS) {
bool requestIncludesCredentials = false;
nsresult rv = GetCorsIncludeCredentials(&requestIncludesCredentials);
if (NS_FAILED(rv)) {
return NS_OK;
}
// COEP: Set policy to `same-origin` if: response’s
// request-includes-credentials is true, or forNavigation is true.
if (requestIncludesCredentials ||
extContentPolicyType == ExtContentPolicyType::TYPE_SUBDOCUMENT) {
content = "same-origin"_ns;
}
} else if (mLoadInfo->GetLoadingEmbedderPolicy() ==
nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP) {
// COEP 3.2.1.6 If policy is null, and embedder policy is
// "require-corp", set policy to "same-origin". Note that we treat
// invalid value as "cross-origin", which spec indicates. We might want
// to make that stricter.
content = "same-origin"_ns;
}
}
}
if (content.IsEmpty()) {
return NS_OK;
}
nsCOMPtr<nsIPrincipal> channelOrigin;
nsContentUtils::GetSecurityManager()->GetChannelResultPrincipal(
this, getter_AddRefs(channelOrigin));
// Cross-Origin-Resource-Policy = %s"same-origin" / %s"same-site" /
// %s"cross-origin"
if (content.EqualsLiteral("same-origin")) {
if (!channelOrigin->Equals(mLoadInfo->GetLoadingPrincipal())) {
return NS_ERROR_DOM_CORP_FAILED;
}
return NS_OK;
}
if (content.EqualsLiteral("same-site")) {
nsAutoCString documentBaseDomain;
nsAutoCString resourceBaseDomain;
mLoadInfo->GetLoadingPrincipal()->GetBaseDomain(documentBaseDomain);
channelOrigin->GetBaseDomain(resourceBaseDomain);
if (documentBaseDomain != resourceBaseDomain) {
return NS_ERROR_DOM_CORP_FAILED;
}
nsCOMPtr<nsIURI> resourceURI = channelOrigin->GetURI();
if (!mLoadInfo->GetLoadingPrincipal()->SchemeIs("https") &&
resourceURI->SchemeIs("https")) {
return NS_ERROR_DOM_CORP_FAILED;
}
return NS_OK;
}
return NS_OK;
}
// See https://gist.github.com/annevk/6f2dd8c79c77123f39797f6bdac43f3e
// This method runs steps 1-4 of the algorithm to compare
// cross-origin-opener policies
static bool CompareCrossOriginOpenerPolicies(
nsILoadInfo::CrossOriginOpenerPolicy documentPolicy,
nsIPrincipal* documentOrigin,
nsILoadInfo::CrossOriginOpenerPolicy resultPolicy,
nsIPrincipal* resultOrigin) {
if (documentPolicy == nsILoadInfo::OPENER_POLICY_UNSAFE_NONE &&
resultPolicy == nsILoadInfo::OPENER_POLICY_UNSAFE_NONE) {
return true;
}
if (documentPolicy == nsILoadInfo::OPENER_POLICY_UNSAFE_NONE ||
resultPolicy == nsILoadInfo::OPENER_POLICY_UNSAFE_NONE) {
return false;
}
if (documentPolicy == resultPolicy && documentOrigin->Equals(resultOrigin)) {
return true;
}
return false;
}
// This runs steps 1-5 of the algorithm when navigating a top level document.
// See https://gist.github.com/annevk/6f2dd8c79c77123f39797f6bdac43f3e
nsresult HttpBaseChannel::ComputeCrossOriginOpenerPolicyMismatch() {
MOZ_ASSERT(XRE_IsParentProcess());
StoreHasCrossOriginOpenerPolicyMismatch(false);
if (!StaticPrefs::browser_tabs_remote_useCrossOriginOpenerPolicy()) {
return NS_OK;
}
// Only consider Cross-Origin-Opener-Policy for toplevel document loads.
if (mLoadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_DOCUMENT) {
return NS_OK;
}
// Maybe the channel failed and we have no response head?
if (!mResponseHead) {
// Not having a response head is not a hard failure at the point where
// this method is called.
return NS_OK;
}
RefPtr<mozilla::dom::BrowsingContext> ctx;
mLoadInfo->GetBrowsingContext(getter_AddRefs(ctx));
// In xpcshell-tests we don't always have a browsingContext
if (!ctx) {
return NS_OK;
}
nsCOMPtr<nsIPrincipal> resultOrigin;
nsContentUtils::GetSecurityManager()->GetChannelResultPrincipal(
this, getter_AddRefs(resultOrigin));
// Get the policy of the active document, and the policy for the result.
nsILoadInfo::CrossOriginOpenerPolicy documentPolicy = ctx->GetOpenerPolicy();
nsILoadInfo::CrossOriginOpenerPolicy resultPolicy =
nsILoadInfo::OPENER_POLICY_UNSAFE_NONE;
(void)ComputeCrossOriginOpenerPolicy(documentPolicy, &resultPolicy);
mComputedCrossOriginOpenerPolicy = resultPolicy;
// Add a permission to mark this site as high-value into the permission DB.
if (resultPolicy != nsILoadInfo::OPENER_POLICY_UNSAFE_NONE) {
mozilla::dom::AddHighValuePermission(
resultOrigin, mozilla::dom::kHighValueCOOPPermission);
}
// If bc's popup sandboxing flag set is not empty and potentialCOOP is
// non-null, then navigate bc to a network error and abort these steps.
if (resultPolicy != nsILoadInfo::OPENER_POLICY_UNSAFE_NONE &&
mLoadInfo->GetSandboxFlags()) {
LOG((
"HttpBaseChannel::ComputeCrossOriginOpenerPolicyMismatch network error "
"for non empty sandboxing and non null COOP"));
return NS_ERROR_DOM_COOP_FAILED;
}
// In xpcshell-tests we don't always have a current window global
RefPtr<mozilla::dom::WindowGlobalParent> currentWindowGlobal =
ctx->Canonical()->GetCurrentWindowGlobal();
if (!currentWindowGlobal) {
return NS_OK;
}
// We use the top window principal as the documentOrigin
nsCOMPtr<nsIPrincipal> documentOrigin =
currentWindowGlobal->DocumentPrincipal();
bool compareResult = CompareCrossOriginOpenerPolicies(
documentPolicy, documentOrigin, resultPolicy, resultOrigin);
if (LOG_ENABLED()) {
LOG(
("HttpBaseChannel::HasCrossOriginOpenerPolicyMismatch - "
"doc:%d result:%d - compare:%d\n",
documentPolicy, resultPolicy, compareResult));
nsAutoCString docOrigin("(null)");
nsCOMPtr<nsIURI> uri = documentOrigin->GetURI();
if (uri) {
uri->GetSpec(docOrigin);
}
nsAutoCString resOrigin("(null)");
uri = resultOrigin->GetURI();
if (uri) {
uri->GetSpec(resOrigin);
}
LOG(("doc origin:%s - res origin: %s\n", docOrigin.get(), resOrigin.get()));
}
if (compareResult) {
return NS_OK;
}
// If one of the following is false:
// - document's policy is same-origin-allow-popups
// - resultPolicy is null
// - doc is the initial about:blank document
// then we have a mismatch.
if (documentPolicy != nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_ALLOW_POPUPS) {
StoreHasCrossOriginOpenerPolicyMismatch(true);
return NS_OK;
}
if (resultPolicy != nsILoadInfo::OPENER_POLICY_UNSAFE_NONE) {
StoreHasCrossOriginOpenerPolicyMismatch(true);
return NS_OK;
}
if (!currentWindowGlobal->IsInitialDocument()) {
StoreHasCrossOriginOpenerPolicyMismatch(true);
return NS_OK;
}
return NS_OK;
}
nsresult HttpBaseChannel::ProcessCrossOriginSecurityHeaders() {
StoreProcessCrossOriginSecurityHeadersCalled(true);
nsresult rv = ProcessCrossOriginEmbedderPolicyHeader();
if (NS_FAILED(rv)) {
return rv;
}
rv = ProcessCrossOriginResourcePolicyHeader();
if (NS_FAILED(rv)) {
return rv;
}
return ComputeCrossOriginOpenerPolicyMismatch();
}
enum class Report { Error, Warning };
// Helper Function to report messages to the console when the loaded
// script had a wrong MIME type.
void ReportMimeTypeMismatch(HttpBaseChannel* aChannel, const char* aMessageName,
nsIURI* aURI, const nsACString& aContentType,
Report report) {
NS_ConvertUTF8toUTF16 spec(aURI->GetSpecOrDefault());
NS_ConvertUTF8toUTF16 contentType(aContentType);
aChannel->LogMimeTypeMismatch(nsCString(aMessageName),
report == Report::Warning, spec, contentType);
}
// Check and potentially enforce X-Content-Type-Options: nosniff
nsresult ProcessXCTO(HttpBaseChannel* aChannel, nsIURI* aURI,
nsHttpResponseHead* aResponseHead,
nsILoadInfo* aLoadInfo) {
if (!aURI || !aResponseHead || !aLoadInfo) {
// if there is no uri, no response head or no loadInfo, then there is
// nothing to do
return NS_OK;
}
// 1) Query the XCTO header and check if 'nosniff' is the first value.
nsAutoCString contentTypeOptionsHeader;
if (!aResponseHead->GetContentTypeOptionsHeader(contentTypeOptionsHeader)) {
// if failed to get XCTO header, then there is nothing to do.
return NS_OK;
}
// let's compare the header (ignoring case)
// e.g. "NoSniFF" -> "nosniff"
// if it's not 'nosniff' then there is nothing to do here
if (!contentTypeOptionsHeader.EqualsIgnoreCase("nosniff")) {
// since we are getting here, the XCTO header was sent;
// a non matching value most likely means a mistake happenend;
// e.g. sending 'nosnif' instead of 'nosniff', let's log a warning.
AutoTArray<nsString, 1> params;
CopyUTF8toUTF16(contentTypeOptionsHeader, *params.AppendElement());
RefPtr<dom::Document> doc;
aLoadInfo->GetLoadingDocument(getter_AddRefs(doc));
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "XCTO"_ns, doc,
nsContentUtils::eSECURITY_PROPERTIES,
"XCTOHeaderValueMissing", params);
return NS_OK;
}
// 2) Query the content type from the channel
nsAutoCString contentType;
aResponseHead->ContentType(contentType);
// 3) Compare the expected MIME type with the actual type
if (aLoadInfo->GetExternalContentPolicyType() ==
ExtContentPolicy::TYPE_STYLESHEET) {
if (contentType.EqualsLiteral(TEXT_CSS)) {
return NS_OK;
}
ReportMimeTypeMismatch(aChannel, "MimeTypeMismatch2", aURI, contentType,
Report::Error);
return NS_ERROR_CORRUPTED_CONTENT;
}
if (aLoadInfo->GetExternalContentPolicyType() ==
ExtContentPolicy::TYPE_SCRIPT) {
if (nsContentUtils::IsJavascriptMIMEType(
NS_ConvertUTF8toUTF16(contentType))) {
return NS_OK;
}
ReportMimeTypeMismatch(aChannel, "MimeTypeMismatch2", aURI, contentType,
Report::Error);
return NS_ERROR_CORRUPTED_CONTENT;
}
auto policyType = aLoadInfo->GetExternalContentPolicyType();
if (policyType == ExtContentPolicy::TYPE_DOCUMENT ||
policyType == ExtContentPolicy::TYPE_SUBDOCUMENT ||
policyType == ExtContentPolicy::TYPE_OBJECT) {
// If the header XCTO nosniff is set for any browsing context, then
// we set the skipContentSniffing flag on the Loadinfo. Within
// GetMIMETypeFromContent we then bail early and do not do any sniffing.
aLoadInfo->SetSkipContentSniffing(true);
return NS_OK;
}
return NS_OK;
}
nsresult EnsureMIMEOfJSONModule(HttpBaseChannel* aChannel, nsIURI* aURI,
nsHttpResponseHead* aResponseHead,
nsILoadInfo* aLoadInfo) {
if (!aURI || !aResponseHead || !aLoadInfo) {
// if there is no uri, no response head or no loadInfo, then there is
// nothing to do
return NS_OK;
}
if (aLoadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_JSON) {
// if this is not a JSON load, then there is nothing to do
return NS_OK;
}
nsAutoCString contentType;
aResponseHead->ContentType(contentType);
NS_ConvertUTF8toUTF16 typeString(contentType);
if (nsContentUtils::IsJsonMimeType(typeString)) {
return NS_OK;
}
ReportMimeTypeMismatch(aChannel, "BlockJsonModuleWithWrongMimeType", aURI,
contentType, Report::Error);
return NS_ERROR_CORRUPTED_CONTENT;
}
// Ensure that a load of type script has correct MIME type
nsresult EnsureMIMEOfScript(HttpBaseChannel* aChannel, nsIURI* aURI,
nsHttpResponseHead* aResponseHead,
nsILoadInfo* aLoadInfo) {
if (!aURI || !aResponseHead || !aLoadInfo) {
// if there is no uri, no response head or no loadInfo, then there is
// nothing to do
return NS_OK;
}
if (aLoadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_SCRIPT) {
// if this is not a script load, then there is nothing to do
return NS_OK;
}
nsAutoCString contentType;
aResponseHead->ContentType(contentType);
NS_ConvertUTF8toUTF16 typeString(contentType);
if (nsContentUtils::IsJavascriptMIMEType(typeString)) {
// script load has type script
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eJavascript)
.Add();
return NS_OK;
}
const auto internalPolicyType = aLoadInfo->InternalContentPolicyType();
if (internalPolicyType ==
nsIContentPolicy::TYPE_INTERNAL_WORKER_STATIC_MODULE &&
nsContentUtils::IsJsonMimeType(typeString)) {
// script and json are both allowed
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eTextJson)
.Add();
return NS_OK;
}
switch (aLoadInfo->InternalContentPolicyType()) {
case nsIContentPolicy::TYPE_SCRIPT:
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
case nsIContentPolicy::TYPE_INTERNAL_MODULE:
case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD:
case nsIContentPolicy::TYPE_INTERNAL_CHROMEUTILS_COMPILED_SCRIPT:
case nsIContentPolicy::TYPE_INTERNAL_FRAME_MESSAGEMANAGER_SCRIPT:
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eScriptLoad)
.Add();
break;
case nsIContentPolicy::TYPE_INTERNAL_WORKER:
case nsIContentPolicy::TYPE_INTERNAL_WORKER_STATIC_MODULE:
case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eWorkerLoad)
.Add();
break;
case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
glean::http::script_block_incorrect_mime
.EnumGet(
glean::http::ScriptBlockIncorrectMimeLabel::eServiceworkerLoad)
.Add();
break;
case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS:
glean::http::script_block_incorrect_mime
.EnumGet(
glean::http::ScriptBlockIncorrectMimeLabel::eImportscriptLoad)
.Add();
break;
case nsIContentPolicy::TYPE_INTERNAL_AUDIOWORKLET:
case nsIContentPolicy::TYPE_INTERNAL_PAINTWORKLET:
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eWorkletLoad)
.Add();
break;
default:
MOZ_ASSERT_UNREACHABLE("unexpected script type");
break;
}
if (aLoadInfo->GetLoadingPrincipal()->IsSameOrigin(aURI)) {
// same origin
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eSameOrigin)
.Add();
} else {
bool cors = false;
nsAutoCString corsOrigin;
nsresult rv = aResponseHead->GetHeader(
nsHttp::ResolveAtom("Access-Control-Allow-Origin"_ns), corsOrigin);
if (NS_SUCCEEDED(rv)) {
if (corsOrigin.Equals("*")) {
cors = true;
} else {
nsCOMPtr<nsIURI> corsOriginURI;
rv = NS_NewURI(getter_AddRefs(corsOriginURI), corsOrigin);
if (NS_SUCCEEDED(rv)) {
if (aLoadInfo->GetLoadingPrincipal()->IsSameOrigin(corsOriginURI)) {
cors = true;
}
}
}
}
if (cors) {
// cors origin
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eCorsOrigin)
.Add();
} else {
// cross origin
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eCrossOrigin)
.Add();
}
}
bool block = false;
if (StringBeginsWith(contentType, "image/"_ns)) {
// script load has type image
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eImage)
.Add();
block = true;
} else if (StringBeginsWith(contentType, "audio/"_ns)) {
// script load has type audio
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eAudio)
.Add();
block = true;
} else if (StringBeginsWith(contentType, "video/"_ns)) {
// script load has type video
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eVideo)
.Add();
block = true;
} else if (StringBeginsWith(contentType, "text/csv"_ns)) {
// script load has type text/csv
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eTextCsv)
.Add();
block = true;
}
if (block) {
ReportMimeTypeMismatch(aChannel, "BlockScriptWithWrongMimeType2", aURI,
contentType, Report::Error);
return NS_ERROR_CORRUPTED_CONTENT;
}
if (StringBeginsWith(contentType, "text/plain"_ns)) {
// script load has type text/plain
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eTextPlain)
.Add();
} else if (StringBeginsWith(contentType, "text/xml"_ns)) {
// script load has type text/xml
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eTextXml)
.Add();
} else if (StringBeginsWith(contentType, "application/octet-stream"_ns)) {
// script load has type application/octet-stream
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eAppOctetStream)
.Add();
} else if (StringBeginsWith(contentType, "application/xml"_ns)) {
// script load has type application/xml
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eAppXml)
.Add();
} else if (StringBeginsWith(contentType, "application/json"_ns)) {
// script load has type application/json
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eAppJson)
.Add();
} else if (StringBeginsWith(contentType, "text/json"_ns)) {
// script load has type text/json
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eTextJson)
.Add();
} else if (StringBeginsWith(contentType, "text/html"_ns)) {
// script load has type text/html
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eTextHtml)
.Add();
} else if (contentType.IsEmpty()) {
// script load has no type
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eEmpty)
.Add();
} else {
// script load has unknown type
glean::http::script_block_incorrect_mime
.EnumGet(glean::http::ScriptBlockIncorrectMimeLabel::eUnknown)
.Add();
}
nsContentPolicyType internalType = aLoadInfo->InternalContentPolicyType();
// We restrict importScripts() in worker code to JavaScript MIME types.
if (internalType == nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS ||
internalType == nsIContentPolicy::TYPE_INTERNAL_WORKER_STATIC_MODULE) {
ReportMimeTypeMismatch(aChannel, "BlockImportScriptsWithWrongMimeType",
aURI, contentType, Report::Error);
return NS_ERROR_CORRUPTED_CONTENT;
}
if (internalType == nsIContentPolicy::TYPE_INTERNAL_WORKER ||
internalType == nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER) {
// Do not block the load if the feature is not enabled.
if (!StaticPrefs::security_block_Worker_with_wrong_mime()) {
return NS_OK;
}
ReportMimeTypeMismatch(aChannel, "BlockWorkerWithWrongMimeType", aURI,
contentType, Report::Error);
return NS_ERROR_CORRUPTED_CONTENT;
}
// ES6 modules require a strict MIME type check.
if (internalType == nsIContentPolicy::TYPE_INTERNAL_MODULE ||
internalType == nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD) {
ReportMimeTypeMismatch(aChannel, "BlockModuleWithWrongMimeType", aURI,
contentType, Report::Error);
return NS_ERROR_CORRUPTED_CONTENT;
}
return NS_OK;
}
// Warn when a load of type script uses a wrong MIME type and
// wasn't blocked by EnsureMIMEOfScript or ProcessXCTO.
void WarnWrongMIMEOfScript(HttpBaseChannel* aChannel, nsIURI* aURI,
nsHttpResponseHead* aResponseHead,
nsILoadInfo* aLoadInfo) {
if (!aURI || !aResponseHead || !aLoadInfo) {
// If there is no uri, no response head or no loadInfo, then there is
// nothing to do.
return;
}
if (aLoadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_SCRIPT) {
// If this is not a script load, then there is nothing to do.
return;
}
bool succeeded;
MOZ_ALWAYS_SUCCEEDS(aChannel->GetRequestSucceeded(&succeeded));
if (!succeeded) {
// Do not warn for failed loads: HTTP error pages are usually in HTML.
return;
}
nsAutoCString contentType;
aResponseHead->ContentType(contentType);
NS_ConvertUTF8toUTF16 typeString(contentType);
if (nsContentUtils::IsJavascriptMIMEType(typeString)) {
return;
}
ReportMimeTypeMismatch(aChannel, "WarnScriptWithWrongMimeType", aURI,
contentType, Report::Warning);
}
nsresult HttpBaseChannel::ValidateMIMEType() {
nsresult rv = EnsureMIMEOfScript(this, mURI, mResponseHead.get(), mLoadInfo);
if (NS_FAILED(rv)) {
return rv;
}
rv = EnsureMIMEOfJSONModule(this, mURI, mResponseHead.get(), mLoadInfo);
if (NS_FAILED(rv)) {
return rv;
}
rv = ProcessXCTO(this, mURI, mResponseHead.get(), mLoadInfo);
if (NS_FAILED(rv)) {
return rv;
}
WarnWrongMIMEOfScript(this, mURI, mResponseHead.get(), mLoadInfo);
return NS_OK;
}
bool HttpBaseChannel::ShouldFilterOpaqueResponse(
OpaqueResponseFilterFetch aFilterType) const {
MOZ_ASSERT(ShouldBlockOpaqueResponse());
if (!mLoadInfo || ConfiguredFilterFetchResponseBehaviour() != aFilterType) {
return false;
}
// We should filter a response in the parent if it is opaque and is the result
// of a fetch() function from the Fetch specification.
return mLoadInfo->InternalContentPolicyType() == nsIContentPolicy::TYPE_FETCH;
}
bool HttpBaseChannel::ShouldBlockOpaqueResponse() const {
if (!mURI || !mResponseHead || !mLoadInfo) {
// if there is no uri, no response head or no loadInfo, then there is
// nothing to do
LOGORB("No block: no mURI, mResponseHead, or mLoadInfo");
return false;
}
nsCOMPtr<nsIPrincipal> principal = mLoadInfo->GetLoadingPrincipal();
if (!principal || principal->IsSystemPrincipal()) {
// If it's a top-level load or a system principal, then there is nothing to
// do.
LOGORB("No block: top-level load or system principal");
return false;
}
// Check if the response is a opaque response, which means requestMode should
// be RequestMode::No_cors and responseType should be ResponseType::Opaque.
nsContentPolicyType contentPolicy = mLoadInfo->InternalContentPolicyType();
// Skip the RequestMode would be RequestMode::Navigate
if (contentPolicy == nsIContentPolicy::TYPE_DOCUMENT ||
contentPolicy == nsIContentPolicy::TYPE_SUBDOCUMENT ||
contentPolicy == nsIContentPolicy::TYPE_INTERNAL_FRAME ||
contentPolicy == nsIContentPolicy::TYPE_INTERNAL_IFRAME ||
// Skip the RequestMode would be RequestMode::Same_origin
contentPolicy == nsIContentPolicy::TYPE_INTERNAL_WORKER ||
contentPolicy == nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER) {
return false;
}
uint32_t securityMode = mLoadInfo->GetSecurityMode();
// Skip when RequestMode would not be RequestMode::no_cors
if (securityMode !=
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT &&
securityMode != nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL) {
LOGORB("No block: not no_cors requests");
return false;
}
// Only continue when ResponseType would be ResponseType::Opaque
if (mLoadInfo->GetTainting() != mozilla::LoadTainting::Opaque) {
LOGORB("No block: not opaque response");
return false;
}
auto extContentPolicyType = mLoadInfo->GetExternalContentPolicyType();
if (extContentPolicyType == ExtContentPolicy::TYPE_OBJECT ||
extContentPolicyType == ExtContentPolicy::TYPE_WEBSOCKET ||
extContentPolicyType == ExtContentPolicy::TYPE_SAVEAS_DOWNLOAD) {
LOGORB("No block: object || websocket request || save as download");
return false;
}
// Ignore the request from object or embed elements
if (mLoadInfo->GetIsFromObjectOrEmbed()) {
LOGORB("No block: Request From <object> or <embed>");
return false;
}
// Exclude no_cors System XHR
if (extContentPolicyType == ExtContentPolicy::TYPE_XMLHTTPREQUEST) {
if (securityMode ==
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT) {
LOGORB("No block: System XHR");
return false;
}
}
// Exclude no_cors web-identity
if (extContentPolicyType == ExtContentPolicy::TYPE_WEB_IDENTITY) {
if (securityMode ==
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT) {
printf("Allowing ORB for web-identity\n");
LOGORB("No block: System web-identity");
return false;
}
}
uint32_t httpsOnlyStatus = mLoadInfo->GetHttpsOnlyStatus();
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_BYPASS_ORB) {
LOGORB("No block: HTTPS_ONLY_BYPASS_ORB");
return false;
}
bool isInDevToolsContext;
mLoadInfo->GetIsInDevToolsContext(&isInDevToolsContext);
if (isInDevToolsContext) {
LOGORB("No block: Request created by devtools");
return false;
}
return true;
}
OpaqueResponse HttpBaseChannel::BlockOrFilterOpaqueResponse(
OpaqueResponseBlocker* aORB, const nsAString& aReason,
const OpaqueResponseBlockedTelemetryReason aTelemetryReason,
const char* aFormat, ...) {
NimbusFeatures::RecordExposureEvent("opaqueResponseBlocking"_ns, true);
const bool shouldFilter =
ShouldFilterOpaqueResponse(OpaqueResponseFilterFetch::BlockedByORB);
if (MOZ_UNLIKELY(MOZ_LOG_TEST(GetORBLog(), LogLevel::Debug))) {
va_list ap;
va_start(ap, aFormat);
nsVprintfCString logString(aFormat, ap);
va_end(ap);
LOGORB("%s: %s", shouldFilter ? "Filtered" : "Blocked", logString.get());
}
if (shouldFilter) {
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eFilteredFetch)
.Add();
// The existence of `mORB` depends on `BlockOrFilterOpaqueResponse` being
// called before or after sniffing has completed.
// Another requirement is that `OpaqueResponseFilter` must come after
// `OpaqueResponseBlocker`, which is why in the case of having an
// `OpaqueResponseBlocker` we let it handle creating an
// `OpaqueResponseFilter`.
if (aORB) {
MOZ_DIAGNOSTIC_ASSERT(!mORB || aORB == mORB);
aORB->FilterResponse();
} else {
mListener = new OpaqueResponseFilter(mListener);
}
return OpaqueResponse::Allow;
}
LogORBError(aReason, aTelemetryReason);
return OpaqueResponse::Block;
}
// The specification for ORB is currently being written:
// https://whatpr.org/fetch/1442.html#orb-algorithm
// The `opaque-response-safelist check` is implemented in:
// * `HttpBaseChannel::PerformOpaqueResponseSafelistCheckBeforeSniff`
// * `nsHttpChannel::DisableIsOpaqueResponseAllowedAfterSniffCheck`
// * `HttpBaseChannel::PerformOpaqueResponseSafelistCheckAfterSniff`
// * `OpaqueResponseBlocker::ValidateJavaScript`
OpaqueResponse
HttpBaseChannel::PerformOpaqueResponseSafelistCheckBeforeSniff() {
MOZ_ASSERT(XRE_IsParentProcess());
// https://whatpr.org/fetch/1442.html#http-fetch, step 6.4
if (!ShouldBlockOpaqueResponse()) {
return OpaqueResponse::Allow;
}
// Regardless of if ORB is enabled or not, we check if we should filter the
// response in the parent. This way data won't reach a content process that
// will create a filtered `Response` object. This is enabled when
// 'browser.opaqueResponseBlocking.filterFetchResponse' is
// `OpaqueResponseFilterFetch::All`.
// See https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
if (ShouldFilterOpaqueResponse(OpaqueResponseFilterFetch::All)) {
mListener = new OpaqueResponseFilter(mListener);
// If we're filtering a response in the parent, there will be no data to
// determine if it should be blocked or not so the only option we have is to
// allow it.
return OpaqueResponse::Allow;
}
if (!mCachedOpaqueResponseBlockingPref) {
return OpaqueResponse::Allow;
}
// If ORB is enabled, we check if we should filter the response in the parent.
// This way data won't reach a content process that will create a filtered
// `Response` object. We allow ORB to determine if the response should be
// blocked or filtered, but regardless no data should reach the content
// process. This is enabled when
// 'browser.opaqueResponseBlocking.filterFetchResponse' is
// `OpaqueResponseFilterFetch::AllowedByORB`.
// See https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
if (ShouldFilterOpaqueResponse(OpaqueResponseFilterFetch::AllowedByORB)) {
mListener = new OpaqueResponseFilter(mListener);
}
glean::opaque_response_blocking::cross_origin_opaque_response_count.Add(1);
PROFILER_MARKER_TEXT("ORB safelist check", NETWORK, {}, "Before sniff"_ns);
// https://whatpr.org/fetch/1442.html#orb-algorithm
// Step 1
nsAutoCString contentType;
mResponseHead->ContentType(contentType);
// Step 2
nsAutoCString contentTypeOptionsHeader;
bool nosniff =
mResponseHead->GetContentTypeOptionsHeader(contentTypeOptionsHeader) &&
contentTypeOptionsHeader.EqualsIgnoreCase("nosniff");
// Step 3
switch (GetOpaqueResponseBlockedReason(contentType, mResponseHead->Status(),
nosniff)) {
case OpaqueResponseBlockedReason::ALLOWED_SAFE_LISTED:
// Step 3.1
return OpaqueResponse::Allow;
case OpaqueResponseBlockedReason::ALLOWED_SAFE_LISTED_SPEC_BREAKING:
LOGORB("Allowed %s in a spec breaking way", contentType.get());
return OpaqueResponse::Allow;
case OpaqueResponseBlockedReason::BLOCKED_BLOCKLISTED_NEVER_SNIFFED:
return BlockOrFilterOpaqueResponse(
mORB, u"mimeType is an opaque-blocklisted-never-sniffed MIME type"_ns,
OpaqueResponseBlockedTelemetryReason::eMimeNeverSniffed,
"BLOCKED_BLOCKLISTED_NEVER_SNIFFED");
case OpaqueResponseBlockedReason::BLOCKED_206_AND_BLOCKLISTED:
// Step 3.3
return BlockOrFilterOpaqueResponse(
mORB,
u"response's status is 206 and mimeType is an opaque-blocklisted MIME type"_ns,
OpaqueResponseBlockedTelemetryReason::eResp206Blclisted,
"BLOCKED_206_AND_BLOCKEDLISTED");
case OpaqueResponseBlockedReason::
BLOCKED_NOSNIFF_AND_EITHER_BLOCKLISTED_OR_TEXTPLAIN:
// Step 3.4
return BlockOrFilterOpaqueResponse(
mORB,
u"nosniff is true and mimeType is an opaque-blocklisted MIME type or its essence is 'text/plain'"_ns,
OpaqueResponseBlockedTelemetryReason::eNosniffBlcOrTextp,
"BLOCKED_NOSNIFF_AND_EITHER_BLOCKLISTED_OR_TEXTPLAIN");
default:
break;
}
// Step 4
// If it's a media subsequent request, we assume that it will only be made
// after a successful initial request.
bool isMediaRequest;
mLoadInfo->GetIsMediaRequest(&isMediaRequest);
if (isMediaRequest) {
bool isMediaInitialRequest;
mLoadInfo->GetIsMediaInitialRequest(&isMediaInitialRequest);
if (!isMediaInitialRequest) {
return OpaqueResponse::Allow;
}
}
// Step 5
if (mResponseHead->Status() == 206 &&
!IsFirstPartialResponse(*mResponseHead)) {
return BlockOrFilterOpaqueResponse(
mORB, u"response status is 206 and not first partial response"_ns,
OpaqueResponseBlockedTelemetryReason::eResp206Blclisted,
"Is not a valid partial response given 0");
}
// Setup for steps 6, 7, 8 and 10.
// Steps 6 and 7 are handled by the sniffer framework.
// Steps 8 and 10 by are handled by
// `nsHttpChannel::DisableIsOpaqueResponseAllowedAfterSniffCheck`
if (mLoadFlags & nsIChannel::LOAD_CALL_CONTENT_SNIFFERS) {
mSnifferCategoryType = SnifferCategoryType::All;
} else {
mSnifferCategoryType = SnifferCategoryType::OpaqueResponseBlocking;
}
mLoadFlags |= (nsIChannel::LOAD_CALL_CONTENT_SNIFFERS |
nsIChannel::LOAD_MEDIA_SNIFFER_OVERRIDES_CONTENT_TYPE);
// Install an input stream listener that performs ORB checks that depend on
// inspecting the incoming data. It is crucial that `OnStartRequest` is called
// on this listener either after sniffing is completed or that we skip
// sniffing, otherwise `OpaqueResponseBlocker` will allow responses that it
// shouldn't.
mORB = new OpaqueResponseBlocker(mListener, this, contentType, nosniff);
mListener = mORB;
nsAutoCString contentEncoding;
nsresult rv =
mResponseHead->GetHeader(nsHttp::Content_Encoding, contentEncoding);
if (NS_SUCCEEDED(rv) && !contentEncoding.IsEmpty()) {
return OpaqueResponse::SniffCompressed;
}
mLoadFlags |= (nsIChannel::LOAD_CALL_CONTENT_SNIFFERS |
nsIChannel::LOAD_MEDIA_SNIFFER_OVERRIDES_CONTENT_TYPE);
return OpaqueResponse::Sniff;
}
// The specification for ORB is currently being written:
// https://whatpr.org/fetch/1442.html#orb-algorithm
// The `opaque-response-safelist check` is implemented in:
// * `HttpBaseChannel::PerformOpaqueResponseSafelistCheckBeforeSniff`
// * `nsHttpChannel::DisableIsOpaqueResponseAllowedAfterSniffCheck`
// * `HttpBaseChannel::PerformOpaqueResponseSafelistCheckAfterSniff`
// * `OpaqueResponseBlocker::ValidateJavaScript`
OpaqueResponse HttpBaseChannel::PerformOpaqueResponseSafelistCheckAfterSniff(
const nsACString& aContentType, bool aNoSniff) {
PROFILER_MARKER_TEXT("ORB safelist check", NETWORK, {}, "After sniff"_ns);
// https://whatpr.org/fetch/1442.html#orb-algorithm
MOZ_ASSERT(XRE_IsParentProcess());
MOZ_ASSERT(mCachedOpaqueResponseBlockingPref);
// Step 9
bool isMediaRequest;
mLoadInfo->GetIsMediaRequest(&isMediaRequest);
if (isMediaRequest) {
return BlockOrFilterOpaqueResponse(
mORB, u"after sniff: media request"_ns,
OpaqueResponseBlockedTelemetryReason::eAfterSniffMedia,
"media request");
}
// Step 11
if (aNoSniff) {
return BlockOrFilterOpaqueResponse(
mORB, u"after sniff: nosniff is true"_ns,
OpaqueResponseBlockedTelemetryReason::eAfterSniffNosniff, "nosniff");
}
// Step 12
if (mResponseHead &&
(mResponseHead->Status() < 200 || mResponseHead->Status() > 299)) {
return BlockOrFilterOpaqueResponse(
mORB, u"after sniff: status code is not in allowed range"_ns,
OpaqueResponseBlockedTelemetryReason::eAfterSniffStaCode,
"status code (%d) is not allowed", mResponseHead->Status());
}
// Step 13
if (!mResponseHead || aContentType.IsEmpty()) {
LOGORB("Allowed: mimeType is failure");
return OpaqueResponse::Allow;
}
// Step 14
if (StringBeginsWith(aContentType, "image/"_ns) ||
StringBeginsWith(aContentType, "video/"_ns) ||
StringBeginsWith(aContentType, "audio/"_ns)) {
return BlockOrFilterOpaqueResponse(
mORB,
u"after sniff: content-type declares image/video/audio, but sniffing fails"_ns,
OpaqueResponseBlockedTelemetryReason::eAfterSniffCtFail,
"ContentType is image/video/audio");
}
return OpaqueResponse::Sniff;
}
bool HttpBaseChannel::NeedOpaqueResponseAllowedCheckAfterSniff() const {
return mORB ? mORB->IsSniffing() : false;
}
void HttpBaseChannel::BlockOpaqueResponseAfterSniff(
const nsAString& aReason,
const OpaqueResponseBlockedTelemetryReason aTelemetryReason) {
MOZ_DIAGNOSTIC_ASSERT(mORB);
LogORBError(aReason, aTelemetryReason);
mORB->BlockResponse(this, NS_BINDING_ABORTED);
}
void HttpBaseChannel::AllowOpaqueResponseAfterSniff() {
MOZ_DIAGNOSTIC_ASSERT(mORB);
mORB->AllowResponse();
}
void HttpBaseChannel::SetChannelBlockedByOpaqueResponse() {
mChannelBlockedByOpaqueResponse = true;
RefPtr<dom::BrowsingContext> browsingContext =
dom::BrowsingContext::GetCurrentTopByBrowserId(mBrowserId);
if (!browsingContext) {
return;
}
dom::WindowContext* windowContext = browsingContext->GetTopWindowContext();
if (windowContext) {
windowContext->Canonical()->SetShouldReportHasBlockedOpaqueResponse(
mLoadInfo->InternalContentPolicyType());
}
}
NS_IMETHODIMP
HttpBaseChannel::SetCookieHeaders(const nsTArray<nsCString>& aCookieHeaders) {
if (mLoadFlags & LOAD_ANONYMOUS) return NS_OK;
// The loadGroup of the channel in the parent process could be null in the
// XPCShell content process test, see test_cookiejars_wrap.js. In this case,
// we cannot explicitly set the loadGroup for the parent channel because it's
// created from the content process. To workaround this, we add a testing pref
// to skip this check.
if (!StaticPrefs::
network_cookie_skip_browsing_context_check_in_parent_for_testing() &&
IsBrowsingContextDiscarded()) {
return NS_OK;
}
// empty header isn't an error
if (aCookieHeaders.IsEmpty()) {
return NS_OK;
}
nsICookieService* cs = gHttpHandler->GetCookieService();
NS_ENSURE_TRUE(cs, NS_ERROR_FAILURE);
for (const nsCString& cookieHeader : aCookieHeaders) {
nsresult rv = cs->SetCookieStringFromHttp(mURI, cookieHeader, this);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetThirdPartyFlags(uint32_t* aFlags) {
*aFlags = LoadThirdPartyFlags();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetThirdPartyFlags(uint32_t aFlags) {
ENSURE_CALLED_BEFORE_ASYNC_OPEN();
StoreThirdPartyFlags(aFlags);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetForceAllowThirdPartyCookie(bool* aForce) {
*aForce = !!(LoadThirdPartyFlags() &
nsIHttpChannelInternal::THIRD_PARTY_FORCE_ALLOW);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetForceAllowThirdPartyCookie(bool aForce) {
ENSURE_CALLED_BEFORE_ASYNC_OPEN();
if (aForce) {
StoreThirdPartyFlags(LoadThirdPartyFlags() |
nsIHttpChannelInternal::THIRD_PARTY_FORCE_ALLOW);
} else {
StoreThirdPartyFlags(LoadThirdPartyFlags() &
~nsIHttpChannelInternal::THIRD_PARTY_FORCE_ALLOW);
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetCanceled(bool* aCanceled) {
*aCanceled = mCanceled;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetChannelIsForDownload(bool* aChannelIsForDownload) {
*aChannelIsForDownload = LoadChannelIsForDownload();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetChannelIsForDownload(bool aChannelIsForDownload) {
StoreChannelIsForDownload(aChannelIsForDownload);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetCacheKeysRedirectChain(nsTArray<nsCString>* cacheKeys) {
auto RedirectedCachekeys = mRedirectedCachekeys.Lock();
auto& ref = RedirectedCachekeys.ref();
ref = WrapUnique(cacheKeys);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLocalAddress(nsACString& addr) {
if (mSelfAddr.raw.family == PR_AF_UNSPEC) return NS_ERROR_NOT_AVAILABLE;
addr.SetLength(kIPv6CStrBufSize);
mSelfAddr.ToStringBuffer(addr.BeginWriting(), kIPv6CStrBufSize);
addr.SetLength(strlen(addr.BeginReading()));
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::TakeAllSecurityMessages(
nsCOMArray<nsISecurityConsoleMessage>& aMessages) {
MOZ_ASSERT(NS_IsMainThread());
aMessages.Clear();
for (const auto& pair : mSecurityConsoleMessages) {
nsresult rv;
nsCOMPtr<nsISecurityConsoleMessage> message =
do_CreateInstance(NS_SECURITY_CONSOLE_MESSAGE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
message->SetTag(pair.first);
message->SetCategory(pair.second);
aMessages.AppendElement(message);
}
MOZ_ASSERT(mSecurityConsoleMessages.Length() == aMessages.Length());
mSecurityConsoleMessages.Clear();
return NS_OK;
}
/* Please use this method with care. This can cause the message
* queue to grow large and cause the channel to take up a lot
* of memory. Use only static string messages and do not add
* server side data to the queue, as that can be large.
* Add only a limited number of messages to the queue to keep
* the channel size down and do so only in rare erroneous situations.
* More information can be found here:
* https://bugzilla.mozilla.org/show_bug.cgi?id=846918
*/
nsresult HttpBaseChannel::AddSecurityMessage(
const nsAString& aMessageTag, const nsAString& aMessageCategory) {
MOZ_ASSERT(NS_IsMainThread());
nsresult rv;
// nsSecurityConsoleMessage is not thread-safe refcounted.
// Delay the object construction until requested.
// See TakeAllSecurityMessages()
std::pair<nsString, nsString> pair(aMessageTag, aMessageCategory);
mSecurityConsoleMessages.AppendElement(std::move(pair));
nsCOMPtr<nsIConsoleService> console(
do_GetService(NS_CONSOLESERVICE_CONTRACTID));
if (!console) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsILoadInfo> loadInfo = LoadInfo();
auto innerWindowID = loadInfo->GetInnerWindowID();
nsAutoString errorText;
rv = nsContentUtils::GetLocalizedString(
nsContentUtils::eSECURITY_PROPERTIES,
NS_ConvertUTF16toUTF8(aMessageTag).get(), errorText);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIScriptError> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
error->InitWithSourceURI(errorText, mURI, 0, 0, nsIScriptError::warningFlag,
NS_ConvertUTF16toUTF8(aMessageCategory),
innerWindowID);
console->LogMessage(error);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLocalPort(int32_t* port) {
NS_ENSURE_ARG_POINTER(port);
if (mSelfAddr.raw.family == PR_AF_INET) {
*port = (int32_t)ntohs(mSelfAddr.inet.port);
} else if (mSelfAddr.raw.family == PR_AF_INET6) {
*port = (int32_t)ntohs(mSelfAddr.inet6.port);
} else {
return NS_ERROR_NOT_AVAILABLE;
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRemoteAddress(nsACString& addr) {
if (mPeerAddr.raw.family == PR_AF_UNSPEC) return NS_ERROR_NOT_AVAILABLE;
addr.SetLength(kIPv6CStrBufSize);
mPeerAddr.ToStringBuffer(addr.BeginWriting(), kIPv6CStrBufSize);
addr.SetLength(strlen(addr.BeginReading()));
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRemotePort(int32_t* port) {
NS_ENSURE_ARG_POINTER(port);
if (mPeerAddr.raw.family == PR_AF_INET) {
*port = (int32_t)ntohs(mPeerAddr.inet.port);
} else if (mPeerAddr.raw.family == PR_AF_INET6) {
*port = (int32_t)ntohs(mPeerAddr.inet6.port);
} else {
return NS_ERROR_NOT_AVAILABLE;
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::HTTPUpgrade(const nsACString& aProtocolName,
nsIHttpUpgradeListener* aListener) {
NS_ENSURE_ARG(!aProtocolName.IsEmpty());
NS_ENSURE_ARG_POINTER(aListener);
mUpgradeProtocol = aProtocolName;
mUpgradeProtocolCallback = aListener;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetOnlyConnect(bool* aOnlyConnect) {
NS_ENSURE_ARG_POINTER(aOnlyConnect);
*aOnlyConnect = mCaps & NS_HTTP_CONNECT_ONLY;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetConnectOnly(bool aTlsTunnel) {
ENSURE_CALLED_BEFORE_CONNECT();
if (!mUpgradeProtocolCallback) {
return NS_ERROR_FAILURE;
}
mCaps |= NS_HTTP_CONNECT_ONLY;
if (aTlsTunnel) {
mCaps |= NS_HTTP_TLS_TUNNEL;
}
mProxyResolveFlags = nsIProtocolProxyService::RESOLVE_PREFER_HTTPS_PROXY |
nsIProtocolProxyService::RESOLVE_ALWAYS_TUNNEL;
return SetLoadFlags(nsIRequest::INHIBIT_CACHING | nsIChannel::LOAD_ANONYMOUS |
nsIRequest::LOAD_BYPASS_CACHE |
nsIChannel::LOAD_BYPASS_SERVICE_WORKER);
}
NS_IMETHODIMP
HttpBaseChannel::GetAllowSpdy(bool* aAllowSpdy) {
NS_ENSURE_ARG_POINTER(aAllowSpdy);
*aAllowSpdy = LoadAllowSpdy();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetAllowSpdy(bool aAllowSpdy) {
StoreAllowSpdy(aAllowSpdy);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetAllowHttp3(bool* aAllowHttp3) {
NS_ENSURE_ARG_POINTER(aAllowHttp3);
*aAllowHttp3 = LoadAllowHttp3();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetAllowHttp3(bool aAllowHttp3) {
StoreAllowHttp3(aAllowHttp3);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetAllowAltSvc(bool* aAllowAltSvc) {
NS_ENSURE_ARG_POINTER(aAllowAltSvc);
*aAllowAltSvc = LoadAllowAltSvc();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetAllowAltSvc(bool aAllowAltSvc) {
StoreAllowAltSvc(aAllowAltSvc);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetBeConservative(bool* aBeConservative) {
NS_ENSURE_ARG_POINTER(aBeConservative);
*aBeConservative = LoadBeConservative();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetBeConservative(bool aBeConservative) {
StoreBeConservative(aBeConservative);
return NS_OK;
}
bool HttpBaseChannel::BypassProxy() {
return StaticPrefs::network_proxy_allow_bypass() && LoadBypassProxy();
}
NS_IMETHODIMP
HttpBaseChannel::GetBypassProxy(bool* aBypassProxy) {
NS_ENSURE_ARG_POINTER(aBypassProxy);
*aBypassProxy = BypassProxy();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetBypassProxy(bool aBypassProxy) {
if (StaticPrefs::network_proxy_allow_bypass()) {
StoreBypassProxy(aBypassProxy);
} else {
NS_WARNING("bypassProxy set but network.proxy.allow_bypass is disabled");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsTRRServiceChannel(bool* aIsTRRServiceChannel) {
NS_ENSURE_ARG_POINTER(aIsTRRServiceChannel);
*aIsTRRServiceChannel = LoadIsTRRServiceChannel();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetIsTRRServiceChannel(bool aIsTRRServiceChannel) {
StoreIsTRRServiceChannel(aIsTRRServiceChannel);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsResolvedByTRR(bool* aResolvedByTRR) {
NS_ENSURE_ARG_POINTER(aResolvedByTRR);
*aResolvedByTRR = LoadResolvedByTRR();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetEffectiveTRRMode(nsIRequest::TRRMode* aEffectiveTRRMode) {
*aEffectiveTRRMode = mEffectiveTRRMode;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetTrrSkipReason(nsITRRSkipReason::value* aTrrSkipReason) {
*aTrrSkipReason = mTRRSkipReason;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsLoadedBySocketProcess(bool* aResult) {
NS_ENSURE_ARG_POINTER(aResult);
*aResult = LoadLoadedBySocketProcess();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetTlsFlags(uint32_t* aTlsFlags) {
NS_ENSURE_ARG_POINTER(aTlsFlags);
*aTlsFlags = mTlsFlags;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetTlsFlags(uint32_t aTlsFlags) {
mTlsFlags = aTlsFlags;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetApiRedirectToURI(nsIURI** aResult) {
if (!mAPIRedirectTo) {
return NS_ERROR_NOT_AVAILABLE;
}
NS_ENSURE_ARG_POINTER(aResult);
*aResult = do_AddRef(mAPIRedirectTo->first()).take();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetResponseTimeoutEnabled(bool* aEnable) {
if (NS_WARN_IF(!aEnable)) {
return NS_ERROR_NULL_POINTER;
}
*aEnable = LoadResponseTimeoutEnabled();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetResponseTimeoutEnabled(bool aEnable) {
StoreResponseTimeoutEnabled(aEnable);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetInitialRwin(uint32_t* aRwin) {
if (NS_WARN_IF(!aRwin)) {
return NS_ERROR_NULL_POINTER;
}
*aRwin = mInitialRwin;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetInitialRwin(uint32_t aRwin) {
ENSURE_CALLED_BEFORE_CONNECT();
mInitialRwin = aRwin;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::ForcePending(bool aForcePending) {
StoreForcePending(aForcePending);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLastModifiedTime(PRTime* lastModifiedTime) {
if (!mResponseHead) return NS_ERROR_NOT_AVAILABLE;
uint32_t lastMod;
nsresult rv = mResponseHead->GetLastModifiedValue(&lastMod);
NS_ENSURE_SUCCESS(rv, rv);
*lastModifiedTime = lastMod;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetCorsIncludeCredentials(bool* aInclude) {
*aInclude = LoadCorsIncludeCredentials();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetCorsIncludeCredentials(bool aInclude) {
StoreCorsIncludeCredentials(aInclude);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestMode(RequestMode* aMode) {
*aMode = mRequestMode;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRequestMode(RequestMode aMode) {
mRequestMode = aMode;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRedirectMode(uint32_t* aMode) {
*aMode = mRedirectMode;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRedirectMode(uint32_t aMode) {
mRedirectMode = aMode;
return NS_OK;
}
namespace {
bool ContainsAllFlags(uint32_t aLoadFlags, uint32_t aMask) {
return (aLoadFlags & aMask) == aMask;
}
} // anonymous namespace
NS_IMETHODIMP
HttpBaseChannel::GetFetchCacheMode(uint32_t* aFetchCacheMode) {
NS_ENSURE_ARG_POINTER(aFetchCacheMode);
// Otherwise try to guess an appropriate cache mode from the load flags.
if (ContainsAllFlags(mLoadFlags, INHIBIT_CACHING | LOAD_BYPASS_CACHE)) {
*aFetchCacheMode = nsIHttpChannelInternal::FETCH_CACHE_MODE_NO_STORE;
} else if (ContainsAllFlags(mLoadFlags, LOAD_BYPASS_CACHE)) {
*aFetchCacheMode = nsIHttpChannelInternal::FETCH_CACHE_MODE_RELOAD;
} else if (ContainsAllFlags(mLoadFlags, VALIDATE_ALWAYS) ||
LoadForceValidateCacheContent()) {
*aFetchCacheMode = nsIHttpChannelInternal::FETCH_CACHE_MODE_NO_CACHE;
} else if (ContainsAllFlags(
mLoadFlags,
VALIDATE_NEVER | nsICachingChannel::LOAD_ONLY_FROM_CACHE)) {
*aFetchCacheMode = nsIHttpChannelInternal::FETCH_CACHE_MODE_ONLY_IF_CACHED;
} else if (ContainsAllFlags(mLoadFlags, VALIDATE_NEVER)) {
*aFetchCacheMode = nsIHttpChannelInternal::FETCH_CACHE_MODE_FORCE_CACHE;
} else {
*aFetchCacheMode = nsIHttpChannelInternal::FETCH_CACHE_MODE_DEFAULT;
}
return NS_OK;
}
namespace {
void SetCacheFlags(uint32_t& aLoadFlags, uint32_t aFlags) {
// First, clear any possible cache related flags.
uint32_t allPossibleFlags =
nsIRequest::INHIBIT_CACHING | nsIRequest::LOAD_BYPASS_CACHE |
nsIRequest::VALIDATE_ALWAYS | nsIRequest::LOAD_FROM_CACHE |
nsICachingChannel::LOAD_ONLY_FROM_CACHE;
aLoadFlags &= ~allPossibleFlags;
// Then set the new flags.
aLoadFlags |= aFlags;
}
} // anonymous namespace
NS_IMETHODIMP
HttpBaseChannel::SetFetchCacheMode(uint32_t aFetchCacheMode) {
ENSURE_CALLED_BEFORE_CONNECT();
// Now, set the load flags that implement each cache mode.
switch (aFetchCacheMode) {
case nsIHttpChannelInternal::FETCH_CACHE_MODE_DEFAULT:
// The "default" mode means to use the http cache normally and
// respect any http cache-control headers. We effectively want
// to clear our cache related load flags.
SetCacheFlags(mLoadFlags, 0);
break;
case nsIHttpChannelInternal::FETCH_CACHE_MODE_NO_STORE:
// no-store means don't consult the cache on the way to the network, and
// don't store the response in the cache even if it's cacheable.
SetCacheFlags(mLoadFlags, INHIBIT_CACHING | LOAD_BYPASS_CACHE);
break;
case nsIHttpChannelInternal::FETCH_CACHE_MODE_RELOAD:
// reload means don't consult the cache on the way to the network, but
// do store the response in the cache if possible.
SetCacheFlags(mLoadFlags, LOAD_BYPASS_CACHE);
break;
case nsIHttpChannelInternal::FETCH_CACHE_MODE_NO_CACHE:
// no-cache means always validate what's in the cache.
SetCacheFlags(mLoadFlags, VALIDATE_ALWAYS);
break;
case nsIHttpChannelInternal::FETCH_CACHE_MODE_FORCE_CACHE:
// force-cache means don't validate unless if the response would vary.
SetCacheFlags(mLoadFlags, VALIDATE_NEVER);
break;
case nsIHttpChannelInternal::FETCH_CACHE_MODE_ONLY_IF_CACHED:
// only-if-cached means only from cache, no network, no validation,
// generate a network error if the document was't in the cache. The
// privacy implications of these flags (making it fast/easy to check if
// the user has things in their cache without any network traffic side
// effects) are addressed in the Request constructor which
// enforces/requires same-origin request mode.
SetCacheFlags(mLoadFlags,
VALIDATE_NEVER | nsICachingChannel::LOAD_ONLY_FROM_CACHE);
break;
}
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
uint32_t finalMode = 0;
MOZ_ALWAYS_SUCCEEDS(GetFetchCacheMode(&finalMode));
MOZ_DIAGNOSTIC_ASSERT(finalMode == aFetchCacheMode);
#endif // MOZ_DIAGNOSTIC_ASSERT_ENABLED
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsISupportsPriority
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetPriority(int32_t* value) {
*value = mPriority;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::AdjustPriority(int32_t delta) {
return SetPriority(mPriority + delta);
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIResumableChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetEntityID(nsACString& aEntityID) {
// Don't return an entity ID for Non-GET requests which require
// additional data
if (!mRequestHead.IsGet()) {
return NS_ERROR_NOT_RESUMABLE;
}
uint64_t size = UINT64_MAX;
nsAutoCString etag, lastmod;
if (mResponseHead) {
// Don't return an entity if the server sent the following header:
// Accept-Ranges: none
// Not sending the Accept-Ranges header means we can still try
// sending range requests.
nsAutoCString acceptRanges;
(void)mResponseHead->GetHeader(nsHttp::Accept_Ranges, acceptRanges);
if (!acceptRanges.IsEmpty() &&
!nsHttp::FindToken(acceptRanges.get(), "bytes",
HTTP_HEADER_VALUE_SEPS)) {
return NS_ERROR_NOT_RESUMABLE;
}
size = mResponseHead->TotalEntitySize();
(void)mResponseHead->GetHeader(nsHttp::Last_Modified, lastmod);
(void)mResponseHead->GetHeader(nsHttp::ETag, etag);
}
nsCString entityID;
NS_EscapeURL(etag.BeginReading(), etag.Length(),
esc_AlwaysCopy | esc_FileBaseName | esc_Forced, entityID);
entityID.Append('/');
entityID.AppendInt(int64_t(size));
entityID.Append('/');
entityID.Append(lastmod);
// NOTE: Appending lastmod as the last part avoids having to escape it
aEntityID = entityID;
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIConsoleReportCollector
//-----------------------------------------------------------------------------
void HttpBaseChannel::AddConsoleReport(
uint32_t aErrorFlags, const nsACString& aCategory,
nsContentUtils::PropertiesFile aPropertiesFile,
const nsACString& aSourceFileURI, uint32_t aLineNumber,
uint32_t aColumnNumber, const nsACString& aMessageName,
const nsTArray<nsString>& aStringParams) {
mReportCollector->AddConsoleReport(aErrorFlags, aCategory, aPropertiesFile,
aSourceFileURI, aLineNumber, aColumnNumber,
aMessageName, aStringParams);
// If this channel is already part of a loadGroup, we can flush this console
// report immediately.
HttpBaseChannel::MaybeFlushConsoleReports();
}
void HttpBaseChannel::FlushReportsToConsole(uint64_t aInnerWindowID,
ReportAction aAction) {
mReportCollector->FlushReportsToConsole(aInnerWindowID, aAction);
}
void HttpBaseChannel::FlushReportsToConsoleForServiceWorkerScope(
const nsACString& aScope, ReportAction aAction) {
mReportCollector->FlushReportsToConsoleForServiceWorkerScope(aScope, aAction);
}
void HttpBaseChannel::FlushConsoleReports(dom::Document* aDocument,
ReportAction aAction) {
mReportCollector->FlushConsoleReports(aDocument, aAction);
}
void HttpBaseChannel::FlushConsoleReports(nsILoadGroup* aLoadGroup,
ReportAction aAction) {
mReportCollector->FlushConsoleReports(aLoadGroup, aAction);
}
void HttpBaseChannel::FlushConsoleReports(
nsIConsoleReportCollector* aCollector) {
mReportCollector->FlushConsoleReports(aCollector);
}
void HttpBaseChannel::StealConsoleReports(
nsTArray<net::ConsoleReportCollected>& aReports) {
mReportCollector->StealConsoleReports(aReports);
}
void HttpBaseChannel::ClearConsoleReports() {
mReportCollector->ClearConsoleReports();
}
bool HttpBaseChannel::IsNavigation() {
return LoadForceMainDocumentChannel() || (mLoadFlags & LOAD_DOCUMENT_URI);
}
bool HttpBaseChannel::BypassServiceWorker() const {
return mLoadFlags & LOAD_BYPASS_SERVICE_WORKER;
}
bool HttpBaseChannel::ShouldIntercept(nsIURI* aURI) {
nsCOMPtr<nsINetworkInterceptController> controller;
GetCallback(controller);
bool shouldIntercept = false;
if (!StaticPrefs::dom_serviceWorkers_enabled()) {
return false;
}
// We should never intercept internal redirects. The ServiceWorker code
// can trigger interntal redirects as the result of a FetchEvent. If
// we re-intercept then an infinite loop can occur.
//
// Its also important that we do not set the LOAD_BYPASS_SERVICE_WORKER
// flag because an internal redirect occurs. Its possible that another
// interception should occur after the internal redirect. For example,
// if the ServiceWorker chooses not to call respondWith() the channel
// will be reset with an internal redirect. If the request is a navigation
// and the network then triggers a redirect its possible the new URL
// should be intercepted again.
//
// Note, HSTS upgrade redirects are often treated the same as internal
// redirects. In this case, however, we intentionally allow interception
// of HSTS upgrade redirects. This matches the expected spec behavior and
// does not run the risk of infinite loops as described above.
bool internalRedirect =
mLastRedirectFlags & nsIChannelEventSink::REDIRECT_INTERNAL;
if (controller && mLoadInfo && !BypassServiceWorker() && !internalRedirect) {
nsresult rv = controller->ShouldPrepareForIntercept(
aURI ? aURI : mURI.get(), this, &shouldIntercept);
if (NS_FAILED(rv)) {
return false;
}
}
return shouldIntercept;
}
void HttpBaseChannel::AddAsNonTailRequest() {
MOZ_ASSERT(NS_IsMainThread());
if (EnsureRequestContext()) {
LOG((
"HttpBaseChannel::AddAsNonTailRequest this=%p, rc=%p, already added=%d",
this, mRequestContext.get(), (bool)LoadAddedAsNonTailRequest()));
if (!LoadAddedAsNonTailRequest()) {
mRequestContext->AddNonTailRequest();
StoreAddedAsNonTailRequest(true);
}
}
}
void HttpBaseChannel::RemoveAsNonTailRequest() {
MOZ_ASSERT(NS_IsMainThread());
if (mRequestContext) {
LOG(
("HttpBaseChannel::RemoveAsNonTailRequest this=%p, rc=%p, already "
"added=%d",
this, mRequestContext.get(), (bool)LoadAddedAsNonTailRequest()));
if (LoadAddedAsNonTailRequest()) {
mRequestContext->RemoveNonTailRequest();
StoreAddedAsNonTailRequest(false);
}
}
}
#ifdef DEBUG
void HttpBaseChannel::AssertPrivateBrowsingId() {
nsCOMPtr<nsILoadContext> loadContext;
NS_QueryNotificationCallbacks(this, loadContext);
if (!loadContext) {
return;
}
// We skip testing of favicon loading here since it could be triggered by XUL
// image which uses SystemPrincipal. The SystemPrincpal doesn't have
// mPrivateBrowsingId.
if (mLoadInfo->GetLoadingPrincipal() &&
mLoadInfo->GetLoadingPrincipal()->IsSystemPrincipal() &&
mLoadInfo->InternalContentPolicyType() ==
nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON) {
return;
}
OriginAttributes docShellAttrs;
loadContext->GetOriginAttributes(docShellAttrs);
MOZ_ASSERT(mLoadInfo->GetOriginAttributes().mPrivateBrowsingId ==
docShellAttrs.mPrivateBrowsingId,
"PrivateBrowsingId values are not the same between LoadInfo and "
"LoadContext.");
}
#endif
already_AddRefed<nsILoadInfo> HttpBaseChannel::CloneLoadInfoForRedirect(
nsIURI* aNewURI, uint32_t aRedirectFlags) {
// make a copy of the loadinfo, append to the redirectchain
// this will be set on the newly created channel for the redirect target.
nsCOMPtr<nsILoadInfo> newLoadInfo =
static_cast<mozilla::net::LoadInfo*>(mLoadInfo.get())->Clone();
ExtContentPolicyType contentPolicyType =
mLoadInfo->GetExternalContentPolicyType();
if (contentPolicyType == ExtContentPolicy::TYPE_DOCUMENT ||
contentPolicyType == ExtContentPolicy::TYPE_SUBDOCUMENT) {
// Reset PrincipalToInherit to a null principal. We'll credit the the
// redirecting resource's result principal as the new principal's precursor.
// This means that a data: URI will end up loading in a process based on the
// redirected-from URI.
nsCOMPtr<nsIPrincipal> redirectPrincipal;
nsContentUtils::GetSecurityManager()->GetChannelResultPrincipal(
this, getter_AddRefs(redirectPrincipal));
nsCOMPtr<nsIPrincipal> nullPrincipalToInherit =
NullPrincipal::CreateWithInheritedAttributes(redirectPrincipal);
newLoadInfo->SetPrincipalToInherit(nullPrincipalToInherit);
}
bool isTopLevelDoc = newLoadInfo->GetExternalContentPolicyType() ==
ExtContentPolicy::TYPE_DOCUMENT;
if (isTopLevelDoc) {
// re-compute the origin attributes of the loadInfo if it's top-level load.
nsCOMPtr<nsILoadContext> loadContext;
NS_QueryNotificationCallbacks(this, loadContext);
OriginAttributes docShellAttrs;
if (loadContext) {
loadContext->GetOriginAttributes(docShellAttrs);
}
OriginAttributes attrs = newLoadInfo->GetOriginAttributes();
MOZ_ASSERT(
docShellAttrs.mUserContextId == attrs.mUserContextId,
"docshell and necko should have the same userContextId attribute.");
MOZ_ASSERT(
docShellAttrs.mPrivateBrowsingId == attrs.mPrivateBrowsingId,
"docshell and necko should have the same privateBrowsingId attribute.");
MOZ_ASSERT(docShellAttrs.mGeckoViewSessionContextId ==
attrs.mGeckoViewSessionContextId,
"docshell and necko should have the same "
"geckoViewSessionContextId attribute");
attrs = docShellAttrs;
attrs.SetFirstPartyDomain(true, aNewURI);
newLoadInfo->SetOriginAttributes(attrs);
// re-compute the upgrade insecure requests bit for document navigations
// since it should only apply to same-origin navigations (redirects).
// we only do this if the CSP of the triggering element (the cspToInherit)
// uses 'upgrade-insecure-requests', otherwise UIR does not apply.
nsCOMPtr<nsIPolicyContainer> policyContainer =
newLoadInfo->GetPolicyContainerToInherit();
nsCOMPtr<nsIContentSecurityPolicy> csp =
PolicyContainer::GetCSP(policyContainer);
if (csp) {
bool upgradeInsecureRequests = false;
csp->GetUpgradeInsecureRequests(&upgradeInsecureRequests);
if (upgradeInsecureRequests) {
nsCOMPtr<nsIPrincipal> resultPrincipal =
BasePrincipal::CreateContentPrincipal(
aNewURI, newLoadInfo->GetOriginAttributes());
bool isConsideredSameOriginforUIR =
nsContentSecurityUtils::IsConsideredSameOriginForUIR(
newLoadInfo->TriggeringPrincipal(), resultPrincipal);
static_cast<mozilla::net::LoadInfo*>(newLoadInfo.get())
->SetUpgradeInsecureRequests(isConsideredSameOriginforUIR);
}
}
}
// Clone a new cookieJarSettings from the old one for the new channel.
// Otherwise, updating the new cookieJarSettings will affect the old one.
nsCOMPtr<nsICookieJarSettings> oldCookieJarSettings;
mLoadInfo->GetCookieJarSettings(getter_AddRefs(oldCookieJarSettings));
RefPtr<CookieJarSettings> newCookieJarSettings;
newCookieJarSettings = CookieJarSettings::Cast(oldCookieJarSettings)->Clone();
newLoadInfo->SetCookieJarSettings(newCookieJarSettings);
// Clear the isThirdPartyContextToTopWindow flag for the new channel so that
// it will be computed again when the new channel is opened.
static_cast<net::LoadInfo*>(newLoadInfo.get())
->ClearIsThirdPartyContextToTopWindow();
// Leave empty, we want a 'clean ground' when creating the new channel.
// This will be ensured to be either set by the protocol handler or set
// to the redirect target URI properly after the channel creation.
newLoadInfo->SetResultPrincipalURI(nullptr);
bool isInternalRedirect =
(aRedirectFlags & (nsIChannelEventSink::REDIRECT_INTERNAL |
nsIChannelEventSink::REDIRECT_STS_UPGRADE));
// Reset our sandboxed null principal ID when cloning loadInfo for an
// externally visible redirect.
if (!isInternalRedirect) {
// If we've redirected from http to something that isn't, clear
// the "external" flag, as loads that now go to other apps should be
// allowed to go ahead and not trip infinite-loop protection
// (see bug 1717314 for context).
if (!net::SchemeIsHttpOrHttps(aNewURI)) {
newLoadInfo->SetLoadTriggeredFromExternal(false);
}
newLoadInfo->ResetSandboxedNullPrincipalID();
if (isTopLevelDoc) {
// Reset HTTPS-first and -only status on http redirect. To not
// unexpectedly downgrade requests that weren't upgraded via HTTPS-First
// (Bug 1904238).
(void)newLoadInfo->SetHttpsOnlyStatus(
nsILoadInfo::HTTPS_ONLY_UNINITIALIZED);
// Reset schemeless status flag to prevent schemeless HTTPS-First from
// repeatedly trying to upgrade loads that get downgraded again from the
// server by a redirect (Bug 1937386).
(void)newLoadInfo->SetSchemelessInput(
nsILoadInfo::SchemelessInputTypeUnset);
}
}
newLoadInfo->AppendRedirectHistoryEntry(this, isInternalRedirect);
return newLoadInfo.forget();
}
//-----------------------------------------------------------------------------
// nsHttpChannel::nsITraceableChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::SetNewListener(nsIStreamListener* aListener,
bool aMustApplyContentConversion,
nsIStreamListener** _retval) {
LOG((
"HttpBaseChannel::SetNewListener [this=%p, mListener=%p, newListener=%p]",
this, mListener.get(), aListener));
if (!LoadTracingEnabled()) return NS_ERROR_FAILURE;
NS_ENSURE_STATE(mListener);
NS_ENSURE_ARG_POINTER(aListener);
nsCOMPtr<nsIStreamListener> wrapper = new nsStreamListenerWrapper(mListener);
wrapper.forget(_retval);
mListener = aListener;
if (aMustApplyContentConversion) {
StoreListenerRequiresContentConversion(true);
}
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel helpers
//-----------------------------------------------------------------------------
void HttpBaseChannel::ReleaseListeners() {
MOZ_ASSERT(mCurrentThread->IsOnCurrentThread(),
"Should only be called on the current thread");
mListener = nullptr;
mCallbacks = nullptr;
mProgressSink = nullptr;
mCompressListener = nullptr;
mORB = nullptr;
}
void HttpBaseChannel::DoNotifyListener() {
LOG(("HttpBaseChannel::DoNotifyListener this=%p", this));
// In case nsHttpChannel::OnStartRequest wasn't called (e.g. due to flag
// LOAD_ONLY_IF_MODIFIED) we want to set AfterOnStartRequestBegun to true
// before notifying listener.
if (!LoadAfterOnStartRequestBegun()) {
StoreAfterOnStartRequestBegun(true);
}
if (mListener && !LoadOnStartRequestCalled()) {
nsCOMPtr<nsIStreamListener> listener = mListener;
StoreOnStartRequestCalled(true);
listener->OnStartRequest(this);
}
StoreOnStartRequestCalled(true);
// Make sure IsPending is set to false. At this moment we are done from
// the point of view of our consumer and we have to report our self
// as not-pending.
StoreIsPending(false);
// notify "http-on-before-stop-request" observers
gHttpHandler->OnBeforeStopRequest(this);
if (mListener && !LoadOnStopRequestCalled()) {
nsCOMPtr<nsIStreamListener> listener = mListener;
StoreOnStopRequestCalled(true);
listener->OnStopRequest(this, mStatus);
}
StoreOnStopRequestCalled(true);
// notify "http-on-stop-request" observers
gHttpHandler->OnStopRequest(this);
// This channel has finished its job, potentially release any tail-blocked
// requests with this.
RemoveAsNonTailRequest();
// We have to make sure to drop the references to listeners and callbacks
// no longer needed.
ReleaseListeners();
DoNotifyListenerCleanup();
// If this is a navigation, then we must let the docshell flush the reports
// to the console later. The LoadDocument() is pointing at the detached
// document that started the navigation. We want to show the reports on the
// new document. Otherwise the console is wiped and the user never sees
// the information.
if (!IsNavigation()) {
if (mLoadGroup) {
FlushConsoleReports(mLoadGroup);
} else {
RefPtr<dom::Document> doc;
mLoadInfo->GetLoadingDocument(getter_AddRefs(doc));
FlushConsoleReports(doc);
}
}
}
void HttpBaseChannel::AddCookiesToRequest() {
if (mLoadFlags & LOAD_ANONYMOUS) {
return;
}
bool useCookieService = (XRE_IsParentProcess());
nsAutoCString cookie;
if (useCookieService) {
nsICookieService* cs = gHttpHandler->GetCookieService();
if (cs) {
cs->GetCookieStringFromHttp(mURI, this, cookie);
}
if (cookie.IsEmpty()) {
cookie = mUserSetCookieHeader;
} else if (!mUserSetCookieHeader.IsEmpty()) {
cookie.AppendLiteral("; ");
cookie.Append(mUserSetCookieHeader);
}
} else {
cookie = mUserSetCookieHeader;
}
// If we are in the child process, we want the parent seeing any
// cookie headers that might have been set by SetRequestHeader()
SetRequestHeader(nsHttp::Cookie.val(), cookie, false);
}
/* static */
void HttpBaseChannel::PropagateReferenceIfNeeded(
nsIURI* aURI, nsCOMPtr<nsIURI>& aRedirectURI) {
bool hasRef = false;
nsresult rv = aRedirectURI->GetHasRef(&hasRef);
if (NS_SUCCEEDED(rv) && !hasRef) {
nsAutoCString ref;
aURI->GetRef(ref);
if (!ref.IsEmpty()) {
// NOTE: SetRef will fail if mRedirectURI is immutable
// (e.g. an about: URI)... Oh well.
(void)NS_MutateURI(aRedirectURI).SetRef(ref).Finalize(aRedirectURI);
}
}
}
bool HttpBaseChannel::ShouldRewriteRedirectToGET(
uint32_t httpStatus, nsHttpRequestHead::ParsedMethodType method) {
// for 301 and 302, only rewrite POST
if (httpStatus == 301 || httpStatus == 302) {
return method == nsHttpRequestHead::kMethod_Post;
}
// rewrite for 303 unless it was HEAD
if (httpStatus == 303) return method != nsHttpRequestHead::kMethod_Head;
// otherwise, such as for 307, do not rewrite
return false;
}
NS_IMETHODIMP
HttpBaseChannel::ShouldStripRequestBodyHeader(const nsACString& aMethod,
bool* aResult) {
*aResult = false;
uint32_t httpStatus = 0;
if (NS_FAILED(GetResponseStatus(&httpStatus))) {
return NS_OK;
}
nsAutoCString method(aMethod);
nsHttpRequestHead::ParsedMethodType parsedMethod;
nsHttpRequestHead::ParseMethod(method, parsedMethod);
// Fetch 4.4.11, which is slightly different than the perserved method
// algrorithm: strip request-body-header for GET->GET redirection for 303.
*aResult =
ShouldRewriteRedirectToGET(httpStatus, parsedMethod) &&
!(httpStatus == 303 && parsedMethod == nsHttpRequestHead::kMethod_Get);
return NS_OK;
}
HttpBaseChannel::ReplacementChannelConfig
HttpBaseChannel::CloneReplacementChannelConfig(bool aPreserveMethod,
uint32_t aRedirectFlags,
ReplacementReason aReason) {
ReplacementChannelConfig config;
config.redirectFlags = aRedirectFlags;
config.classOfService = mClassOfService;
if (mPrivateBrowsingOverriden) {
config.privateBrowsing = Some(mPrivateBrowsing);
}
if (mReferrerInfo) {
// When cloning for a document channel replacement (parent process
// copying values for a new content process channel), this happens after
// OnStartRequest so we have the headers for the response available.
// We don't want to apply them to the referrer for the channel though,
// since that is the referrer for the current document, and the header
// should only apply to navigations from the current document.
if (aReason == ReplacementReason::DocumentChannel) {
config.referrerInfo = mReferrerInfo;
} else {
dom::ReferrerPolicy referrerPolicy = dom::ReferrerPolicy::_empty;
nsAutoCString tRPHeaderCValue;
(void)GetResponseHeader("referrer-policy"_ns, tRPHeaderCValue);
NS_ConvertUTF8toUTF16 tRPHeaderValue(tRPHeaderCValue);
if (!tRPHeaderValue.IsEmpty()) {
referrerPolicy =
dom::ReferrerInfo::ReferrerPolicyFromHeaderString(tRPHeaderValue);
}
// In case we are here because an upgrade happened through mixed content
// upgrading, CSP upgrade-insecure-requests, HTTPS-Only or HTTPS-First, we
// have to recalculate the referrer based on the original referrer to
// account for the different scheme. This does NOT apply to HSTS.
// See Bug 1857894 and order of https://fetch.spec.whatwg.org/#main-fetch.
// Otherwise, if we have a new referrer policy, we want to recalculate the
// referrer based on the old computed referrer (Bug 1678545).
bool wasNonHSTSUpgrade =
(aRedirectFlags & nsIChannelEventSink::REDIRECT_STS_UPGRADE) &&
(!mLoadInfo->GetHstsStatus());
if (wasNonHSTSUpgrade) {
nsCOMPtr<nsIURI> referrer = mReferrerInfo->GetOriginalReferrer();
config.referrerInfo =
new dom::ReferrerInfo(referrer, mReferrerInfo->ReferrerPolicy(),
mReferrerInfo->GetSendReferrer());
} else if (referrerPolicy != dom::ReferrerPolicy::_empty) {
nsCOMPtr<nsIURI> referrer = mReferrerInfo->GetComputedReferrer();
config.referrerInfo = new dom::ReferrerInfo(
referrer, referrerPolicy, mReferrerInfo->GetSendReferrer());
} else {
config.referrerInfo = mReferrerInfo;
}
}
}
nsCOMPtr<nsITimedChannel> oldTimedChannel(
do_QueryInterface(static_cast<nsIHttpChannel*>(this)));
if (oldTimedChannel) {
config.timedChannelInfo = Some(dom::TimedChannelInfo());
config.timedChannelInfo->redirectCount() = mRedirectCount;
config.timedChannelInfo->internalRedirectCount() = mInternalRedirectCount;
config.timedChannelInfo->asyncOpen() = mAsyncOpenTime;
config.timedChannelInfo->channelCreation() = mChannelCreationTimestamp;
config.timedChannelInfo->redirectStart() = mRedirectStartTimeStamp;
config.timedChannelInfo->redirectEnd() = mRedirectEndTimeStamp;
config.timedChannelInfo->initiatorType() = mInitiatorType;
config.timedChannelInfo->allRedirectsSameOrigin() =
LoadAllRedirectsSameOrigin();
config.timedChannelInfo->allRedirectsPassTimingAllowCheck() =
LoadAllRedirectsPassTimingAllowCheck();
// Execute the timing allow check to determine whether
// to report the redirect timing info
nsCOMPtr<nsILoadInfo> loadInfo = LoadInfo();
// TYPE_DOCUMENT loads don't have a loadingPrincipal, so we can't set
// AllRedirectsPassTimingAllowCheck on them.
if (loadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_DOCUMENT) {
nsCOMPtr<nsIPrincipal> principal = loadInfo->GetLoadingPrincipal();
config.timedChannelInfo->timingAllowCheckForPrincipal() =
Some(oldTimedChannel->TimingAllowCheck(principal));
}
config.timedChannelInfo->allRedirectsPassTimingAllowCheck() =
LoadAllRedirectsPassTimingAllowCheck();
config.timedChannelInfo->launchServiceWorkerStart() =
mLaunchServiceWorkerStart;
config.timedChannelInfo->launchServiceWorkerEnd() = mLaunchServiceWorkerEnd;
config.timedChannelInfo->dispatchFetchEventStart() =
mDispatchFetchEventStart;
config.timedChannelInfo->dispatchFetchEventEnd() = mDispatchFetchEventEnd;
config.timedChannelInfo->handleFetchEventStart() = mHandleFetchEventStart;
config.timedChannelInfo->handleFetchEventEnd() = mHandleFetchEventEnd;
config.timedChannelInfo->responseStart() =
mTransactionTimings.responseStart;
config.timedChannelInfo->responseEnd() = mTransactionTimings.responseEnd;
}
if (aPreserveMethod) {
// since preserveMethod is true, we need to ensure that the appropriate
// request method gets set on the channel, regardless of whether or not
// we set the upload stream above. This means SetRequestMethod() will
// be called twice if ExplicitSetUploadStream() gets called above.
nsAutoCString method;
mRequestHead.Method(method);
config.method = Some(method);
if (mUploadStream) {
// rewind upload stream
nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(mUploadStream);
if (seekable) {
seekable->Seek(nsISeekableStream::NS_SEEK_SET, 0);
}
config.uploadStream = mUploadStream;
}
config.uploadStreamLength = mReqContentLength;
config.uploadStreamHasHeaders = LoadUploadStreamHasHeaders();
nsAutoCString contentType;
nsresult rv = mRequestHead.GetHeader(nsHttp::Content_Type, contentType);
if (NS_SUCCEEDED(rv)) {
config.contentType = Some(contentType);
}
nsAutoCString contentLength;
rv = mRequestHead.GetHeader(nsHttp::Content_Length, contentLength);
if (NS_SUCCEEDED(rv)) {
config.contentLength = Some(contentLength);
}
}
return config;
}
/* static */ void HttpBaseChannel::ConfigureReplacementChannel(
nsIChannel* newChannel, const ReplacementChannelConfig& config,
ReplacementReason aReason) {
nsCOMPtr<nsIClassOfService> cos(do_QueryInterface(newChannel));
if (cos) {
cos->SetClassOfService(config.classOfService);
}
// Try to preserve the privacy bit if it has been overridden
if (config.privateBrowsing) {
nsCOMPtr<nsIPrivateBrowsingChannel> newPBChannel =
do_QueryInterface(newChannel);
if (newPBChannel) {
newPBChannel->SetPrivate(*config.privateBrowsing);
}
}
// Transfer the timing data (if we are dealing with an nsITimedChannel).
nsCOMPtr<nsITimedChannel> newTimedChannel(do_QueryInterface(newChannel));
if (config.timedChannelInfo && newTimedChannel) {
// If we're an internal redirect, or a document channel replacement,
// then we shouldn't record any new timing for this and just copy
// over the existing values.
bool shouldHideTiming = aReason != ReplacementReason::Redirect;
if (shouldHideTiming) {
newTimedChannel->SetRedirectCount(
config.timedChannelInfo->redirectCount());
int32_t newCount = config.timedChannelInfo->internalRedirectCount() + 1;
newTimedChannel->SetInternalRedirectCount(std::max(
newCount, static_cast<int32_t>(
config.timedChannelInfo->internalRedirectCount())));
} else {
int32_t newCount = config.timedChannelInfo->redirectCount() + 1;
newTimedChannel->SetRedirectCount(std::max(
newCount,
static_cast<int32_t>(config.timedChannelInfo->redirectCount())));
newTimedChannel->SetInternalRedirectCount(
config.timedChannelInfo->internalRedirectCount());
}
if (shouldHideTiming) {
if (!config.timedChannelInfo->channelCreation().IsNull()) {
newTimedChannel->SetChannelCreation(
config.timedChannelInfo->channelCreation());
}
if (!config.timedChannelInfo->asyncOpen().IsNull()) {
newTimedChannel->SetAsyncOpen(config.timedChannelInfo->asyncOpen());
}
}
// If the RedirectStart is null, we will use the AsyncOpen value of the
// previous channel (this is the first redirect in the redirects chain).
if (config.timedChannelInfo->redirectStart().IsNull()) {
// Only do this for real redirects. Internal redirects should be hidden.
if (!shouldHideTiming) {
newTimedChannel->SetRedirectStart(config.timedChannelInfo->asyncOpen());
}
} else {
newTimedChannel->SetRedirectStart(
config.timedChannelInfo->redirectStart());
}
// For internal redirects just propagate the last redirect end time
// forward. Otherwise the new redirect end time is the last response
// end time.
TimeStamp newRedirectEnd;
if (shouldHideTiming) {
newRedirectEnd = config.timedChannelInfo->redirectEnd();
} else if (!config.timedChannelInfo->responseEnd().IsNull()) {
newRedirectEnd = config.timedChannelInfo->responseEnd();
} else {
newRedirectEnd = TimeStamp::Now();
}
newTimedChannel->SetRedirectEnd(newRedirectEnd);
newTimedChannel->SetInitiatorType(config.timedChannelInfo->initiatorType());
nsCOMPtr<nsILoadInfo> loadInfo = newChannel->LoadInfo();
MOZ_ASSERT(loadInfo);
newTimedChannel->SetAllRedirectsSameOrigin(
config.timedChannelInfo->allRedirectsSameOrigin());
if (config.timedChannelInfo->timingAllowCheckForPrincipal()) {
newTimedChannel->SetAllRedirectsPassTimingAllowCheck(
config.timedChannelInfo->allRedirectsPassTimingAllowCheck() &&
*config.timedChannelInfo->timingAllowCheckForPrincipal());
}
// Propagate service worker measurements across redirects. The
// PeformanceResourceTiming.workerStart API expects to see the
// worker start time after a redirect.
newTimedChannel->SetLaunchServiceWorkerStart(
config.timedChannelInfo->launchServiceWorkerStart());
newTimedChannel->SetLaunchServiceWorkerEnd(
config.timedChannelInfo->launchServiceWorkerEnd());
newTimedChannel->SetDispatchFetchEventStart(
config.timedChannelInfo->dispatchFetchEventStart());
newTimedChannel->SetDispatchFetchEventEnd(
config.timedChannelInfo->dispatchFetchEventEnd());
newTimedChannel->SetHandleFetchEventStart(
config.timedChannelInfo->handleFetchEventStart());
newTimedChannel->SetHandleFetchEventEnd(
config.timedChannelInfo->handleFetchEventEnd());
}
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(newChannel);
if (!httpChannel) {
return; // no other options to set
}
if (config.uploadStream) {
nsCOMPtr<nsIUploadChannel2> uploadChannel2 = do_QueryInterface(httpChannel);
// replicate original call to SetUploadStream...
if (uploadChannel2) {
const nsACString& ctype =
config.contentType ? *config.contentType : VoidCString();
// If header is not present mRequestHead.HasHeaderValue will truncated
// it. But we want to end up with a void string, not an empty string,
// because ExplicitSetUploadStream treats the former as "no header" and
// the latter as "header with empty string value".
const nsACString& method = config.method ? *config.method : VoidCString();
uploadChannel2->ExplicitSetUploadStream(config.uploadStream, ctype,
config.uploadStreamLength, method,
config.uploadStreamHasHeaders);
} else if (nsCOMPtr<nsIUploadChannel> uploadChannel =
do_QueryInterface(httpChannel)) {
MOZ_ASSERT(false,
"Should not QI to nsIUploadChannel but not nsIUploadChannel2");
}
}
if (config.referrerInfo) {
DebugOnly<nsresult> success{};
success = httpChannel->SetReferrerInfo(config.referrerInfo);
MOZ_ASSERT(NS_SUCCEEDED(success));
}
if (config.method) {
DebugOnly<nsresult> rv = httpChannel->SetRequestMethod(*config.method);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
HttpBaseChannel::ReplacementChannelConfig::ReplacementChannelConfig(
const dom::ReplacementChannelConfigInit& aInit) {
redirectFlags = aInit.redirectFlags();
classOfService = aInit.classOfService();
privateBrowsing = aInit.privateBrowsing();
method = aInit.method();
referrerInfo = aInit.referrerInfo();
timedChannelInfo = aInit.timedChannelInfo();
uploadStream = aInit.uploadStream();
uploadStreamLength = aInit.uploadStreamLength();
uploadStreamHasHeaders = aInit.uploadStreamHasHeaders();
contentType = aInit.contentType();
contentLength = aInit.contentLength();
}
dom::ReplacementChannelConfigInit
HttpBaseChannel::ReplacementChannelConfig::Serialize() {
dom::ReplacementChannelConfigInit config;
config.redirectFlags() = redirectFlags;
config.classOfService() = classOfService;
config.privateBrowsing() = privateBrowsing;
config.method() = method;
config.referrerInfo() = referrerInfo;
config.timedChannelInfo() = timedChannelInfo;
config.uploadStream() =
uploadStream ? RemoteLazyInputStream::WrapStream(uploadStream) : nullptr;
config.uploadStreamLength() = uploadStreamLength;
config.uploadStreamHasHeaders() = uploadStreamHasHeaders;
config.contentType() = contentType;
config.contentLength() = contentLength;
return config;
}
nsresult HttpBaseChannel::SetupReplacementChannel(nsIURI* newURI,
nsIChannel* newChannel,
bool preserveMethod,
uint32_t redirectFlags) {
nsresult rv;
LOG(
("HttpBaseChannel::SetupReplacementChannel "
"[this=%p newChannel=%p preserveMethod=%d]",
this, newChannel, preserveMethod));
// Ensure the channel's loadInfo's result principal URI so that it's
// either non-null or updated to the redirect target URI.
// We must do this because in case the loadInfo's result principal URI
// is null, it would be taken from OriginalURI of the channel. But we
// overwrite it with the whole redirect chain first URI before opening
// the target channel, hence the information would be lost.
// If the protocol handler that created the channel wants to use
// the originalURI of the channel as the principal URI, this fulfills
// that request - newURI is the original URI of the channel.
nsCOMPtr<nsILoadInfo> newLoadInfo = newChannel->LoadInfo();
nsCOMPtr<nsIURI> resultPrincipalURI;
rv = newLoadInfo->GetResultPrincipalURI(getter_AddRefs(resultPrincipalURI));
NS_ENSURE_SUCCESS(rv, rv);
if (!resultPrincipalURI) {
rv = newLoadInfo->SetResultPrincipalURI(newURI);
NS_ENSURE_SUCCESS(rv, rv);
}
nsLoadFlags loadFlags = mLoadFlags;
loadFlags |= LOAD_REPLACE;
// if the original channel was using SSL and this channel is not using
// SSL, then no need to inhibit persistent caching. however, if the
// original channel was not using SSL and has INHIBIT_PERSISTENT_CACHING
// set, then allow the flag to apply to the redirected channel as well.
// since we force set INHIBIT_PERSISTENT_CACHING on all HTTPS channels,
// we only need to check if the original channel was using SSL.
if (mURI->SchemeIs("https")) {
loadFlags &= ~INHIBIT_PERSISTENT_CACHING;
}
newChannel->SetLoadFlags(loadFlags);
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(newChannel);
ReplacementReason redirectType =
redirectFlags & (nsIChannelEventSink::REDIRECT_INTERNAL |
nsIChannelEventSink::REDIRECT_TRANSPARENT)
? ReplacementReason::InternalRedirect
: ReplacementReason::Redirect;
ReplacementChannelConfig config = CloneReplacementChannelConfig(
preserveMethod, redirectFlags, redirectType);
ConfigureReplacementChannel(newChannel, config, redirectType);
// Check whether or not this was a cross-domain redirect.
nsCOMPtr<nsITimedChannel> newTimedChannel(do_QueryInterface(newChannel));
bool sameOriginWithOriginalUri = SameOriginWithOriginalUri(newURI);
if (config.timedChannelInfo && newTimedChannel) {
newTimedChannel->SetAllRedirectsSameOrigin(
config.timedChannelInfo->allRedirectsSameOrigin() &&
sameOriginWithOriginalUri);
}
newChannel->SetLoadGroup(mLoadGroup);
newChannel->SetNotificationCallbacks(mCallbacks);
// TODO: create tests for cross-origin redirect in bug 1662896.
if (sameOriginWithOriginalUri) {
newChannel->SetContentDisposition(mContentDispositionHint);
if (mContentDispositionFilename) {
newChannel->SetContentDispositionFilename(*mContentDispositionFilename);
}
}
if (!httpChannel) return NS_OK; // no other options to set
// Preserve the CORS preflight information.
nsCOMPtr<nsIHttpChannelInternal> httpInternal = do_QueryInterface(newChannel);
if (httpInternal) {
httpInternal->SetLastRedirectFlags(redirectFlags);
if (LoadRequireCORSPreflight()) {
httpInternal->SetCorsPreflightParameters(mUnsafeHeaders, false, false);
}
}
// convey the LoadAllowSTS() flags
rv = httpChannel->SetAllowSTS(LoadAllowSTS());
MOZ_ASSERT(NS_SUCCEEDED(rv));
// convey the Accept header value
{
nsAutoCString oldAcceptValue;
nsresult hasHeader = mRequestHead.GetHeader(nsHttp::Accept, oldAcceptValue);
if (NS_SUCCEEDED(hasHeader)) {
rv = httpChannel->SetRequestHeader("Accept"_ns, oldAcceptValue, false);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
// convey the User-Agent header value
// since we might be setting custom user agent from DevTools.
if (httpInternal && mRequestMode == RequestMode::No_cors &&
redirectType == ReplacementReason::Redirect) {
nsAutoCString oldUserAgent;
nsresult hasHeader =
mRequestHead.GetHeader(nsHttp::User_Agent, oldUserAgent);
if (NS_SUCCEEDED(hasHeader)) {
rv = httpChannel->SetRequestHeader("User-Agent"_ns, oldUserAgent, false);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
// convery the IsUserAgentHeaderModified value.
if (httpInternal) {
rv = httpInternal->SetIsUserAgentHeaderModified(
LoadIsUserAgentHeaderModified());
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
// share the request context - see bug 1236650
rv = httpChannel->SetRequestContextID(mRequestContextID);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// When on the parent process, the channel can't attempt to get it itself.
// When on the child process, it would be waste to query it again.
rv = httpChannel->SetBrowserId(mBrowserId);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Not setting this flag would break carrying permissions down to the child
// process when the channel is artificially forced to be a main document load.
rv = httpChannel->SetIsMainDocumentChannel(LoadForceMainDocumentChannel());
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Preserve the loading order
nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(newChannel);
if (p) {
p->SetPriority(mPriority);
}
if (httpInternal) {
// Convey third party cookie, conservative, and spdy flags.
rv = httpInternal->SetThirdPartyFlags(LoadThirdPartyFlags());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = httpInternal->SetAllowSpdy(LoadAllowSpdy());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = httpInternal->SetAllowHttp3(LoadAllowHttp3());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = httpInternal->SetAllowAltSvc(LoadAllowAltSvc());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = httpInternal->SetBeConservative(LoadBeConservative());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = httpInternal->SetIsTRRServiceChannel(LoadIsTRRServiceChannel());
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = httpInternal->SetTlsFlags(mTlsFlags);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Ensure the type of realChannel involves all types it may redirect to.
// Such as nsHttpChannel and InterceptedChannel.
// Even thought InterceptedChannel itself doesn't require these information,
// it may still be necessary for the following redirections.
// E.g. nsHttpChannel -> InterceptedChannel -> nsHttpChannel
RefPtr<HttpBaseChannel> realChannel;
CallQueryInterface(newChannel, realChannel.StartAssignment());
if (realChannel) {
realChannel->SetTopWindowURI(mTopWindowURI);
realChannel->StoreTaintedOriginFlag(
ShouldTaintReplacementChannelOrigin(newChannel, redirectFlags));
}
// update the DocumentURI indicator since we are being redirected.
// if this was a top-level document channel, then the new channel
// should have its mDocumentURI point to newURI; otherwise, we
// just need to pass along our mDocumentURI to the new channel.
if (newURI && (mURI == mDocumentURI)) {
rv = httpInternal->SetDocumentURI(newURI);
} else {
rv = httpInternal->SetDocumentURI(mDocumentURI);
}
MOZ_ASSERT(NS_SUCCEEDED(rv));
// if there is a chain of keys for redirect-responses we transfer it to
// the new channel (see bug #561276)
{
auto redirectedCachekeys = mRedirectedCachekeys.Lock();
auto& ref = redirectedCachekeys.ref();
if (ref) {
LOG(
("HttpBaseChannel::SetupReplacementChannel "
"[this=%p] transferring chain of redirect cache-keys",
this));
rv = httpInternal->SetCacheKeysRedirectChain(ref.release());
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
// Preserve Request mode.
rv = httpInternal->SetRequestMode(mRequestMode);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Preserve Redirect mode flag.
rv = httpInternal->SetRedirectMode(mRedirectMode);
MOZ_ASSERT(NS_SUCCEEDED(rv));
httpInternal->SetAltDataForChild(LoadAltDataForChild());
if (LoadDisableAltDataCache()) {
httpInternal->DisableAltDataCache();
}
}
// transfer any properties
nsCOMPtr<nsIWritablePropertyBag> bag(do_QueryInterface(newChannel));
if (bag) {
for (const auto& entry : mPropertyHash) {
bag->SetProperty(entry.GetKey(), entry.GetWeak());
}
}
// Pass the preferred alt-data type on to the new channel.
nsCOMPtr<nsICacheInfoChannel> cacheInfoChan(do_QueryInterface(newChannel));
if (cacheInfoChan) {
for (auto& data : mPreferredCachedAltDataTypes) {
cacheInfoChan->PreferAlternativeDataType(data.type(), data.contentType(),
data.deliverAltData());
}
if (LoadForceValidateCacheContent()) {
(void)cacheInfoChan->SetForceValidateCacheContent(true);
}
}
if (redirectFlags & (nsIChannelEventSink::REDIRECT_INTERNAL |
nsIChannelEventSink::REDIRECT_STS_UPGRADE)) {
// Copy non-origin related headers to the new channel.
nsCOMPtr<nsIHttpHeaderVisitor> visitor =
new AddHeadersToChannelVisitor(httpChannel);
rv = mRequestHead.VisitHeaders(visitor);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
// we need to strip Authentication headers for cross-origin requests
// Ref: https://fetch.spec.whatwg.org/#http-redirect-fetch
nsAutoCString authHeader;
if (NS_SUCCEEDED(
httpChannel->GetRequestHeader("Authorization"_ns, authHeader)) &&
NS_ShouldRemoveAuthHeaderOnRedirect(static_cast<nsIChannel*>(this),
newChannel, redirectFlags)) {
rv = httpChannel->SetRequestHeader("Authorization"_ns, ""_ns, false);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
return NS_OK;
}
// check whether the new channel is of same origin as the current channel
bool HttpBaseChannel::IsNewChannelSameOrigin(nsIChannel* aNewChannel) {
bool isSameOrigin = false;
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
if (!ssm) {
return false;
}
nsCOMPtr<nsIURI> newURI;
NS_GetFinalChannelURI(aNewChannel, getter_AddRefs(newURI));
nsresult rv = ssm->CheckSameOriginURI(newURI, mURI, false, false);
if (NS_SUCCEEDED(rv)) {
isSameOrigin = true;
}
return isSameOrigin;
}
bool HttpBaseChannel::ShouldTaintReplacementChannelOrigin(
nsIChannel* aNewChannel, uint32_t aRedirectFlags) {
if (LoadTaintedOriginFlag()) {
return true;
}
if (NS_IsInternalSameURIRedirect(this, aNewChannel, aRedirectFlags) ||
NS_IsHSTSUpgradeRedirect(this, aNewChannel, aRedirectFlags)) {
return false;
}
// If new channel is not of same origin we need to taint unless
// mURI <-> mOriginalURI/LoadingPrincipal are same origin.
if (IsNewChannelSameOrigin(aNewChannel)) {
return false;
}
nsresult rv;
if (mLoadInfo->GetLoadingPrincipal()) {
bool sameOrigin = false;
rv = mLoadInfo->GetLoadingPrincipal()->IsSameOrigin(mURI, &sameOrigin);
if (NS_FAILED(rv)) {
return true;
}
return !sameOrigin;
}
if (!mOriginalURI) {
return true;
}
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
if (!ssm) {
return true;
}
rv = ssm->CheckSameOriginURI(mOriginalURI, mURI, false, false);
return NS_FAILED(rv);
}
// Redirect Tracking
bool HttpBaseChannel::SameOriginWithOriginalUri(nsIURI* aURI) {
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
bool isPrivateWin = mLoadInfo->GetOriginAttributes().IsPrivateBrowsing();
nsresult rv =
ssm->CheckSameOriginURI(aURI, mOriginalURI, false, isPrivateWin);
return (NS_SUCCEEDED(rv));
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIClassifiedChannel
NS_IMETHODIMP
HttpBaseChannel::GetMatchedList(nsACString& aList) {
aList = mMatchedList;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetMatchedProvider(nsACString& aProvider) {
aProvider = mMatchedProvider;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetMatchedFullHash(nsACString& aFullHash) {
aFullHash = mMatchedFullHash;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetMatchedInfo(const nsACString& aList,
const nsACString& aProvider,
const nsACString& aFullHash) {
NS_ENSURE_ARG(!aList.IsEmpty());
mMatchedList = aList;
mMatchedProvider = aProvider;
mMatchedFullHash = aFullHash;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetMatchedTrackingLists(nsTArray<nsCString>& aLists) {
aLists = mMatchedTrackingLists.Clone();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetMatchedTrackingFullHashes(
nsTArray<nsCString>& aFullHashes) {
aFullHashes = mMatchedTrackingFullHashes.Clone();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetMatchedTrackingInfo(
const nsTArray<nsCString>& aLists, const nsTArray<nsCString>& aFullHashes) {
NS_ENSURE_ARG(!aLists.IsEmpty());
// aFullHashes can be empty for non hash-matching algorithm, for example,
// host based test entries in preference.
mMatchedTrackingLists = aLists.Clone();
mMatchedTrackingFullHashes = aFullHashes.Clone();
return NS_OK;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsITimedChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::GetChannelCreation(TimeStamp* _retval) {
*_retval = mChannelCreationTimestamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetChannelCreation(TimeStamp aValue) {
MOZ_DIAGNOSTIC_ASSERT(!aValue.IsNull());
TimeDuration adjust = aValue - mChannelCreationTimestamp;
mChannelCreationTimestamp = aValue;
mChannelCreationTime += (PRTime)adjust.ToMicroseconds();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetAsyncOpen(TimeStamp* _retval) {
*_retval = mAsyncOpenTime;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetAsyncOpen(TimeStamp aValue) {
MOZ_DIAGNOSTIC_ASSERT(!aValue.IsNull());
mAsyncOpenTime = aValue;
StoreAsyncOpenTimeOverriden(true);
return NS_OK;
}
/**
* @return the number of redirects. There is no check for cross-domain
* redirects. This check must be done by the consumers.
*/
NS_IMETHODIMP
HttpBaseChannel::GetRedirectCount(uint8_t* aRedirectCount) {
*aRedirectCount = mRedirectCount;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRedirectCount(uint8_t aRedirectCount) {
mRedirectCount = aRedirectCount;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetInternalRedirectCount(uint8_t* aRedirectCount) {
*aRedirectCount = mInternalRedirectCount;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetInternalRedirectCount(uint8_t aRedirectCount) {
mInternalRedirectCount = aRedirectCount;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRedirectStart(TimeStamp* _retval) {
*_retval = mRedirectStartTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRedirectStart(TimeStamp aRedirectStart) {
mRedirectStartTimeStamp = aRedirectStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRedirectEnd(TimeStamp* _retval) {
*_retval = mRedirectEndTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRedirectEnd(TimeStamp aRedirectEnd) {
mRedirectEndTimeStamp = aRedirectEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetAllRedirectsSameOrigin(bool* aAllRedirectsSameOrigin) {
*aAllRedirectsSameOrigin = LoadAllRedirectsSameOrigin();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetAllRedirectsSameOrigin(bool aAllRedirectsSameOrigin) {
StoreAllRedirectsSameOrigin(aAllRedirectsSameOrigin);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetAllRedirectsPassTimingAllowCheck(bool* aPassesCheck) {
*aPassesCheck = LoadAllRedirectsPassTimingAllowCheck();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetAllRedirectsPassTimingAllowCheck(bool aPassesCheck) {
StoreAllRedirectsPassTimingAllowCheck(aPassesCheck);
return NS_OK;
}
// https://fetch.spec.whatwg.org/#cors-check
bool HttpBaseChannel::PerformCORSCheck() {
// Step 1
// Let origin be the result of getting `Access-Control-Allow-Origin`
// from response’s header list.
nsAutoCString origin;
nsresult rv = GetResponseHeader("Access-Control-Allow-Origin"_ns, origin);
// Step 2
// If origin is null, then return failure. (Note: null, not 'null').
if (NS_FAILED(rv) || origin.IsVoid()) {
return false;
}
// Step 3
// If request’s credentials mode is not "include"
// and origin is `*`, then return success.
uint32_t cookiePolicy = mLoadInfo->GetCookiePolicy();
if (cookiePolicy != nsILoadInfo::SEC_COOKIES_INCLUDE &&
origin.EqualsLiteral("*")) {
return true;
}
// Step 4
// If the result of byte-serializing a request origin
// with request is not origin, then return failure.
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
nsCOMPtr<nsIPrincipal> resourcePrincipal;
rv = ssm->GetChannelURIPrincipal(this, getter_AddRefs(resourcePrincipal));
if (NS_FAILED(rv) || !resourcePrincipal) {
return false;
}
nsAutoCString serializedOrigin;
nsContentSecurityManager::GetSerializedOrigin(
mLoadInfo->TriggeringPrincipal(), resourcePrincipal, serializedOrigin,
mLoadInfo);
if (!serializedOrigin.Equals(origin)) {
return false;
}
// Step 5
// If request’s credentials mode is not "include", then return success.
if (cookiePolicy != nsILoadInfo::SEC_COOKIES_INCLUDE) {
return true;
}
// Step 6
// Let credentials be the result of getting
// `Access-Control-Allow-Credentials` from response’s header list.
nsAutoCString credentials;
rv = GetResponseHeader("Access-Control-Allow-Credentials"_ns, credentials);
// Step 7 and 8
// If credentials is `true`, then return success.
// (else) return failure.
return NS_SUCCEEDED(rv) && credentials.EqualsLiteral("true");
}
NS_IMETHODIMP
HttpBaseChannel::BodyInfoAccessAllowedCheck(nsIPrincipal* aOrigin,
BodyInfoAccess* _retval) {
// Per the Fetch spec, https://fetch.spec.whatwg.org/#response-body-info,
// the bodyInfo for Resource Timing and Navigation Timing info consists of
// encoded size, decoded size, and content type. It is however made opaque
// whenever the response is turned into a network error, which sets its
// bodyInfo to its default values (sizes=0, content-type="").
// Case 1:
// "no-cors" -> Upon success, fetch will return an opaque filtered response.
// An opaque(-redirect) filtered response is a filtered response
// whose ... body info is a new response body info.
auto tainting = mLoadInfo->GetTainting();
if (tainting == mozilla::LoadTainting::Opaque) {
*_retval = BodyInfoAccess::DISALLOWED;
return NS_OK;
}
// Case 2:
// If request’s response tainting is "cors" and a CORS check for request
// and response returns failure, then return a network error.
if (tainting == mozilla::LoadTainting::CORS && !PerformCORSCheck()) {
*_retval = BodyInfoAccess::DISALLOWED;
return NS_OK;
}
// Otherwise:
// The fetch response handover, given a fetch params fetchParams
// and a response response, run these steps:
// processResponseEndOfBody:
// - If fetchParams’s request’s mode is not "navigate" or response’s
// has-cross-origin-redirects is false:
// - Let mimeType be the result of extracting a MIME type from
// response’s header list.
// - If mimeType is not failure, then set bodyInfo’s content type to the
// result of minimizing a supported MIME type given mimeType.
dom::RequestMode requestMode;
MOZ_ALWAYS_SUCCEEDS(GetRequestMode(&requestMode));
if (requestMode != RequestMode::Navigate || LoadAllRedirectsSameOrigin()) {
*_retval = BodyInfoAccess::ALLOW_ALL;
return NS_OK;
}
*_retval = BodyInfoAccess::ALLOW_SIZES;
return NS_OK;
}
// https://fetch.spec.whatwg.org/#tao-check
NS_IMETHODIMP
HttpBaseChannel::TimingAllowCheck(nsIPrincipal* aOrigin, bool* _retval) {
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
nsCOMPtr<nsIPrincipal> resourcePrincipal;
nsresult rv =
ssm->GetChannelURIPrincipal(this, getter_AddRefs(resourcePrincipal));
if (NS_FAILED(rv) || !resourcePrincipal || !aOrigin) {
*_retval = false;
return NS_OK;
}
bool sameOrigin = false;
rv = resourcePrincipal->Equals(aOrigin, &sameOrigin);
nsAutoCString serializedOrigin;
nsContentSecurityManager::GetSerializedOrigin(aOrigin, resourcePrincipal,
serializedOrigin, mLoadInfo);
// All redirects are same origin
if (sameOrigin && (!serializedOrigin.IsEmpty() &&
!serializedOrigin.EqualsLiteral("null"))) {
*_retval = true;
return NS_OK;
}
nsAutoCString headerValue;
rv = GetResponseHeader("Timing-Allow-Origin"_ns, headerValue);
if (NS_FAILED(rv)) {
*_retval = false;
return NS_OK;
}
Tokenizer p(headerValue);
Tokenizer::Token t;
p.Record();
nsAutoCString headerItem;
while (p.Next(t)) {
if (t.Type() == Tokenizer::TOKEN_EOF ||
t.Equals(Tokenizer::Token::Char(','))) {
p.Claim(headerItem);
nsHttp::TrimHTTPWhitespace(headerItem, headerItem);
// If the list item contains a case-sensitive match for the value of the
// origin, or a wildcard, return pass
if (headerItem == serializedOrigin || headerItem == "*") {
*_retval = true;
return NS_OK;
}
// We start recording again for the following items in the list
p.Record();
}
}
*_retval = false;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLaunchServiceWorkerStart(TimeStamp* _retval) {
MOZ_ASSERT(_retval);
*_retval = mLaunchServiceWorkerStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetLaunchServiceWorkerStart(TimeStamp aTimeStamp) {
mLaunchServiceWorkerStart = aTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLaunchServiceWorkerEnd(TimeStamp* _retval) {
MOZ_ASSERT(_retval);
*_retval = mLaunchServiceWorkerEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetLaunchServiceWorkerEnd(TimeStamp aTimeStamp) {
mLaunchServiceWorkerEnd = aTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetDispatchFetchEventStart(TimeStamp* _retval) {
MOZ_ASSERT(_retval);
*_retval = mDispatchFetchEventStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetDispatchFetchEventStart(TimeStamp aTimeStamp) {
mDispatchFetchEventStart = aTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetDispatchFetchEventEnd(TimeStamp* _retval) {
MOZ_ASSERT(_retval);
*_retval = mDispatchFetchEventEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetDispatchFetchEventEnd(TimeStamp aTimeStamp) {
mDispatchFetchEventEnd = aTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetHandleFetchEventStart(TimeStamp* _retval) {
MOZ_ASSERT(_retval);
*_retval = mHandleFetchEventStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetHandleFetchEventStart(TimeStamp aTimeStamp) {
mHandleFetchEventStart = aTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetHandleFetchEventEnd(TimeStamp* _retval) {
MOZ_ASSERT(_retval);
*_retval = mHandleFetchEventEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetHandleFetchEventEnd(TimeStamp aTimeStamp) {
mHandleFetchEventEnd = aTimeStamp;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetDomainLookupStart(TimeStamp* _retval) {
*_retval = mTransactionTimings.domainLookupStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetDomainLookupEnd(TimeStamp* _retval) {
*_retval = mTransactionTimings.domainLookupEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetConnectStart(TimeStamp* _retval) {
*_retval = mTransactionTimings.connectStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetTcpConnectEnd(TimeStamp* _retval) {
*_retval = mTransactionTimings.tcpConnectEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetSecureConnectionStart(TimeStamp* _retval) {
*_retval = mTransactionTimings.secureConnectionStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetConnectEnd(TimeStamp* _retval) {
*_retval = mTransactionTimings.connectEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRequestStart(TimeStamp* _retval) {
*_retval = mTransactionTimings.requestStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetResponseStart(TimeStamp* _retval) {
*_retval = mTransactionTimings.responseStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetResponseEnd(TimeStamp* _retval) {
*_retval = mTransactionTimings.responseEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetCacheReadStart(TimeStamp* _retval) {
*_retval = mCacheReadStart;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetCacheReadEnd(TimeStamp* _retval) {
*_retval = mCacheReadEnd;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetTransactionPending(TimeStamp* _retval) {
*_retval = mTransactionTimings.transactionPending;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetInitiatorType(nsAString& aInitiatorType) {
aInitiatorType = mInitiatorType;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetInitiatorType(const nsAString& aInitiatorType) {
mInitiatorType = aInitiatorType;
return NS_OK;
}
#define IMPL_TIMING_ATTR(name) \
NS_IMETHODIMP \
HttpBaseChannel::Get##name##Time(PRTime* _retval) { \
TimeStamp stamp; \
Get##name(&stamp); \
if (stamp.IsNull()) { \
*_retval = 0; \
return NS_OK; \
} \
*_retval = \
mChannelCreationTime + \
(PRTime)((stamp - mChannelCreationTimestamp).ToSeconds() * 1e6); \
return NS_OK; \
}
IMPL_TIMING_ATTR(ChannelCreation)
IMPL_TIMING_ATTR(AsyncOpen)
IMPL_TIMING_ATTR(LaunchServiceWorkerStart)
IMPL_TIMING_ATTR(LaunchServiceWorkerEnd)
IMPL_TIMING_ATTR(DispatchFetchEventStart)
IMPL_TIMING_ATTR(DispatchFetchEventEnd)
IMPL_TIMING_ATTR(HandleFetchEventStart)
IMPL_TIMING_ATTR(HandleFetchEventEnd)
IMPL_TIMING_ATTR(DomainLookupStart)
IMPL_TIMING_ATTR(DomainLookupEnd)
IMPL_TIMING_ATTR(ConnectStart)
IMPL_TIMING_ATTR(TcpConnectEnd)
IMPL_TIMING_ATTR(SecureConnectionStart)
IMPL_TIMING_ATTR(ConnectEnd)
IMPL_TIMING_ATTR(RequestStart)
IMPL_TIMING_ATTR(ResponseStart)
IMPL_TIMING_ATTR(ResponseEnd)
IMPL_TIMING_ATTR(CacheReadStart)
IMPL_TIMING_ATTR(CacheReadEnd)
IMPL_TIMING_ATTR(RedirectStart)
IMPL_TIMING_ATTR(RedirectEnd)
IMPL_TIMING_ATTR(TransactionPending)
#undef IMPL_TIMING_ATTR
void HttpBaseChannel::MaybeReportTimingData() {
// There is no point in continuing, since the performance object in the parent
// isn't the same as the one in the child which will be reporting resource
// performance.
if (XRE_IsE10sParentProcess()) {
return;
}
// Devtools can create fetch requests on behalf the content document.
// If we don't exclude these requests, they'd also be reported
// to the content document.
bool isInDevToolsContext;
mLoadInfo->GetIsInDevToolsContext(&isInDevToolsContext);
if (isInDevToolsContext) {
return;
}
mozilla::dom::PerformanceStorage* documentPerformance =
mLoadInfo->GetPerformanceStorage();
if (documentPerformance) {
documentPerformance->AddEntry(this, this);
return;
}
if (!nsGlobalWindowInner::GetInnerWindowWithId(
mLoadInfo->GetInnerWindowID())) {
// The inner window is in a different process.
dom::ContentChild* child = dom::ContentChild::GetSingleton();
if (!child) {
return;
}
nsAutoString initiatorType;
nsAutoString entryName;
UniquePtr<dom::PerformanceTimingData> performanceTimingData(
dom::PerformanceTimingData::Create(this, this, 0, initiatorType,
entryName));
if (!performanceTimingData) {
return;
}
LoadInfoArgs loadInfoArgs;
mozilla::ipc::LoadInfoToLoadInfoArgs(mLoadInfo, &loadInfoArgs);
child->SendReportFrameTimingData(loadInfoArgs, entryName, initiatorType,
std::move(performanceTimingData));
}
}
NS_IMETHODIMP
HttpBaseChannel::SetReportResourceTiming(bool enabled) {
StoreReportTiming(enabled);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetReportResourceTiming(bool* _retval) {
*_retval = LoadReportTiming();
return NS_OK;
}
nsIURI* HttpBaseChannel::GetReferringPage() {
nsCOMPtr<nsPIDOMWindowInner> pDomWindow = GetInnerDOMWindow();
if (!pDomWindow) {
return nullptr;
}
return pDomWindow->GetDocumentURI();
}
nsPIDOMWindowInner* HttpBaseChannel::GetInnerDOMWindow() {
nsCOMPtr<nsILoadContext> loadContext;
NS_QueryNotificationCallbacks(this, loadContext);
if (!loadContext) {
return nullptr;
}
nsCOMPtr<mozIDOMWindowProxy> domWindow;
loadContext->GetAssociatedWindow(getter_AddRefs(domWindow));
if (!domWindow) {
return nullptr;
}
auto* pDomWindow = nsPIDOMWindowOuter::From(domWindow);
if (!pDomWindow) {
return nullptr;
}
nsCOMPtr<nsPIDOMWindowInner> innerWindow =
pDomWindow->GetCurrentInnerWindow();
if (!innerWindow) {
return nullptr;
}
return innerWindow;
}
//-----------------------------------------------------------------------------
// HttpBaseChannel::nsIThrottledInputChannel
//-----------------------------------------------------------------------------
NS_IMETHODIMP
HttpBaseChannel::SetThrottleQueue(nsIInputChannelThrottleQueue* aQueue) {
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
mThrottleQueue = aQueue;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetThrottleQueue(nsIInputChannelThrottleQueue** aQueue) {
NS_ENSURE_ARG_POINTER(aQueue);
nsCOMPtr<nsIInputChannelThrottleQueue> queue = mThrottleQueue;
queue.forget(aQueue);
return NS_OK;
}
//------------------------------------------------------------------------------
bool HttpBaseChannel::EnsureRequestContextID() {
if (mRequestContextID) {
// Already have a request context ID, no need to do the rest of this work
LOG(("HttpBaseChannel::EnsureRequestContextID this=%p id=%" PRIx64, this,
mRequestContextID));
return true;
}
// Find the loadgroup at the end of the chain in order
// to make sure all channels derived from the load group
// use the same connection scope.
nsCOMPtr<nsILoadGroupChild> childLoadGroup = do_QueryInterface(mLoadGroup);
if (!childLoadGroup) {
return false;
}
nsCOMPtr<nsILoadGroup> rootLoadGroup;
childLoadGroup->GetRootLoadGroup(getter_AddRefs(rootLoadGroup));
if (!rootLoadGroup) {
return false;
}
// Set the load group connection scope on this channel and its transaction
rootLoadGroup->GetRequestContextID(&mRequestContextID);
LOG(("HttpBaseChannel::EnsureRequestContextID this=%p id=%" PRIx64, this,
mRequestContextID));
return true;
}
bool HttpBaseChannel::EnsureRequestContext() {
if (mRequestContext) {
// Already have a request context, no need to do the rest of this work
return true;
}
if (!EnsureRequestContextID()) {
return false;
}
nsIRequestContextService* rcsvc = gHttpHandler->GetRequestContextService();
if (!rcsvc) {
return false;
}
rcsvc->GetRequestContext(mRequestContextID, getter_AddRefs(mRequestContext));
return static_cast<bool>(mRequestContext);
}
void HttpBaseChannel::EnsureBrowserId() {
if (mBrowserId) {
return;
}
RefPtr<dom::BrowsingContext> bc;
MOZ_ALWAYS_SUCCEEDS(mLoadInfo->GetBrowsingContext(getter_AddRefs(bc)));
if (bc) {
mBrowserId = bc->GetBrowserId();
}
}
void HttpBaseChannel::SetCorsPreflightParameters(
const nsTArray<nsCString>& aUnsafeHeaders,
bool aShouldStripRequestBodyHeader, bool aShouldStripAuthHeader) {
MOZ_RELEASE_ASSERT(!LoadRequestObserversCalled());
StoreRequireCORSPreflight(true);
mUnsafeHeaders = aUnsafeHeaders.Clone();
if (aShouldStripRequestBodyHeader || aShouldStripAuthHeader) {
mUnsafeHeaders.RemoveElementsBy([&](const nsCString& aHeader) {
return (aShouldStripRequestBodyHeader &&
(aHeader.LowerCaseEqualsASCII("content-type") ||
aHeader.LowerCaseEqualsASCII("content-encoding") ||
aHeader.LowerCaseEqualsASCII("content-language") ||
aHeader.LowerCaseEqualsASCII("content-location"))) ||
(aShouldStripAuthHeader &&
aHeader.LowerCaseEqualsASCII("authorization"));
});
}
}
void HttpBaseChannel::SetAltDataForChild(bool aIsForChild) {
StoreAltDataForChild(aIsForChild);
}
NS_IMETHODIMP
HttpBaseChannel::GetBlockAuthPrompt(bool* aValue) {
if (!aValue) {
return NS_ERROR_FAILURE;
}
*aValue = LoadBlockAuthPrompt();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetBlockAuthPrompt(bool aValue) {
ENSURE_CALLED_BEFORE_CONNECT();
StoreBlockAuthPrompt(aValue);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetConnectionInfoHashKey(nsACString& aConnectionInfoHashKey) {
if (!mConnectionInfo) {
return NS_ERROR_FAILURE;
}
aConnectionInfoHashKey.Assign(mConnectionInfo->HashKey());
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetLastRedirectFlags(uint32_t* aValue) {
NS_ENSURE_ARG(aValue);
*aValue = mLastRedirectFlags;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetLastRedirectFlags(uint32_t aValue) {
mLastRedirectFlags = aValue;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetNavigationStartTimeStamp(TimeStamp* aTimeStamp) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
HttpBaseChannel::SetNavigationStartTimeStamp(TimeStamp aTimeStamp) {
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult HttpBaseChannel::CheckRedirectLimit(nsIURI* aNewURI,
uint32_t aRedirectFlags) const {
if (aRedirectFlags & nsIChannelEventSink::REDIRECT_INTERNAL) {
// for internal redirect due to auth retry we do not have any limit
// as we might restrict the number of times a user might retry
// authentication
if (aRedirectFlags & nsIChannelEventSink::REDIRECT_AUTH_RETRY) {
return NS_OK;
}
// Some platform features, like Service Workers, depend on internal
// redirects. We should allow some number of internal redirects above
// and beyond the normal redirect limit so these features continue
// to work.
static const int8_t kMinInternalRedirects = 5;
if (mInternalRedirectCount >= (mRedirectionLimit + kMinInternalRedirects)) {
LOG(("internal redirection limit reached!\n"));
return NS_ERROR_REDIRECT_LOOP;
}
return NS_OK;
}
MOZ_ASSERT(aRedirectFlags & (nsIChannelEventSink::REDIRECT_TEMPORARY |
nsIChannelEventSink::REDIRECT_PERMANENT |
nsIChannelEventSink::REDIRECT_STS_UPGRADE));
if (mRedirectCount >= mRedirectionLimit) {
LOG(("redirection limit reached!\n"));
return NS_ERROR_REDIRECT_LOOP;
}
// in case https-only mode is enabled which upgrades top-level requests to
// https and the page answers with a redirect (meta, 302, win.location, ...)
// then this method can break the cycle which causes the https-only exception
// page to appear. Note that https-first mode breaks upgrade downgrade endless
// loops within ShouldUpgradeHttpsFirstRequest because https-first does not
// display an exception page but needs a soft fallback/downgrade.
if (nsHTTPSOnlyUtils::IsUpgradeDowngradeEndlessLoop(
mURI, aNewURI, mLoadInfo,
{nsHTTPSOnlyUtils::UpgradeDowngradeEndlessLoopOptions::
EnforceForHTTPSOnlyMode})) {
// Mark that we didn't upgrade to https due to loop detection in https-only
// mode to show https-only error page. We know that we are in https-only
// mode, because we passed `EnforceForHTTPSOnlyMode` to
// `IsUpgradeDowngradeEndlessLoop`. In other words we upgrade the request
// with https-only mode, but then immediately cancel the request.
uint32_t httpsOnlyStatus = mLoadInfo->GetHttpsOnlyStatus();
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_UNINITIALIZED) {
httpsOnlyStatus ^= nsILoadInfo::HTTPS_ONLY_UNINITIALIZED;
httpsOnlyStatus |=
nsILoadInfo::HTTPS_ONLY_UPGRADED_LISTENER_NOT_REGISTERED;
mLoadInfo->SetHttpsOnlyStatus(httpsOnlyStatus);
}
LOG(("upgrade downgrade redirect loop!\n"));
return NS_ERROR_REDIRECT_LOOP;
}
// in case of http-first mode we want to add an exception to disable the
// upgrade behavior if we have upgrade-downgrade loop to break the loop and
// load the http request next
if (mozilla::StaticPrefs::
dom_security_https_first_add_exception_on_failure() &&
nsHTTPSOnlyUtils::IsUpgradeDowngradeEndlessLoop(
mURI, aNewURI, mLoadInfo,
{nsHTTPSOnlyUtils::UpgradeDowngradeEndlessLoopOptions::
EnforceForHTTPSFirstMode})) {
nsHTTPSOnlyUtils::AddHTTPSFirstException(mURI, mLoadInfo);
}
return NS_OK;
}
// NOTE: This function duplicates code from nsBaseChannel. This will go away
// once HTTP uses nsBaseChannel (part of bug 312760)
/* static */
void HttpBaseChannel::CallTypeSniffers(void* aClosure, const uint8_t* aData,
uint32_t aCount) {
nsIChannel* chan = static_cast<nsIChannel*>(aClosure);
const char* snifferType = [chan]() {
if (RefPtr<nsHttpChannel> httpChannel = do_QueryObject(chan)) {
switch (httpChannel->GetSnifferCategoryType()) {
case SnifferCategoryType::NetContent:
return NS_CONTENT_SNIFFER_CATEGORY;
case SnifferCategoryType::OpaqueResponseBlocking:
return NS_ORB_SNIFFER_CATEGORY;
case SnifferCategoryType::All:
return NS_CONTENT_AND_ORB_SNIFFER_CATEGORY;
default:
MOZ_ASSERT_UNREACHABLE("Unexpected SnifferCategoryType!");
}
}
return NS_CONTENT_SNIFFER_CATEGORY;
}();
nsAutoCString newType;
NS_SniffContent(snifferType, chan, aData, aCount, newType);
if (!newType.IsEmpty()) {
chan->SetContentType(newType);
}
}
template <class T>
static void ParseServerTimingHeader(
const UniquePtr<T>& aHeader, nsTArray<nsCOMPtr<nsIServerTiming>>& aOutput) {
if (!aHeader) {
return;
}
nsAutoCString serverTimingHeader;
(void)aHeader->GetHeader(nsHttp::Server_Timing, serverTimingHeader);
if (serverTimingHeader.IsEmpty()) {
return;
}
ServerTimingParser parser(serverTimingHeader);
parser.Parse();
nsTArray<nsCOMPtr<nsIServerTiming>> array = parser.TakeServerTimingHeaders();
aOutput.AppendElements(array);
}
NS_IMETHODIMP
HttpBaseChannel::GetServerTiming(nsIArray** aServerTiming) {
nsresult rv;
NS_ENSURE_ARG_POINTER(aServerTiming);
nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsTArray<nsCOMPtr<nsIServerTiming>> data;
rv = GetNativeServerTiming(data);
NS_ENSURE_SUCCESS(rv, rv);
for (const auto& entry : data) {
array->AppendElement(entry);
}
array.forget(aServerTiming);
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetNativeServerTiming(
nsTArray<nsCOMPtr<nsIServerTiming>>& aServerTiming) {
aServerTiming.Clear();
if (nsContentUtils::ComputeIsSecureContext(this)) {
ParseServerTimingHeader(mResponseHead, aServerTiming);
ParseServerTimingHeader(mResponseTrailers, aServerTiming);
}
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::CancelByURLClassifier(nsresult aErrorCode) {
MOZ_ASSERT(
UrlClassifierFeatureFactory::IsClassifierBlockingErrorCode(aErrorCode));
return Cancel(aErrorCode);
}
NS_IMETHODIMP HttpBaseChannel::SetIPv4Disabled() {
mCaps |= NS_HTTP_DISABLE_IPV4;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::SetIPv6Disabled() {
mCaps |= NS_HTTP_DISABLE_IPV6;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::GetResponseEmbedderPolicy(
bool aIsOriginTrialCoepCredentiallessEnabled,
nsILoadInfo::CrossOriginEmbedderPolicy* aOutPolicy) {
*aOutPolicy = nsILoadInfo::EMBEDDER_POLICY_NULL;
if (!mResponseHead) {
return NS_ERROR_NOT_AVAILABLE;
}
if (!nsContentUtils::ComputeIsSecureContext(this)) {
// Feature is only available for secure contexts.
return NS_OK;
}
nsAutoCString content;
(void)mResponseHead->GetHeader(nsHttp::Cross_Origin_Embedder_Policy, content);
*aOutPolicy = NS_GetCrossOriginEmbedderPolicyFromHeader(
content, aIsOriginTrialCoepCredentiallessEnabled);
return NS_OK;
}
// Obtain a cross-origin opener-policy from a response response and a
// cross-origin opener policy initiator.
// https://gist.github.com/annevk/6f2dd8c79c77123f39797f6bdac43f3e
NS_IMETHODIMP HttpBaseChannel::ComputeCrossOriginOpenerPolicy(
nsILoadInfo::CrossOriginOpenerPolicy aInitiatorPolicy,
nsILoadInfo::CrossOriginOpenerPolicy* aOutPolicy) {
MOZ_ASSERT(aOutPolicy);
*aOutPolicy = nsILoadInfo::OPENER_POLICY_UNSAFE_NONE;
if (!mResponseHead) {
return NS_ERROR_NOT_AVAILABLE;
}
// COOP headers are ignored for insecure-context loads.
if (!nsContentUtils::ComputeIsSecureContext(this)) {
return NS_OK;
}
nsAutoCString openerPolicy;
(void)mResponseHead->GetHeader(nsHttp::Cross_Origin_Opener_Policy,
openerPolicy);
// Cross-Origin-Opener-Policy = %s"same-origin" /
// %s"same-origin-allow-popups" /
// %s"unsafe-none"; case-sensitive
nsCOMPtr<nsISFVService> sfv = GetSFVService();
nsCOMPtr<nsISFVItem> item;
nsresult rv = sfv->ParseItem(openerPolicy, getter_AddRefs(item));
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsISFVBareItem> value;
rv = item->GetValue(getter_AddRefs(value));
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsISFVToken> token = do_QueryInterface(value);
if (!token) {
return NS_ERROR_UNEXPECTED;
}
rv = token->GetValue(openerPolicy);
if (NS_FAILED(rv)) {
return rv;
}
nsILoadInfo::CrossOriginOpenerPolicy policy =
nsILoadInfo::OPENER_POLICY_UNSAFE_NONE;
if (openerPolicy.EqualsLiteral("same-origin")) {
policy = nsILoadInfo::OPENER_POLICY_SAME_ORIGIN;
} else if (openerPolicy.EqualsLiteral("same-origin-allow-popups")) {
policy = nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_ALLOW_POPUPS;
}
if (policy == nsILoadInfo::OPENER_POLICY_SAME_ORIGIN) {
nsILoadInfo::CrossOriginEmbedderPolicy coep =
nsILoadInfo::EMBEDDER_POLICY_NULL;
bool isCoepCredentiallessEnabled;
rv = mLoadInfo->GetIsOriginTrialCoepCredentiallessEnabledForTopLevel(
&isCoepCredentiallessEnabled);
if (!isCoepCredentiallessEnabled) {
nsAutoCString originTrialToken;
(void)mResponseHead->GetHeader(nsHttp::OriginTrial, originTrialToken);
if (!originTrialToken.IsEmpty()) {
nsCOMPtr<nsIPrincipal> resultPrincipal;
rv = nsContentUtils::GetSecurityManager()->GetChannelResultPrincipal(
this, getter_AddRefs(resultPrincipal));
if (!NS_WARN_IF(NS_FAILED(rv))) {
OriginTrials trials;
trials.UpdateFromToken(NS_ConvertASCIItoUTF16(originTrialToken),
resultPrincipal);
if (trials.IsEnabled(OriginTrial::CoepCredentialless)) {
isCoepCredentiallessEnabled = true;
}
}
}
}
NS_ENSURE_SUCCESS(rv, rv);
if (NS_SUCCEEDED(
GetResponseEmbedderPolicy(isCoepCredentiallessEnabled, &coep)) &&
(coep == nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP ||
coep == nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS)) {
policy =
nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP;
}
}
*aOutPolicy = policy;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetCrossOriginOpenerPolicy(
nsILoadInfo::CrossOriginOpenerPolicy* aPolicy) {
MOZ_ASSERT(aPolicy);
if (!aPolicy) {
return NS_ERROR_INVALID_ARG;
}
// If this method is called before OnStartRequest (ie. before we call
// ComputeCrossOriginOpenerPolicy) or if we were unable to compute the
// policy we'll throw an error.
if (!LoadOnStartRequestCalled()) {
return NS_ERROR_NOT_AVAILABLE;
}
*aPolicy = mComputedCrossOriginOpenerPolicy;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::HasCrossOriginOpenerPolicyMismatch(bool* aIsMismatch) {
// This should only be called in parent process.
MOZ_ASSERT(XRE_IsParentProcess());
*aIsMismatch = LoadHasCrossOriginOpenerPolicyMismatch();
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetOriginAgentClusterHeader(bool* aValue) {
MOZ_ASSERT(XRE_IsParentProcess());
if (!mResponseHead) {
return NS_ERROR_NOT_AVAILABLE;
}
nsAutoCString content;
nsresult rv = mResponseHead->GetHeader(nsHttp::OriginAgentCluster, content);
if (NS_FAILED(rv)) {
return rv;
}
// Origin-Agent-Cluster = <boolean>
nsCOMPtr<nsISFVService> sfv = GetSFVService();
nsCOMPtr<nsISFVItem> item;
rv = sfv->ParseItem(content, getter_AddRefs(item));
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsISFVBareItem> value;
rv = item->GetValue(getter_AddRefs(value));
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsISFVBool> flag = do_QueryInterface(value);
if (!flag) {
return NS_ERROR_NOT_AVAILABLE;
}
return flag->GetValue(aValue);
}
void HttpBaseChannel::MaybeFlushConsoleReports() {
// Flush if we have a known window ID.
if (mLoadInfo->GetInnerWindowID() > 0) {
FlushReportsToConsole(mLoadInfo->GetInnerWindowID());
return;
}
// If this channel is part of a loadGroup, we can flush the console reports
// immediately.
nsCOMPtr<nsILoadGroup> loadGroup;
nsresult rv = GetLoadGroup(getter_AddRefs(loadGroup));
if (NS_SUCCEEDED(rv) && loadGroup) {
FlushConsoleReports(loadGroup);
}
}
void HttpBaseChannel::DoDiagnosticAssertWhenOnStopNotCalledOnDestroy() {}
bool HttpBaseChannel::Http3Allowed() const {
bool allowedProxyInfo =
mProxyInfo ? (static_cast<nsProxyInfo*>(mProxyInfo.get())->IsDirect() ||
static_cast<nsProxyInfo*>(mProxyInfo.get())->IsHttp3Proxy())
: true;
// TODO: When mUpgradeProtocolCallback is not null, we should allow HTTP/3 for
// connect-udp.
return !mUpgradeProtocolCallback && allowedProxyInfo &&
!(mCaps & NS_HTTP_BE_CONSERVATIVE) && !LoadBeConservative() &&
LoadAllowHttp3();
}
UniquePtr<nsHttpResponseHead>
HttpBaseChannel::MaybeCloneResponseHeadForCachedResource() {
if (!mResponseHead) {
return nullptr;
}
return MakeUnique<nsHttpResponseHead>(*mResponseHead);
}
void HttpBaseChannel::SetDummyChannelForCachedResource(
const nsHttpResponseHead* aMaybeResponseHead /* = nullptr */) {
mDummyChannelForCachedResource = true;
MOZ_ASSERT(!mResponseHead,
"SetDummyChannelForCachedResource should only be called once");
if (aMaybeResponseHead) {
mResponseHead = MakeUnique<nsHttpResponseHead>(*aMaybeResponseHead);
} else {
mResponseHead = MakeUnique<nsHttpResponseHead>();
}
}
void HttpBaseChannel::SetEarlyHints(
nsTArray<EarlyHintConnectArgs>&& aEarlyHints) {
mEarlyHints = std::move(aEarlyHints);
}
nsTArray<EarlyHintConnectArgs>&& HttpBaseChannel::TakeEarlyHints() {
return std::move(mEarlyHints);
}
NS_IMETHODIMP
HttpBaseChannel::SetEarlyHintPreloaderId(uint64_t aEarlyHintPreloaderId) {
mEarlyHintPreloaderId = aEarlyHintPreloaderId;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetEarlyHintPreloaderId(uint64_t* aEarlyHintPreloaderId) {
NS_ENSURE_ARG_POINTER(aEarlyHintPreloaderId);
*aEarlyHintPreloaderId = mEarlyHintPreloaderId;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetClassicScriptHintCharset(
const nsAString& aClassicScriptHintCharset) {
mClassicScriptHintCharset = aClassicScriptHintCharset;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::GetClassicScriptHintCharset(
nsAString& aClassicScriptHintCharset) {
aClassicScriptHintCharset = mClassicScriptHintCharset;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::SetDocumentCharacterSet(
const nsAString& aDocumentCharacterSet) {
mDocumentCharacterSet = aDocumentCharacterSet;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::GetDocumentCharacterSet(
nsAString& aDocumentCharacterSet) {
aDocumentCharacterSet = mDocumentCharacterSet;
return NS_OK;
}
void HttpBaseChannel::SetConnectionInfo(nsHttpConnectionInfo* aCI) {
mConnectionInfo = aCI ? aCI->Clone() : nullptr;
}
NS_IMETHODIMP
HttpBaseChannel::GetIsProxyUsed(bool* aIsProxyUsed) {
if (mProxyInfo) {
if (!static_cast<nsProxyInfo*>(mProxyInfo.get())->IsDirect()) {
StoreIsProxyUsed(true);
}
}
*aIsProxyUsed = LoadIsProxyUsed();
return NS_OK;
}
static void CollectORBBlockTelemetry(
const OpaqueResponseBlockedTelemetryReason aTelemetryReason,
ExtContentPolicy aPolicy) {
glean::orb::block_reason.EnumGet(aTelemetryReason).Add();
switch (aPolicy) {
case ExtContentPolicy::TYPE_INVALID:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eInvalid)
.Add();
break;
case ExtContentPolicy::TYPE_OTHER:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eOther)
.Add();
break;
case ExtContentPolicy::TYPE_FETCH:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eBlockedFetch)
.Add();
break;
case ExtContentPolicy::TYPE_SCRIPT:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eScript)
.Add();
break;
case ExtContentPolicy::TYPE_JSON:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eJson)
.Add();
break;
case ExtContentPolicy::TYPE_IMAGE:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eImage)
.Add();
break;
case ExtContentPolicy::TYPE_STYLESHEET:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eStylesheet)
.Add();
break;
case ExtContentPolicy::TYPE_XMLHTTPREQUEST:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eXmlhttprequest)
.Add();
break;
case ExtContentPolicy::TYPE_DTD:
glean::orb::block_initiator.EnumGet(glean::orb::BlockInitiatorLabel::eDtd)
.Add();
break;
case ExtContentPolicy::TYPE_FONT:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eFont)
.Add();
break;
case ExtContentPolicy::TYPE_MEDIA:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eMedia)
.Add();
break;
case ExtContentPolicy::TYPE_CSP_REPORT:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eCspReport)
.Add();
break;
case ExtContentPolicy::TYPE_XSLT:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eXslt)
.Add();
break;
case ExtContentPolicy::TYPE_IMAGESET:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eImageset)
.Add();
break;
case ExtContentPolicy::TYPE_WEB_MANIFEST:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eWebManifest)
.Add();
break;
case ExtContentPolicy::TYPE_SPECULATIVE:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eSpeculative)
.Add();
break;
case ExtContentPolicy::TYPE_UA_FONT:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eUaFont)
.Add();
break;
case ExtContentPolicy::TYPE_PROXIED_WEBRTC_MEDIA:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eProxiedWebrtcMedia)
.Add();
break;
case ExtContentPolicy::TYPE_PING:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::ePing)
.Add();
break;
case ExtContentPolicy::TYPE_BEACON:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eBeacon)
.Add();
break;
case ExtContentPolicy::TYPE_WEB_TRANSPORT:
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eWebTransport)
.Add();
break;
case ExtContentPolicy::TYPE_WEB_IDENTITY:
// Don't bother extending the telemetry for this.
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eOther)
.Add();
break;
case ExtContentPolicy::TYPE_DOCUMENT:
case ExtContentPolicy::TYPE_SUBDOCUMENT:
case ExtContentPolicy::TYPE_OBJECT:
case ExtContentPolicy::TYPE_WEBSOCKET:
case ExtContentPolicy::TYPE_SAVEAS_DOWNLOAD:
MOZ_ASSERT_UNREACHABLE("Shouldn't block this type");
// DOCUMENT, SUBDOCUMENT, OBJECT,
// WEBSOCKET and SAVEAS_DOWNLOAD are excluded from ORB
glean::orb::block_initiator
.EnumGet(glean::orb::BlockInitiatorLabel::eExcluded)
.Add();
break;
// Do not add default: so that compilers can catch the missing case.
}
}
void HttpBaseChannel::LogORBError(
const nsAString& aReason,
const OpaqueResponseBlockedTelemetryReason aTelemetryReason) {
auto policy = mLoadInfo->GetExternalContentPolicyType();
CollectORBBlockTelemetry(aTelemetryReason, policy);
// Blocking `ExtContentPolicy::TYPE_BEACON` isn't web observable, so keep
// quiet in the console about blocking it.
if (policy == ExtContentPolicy::TYPE_BEACON) {
return;
}
RefPtr<dom::Document> doc;
mLoadInfo->GetLoadingDocument(getter_AddRefs(doc));
nsAutoCString uri;
nsresult rv = nsContentUtils::AnonymizeURI(mURI, uri);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
uint64_t contentWindowId;
GetTopLevelContentWindowId(&contentWindowId);
if (contentWindowId) {
nsContentUtils::ReportToConsoleByWindowID(
u"A resource is blocked by OpaqueResponseBlocking, please check browser console for details."_ns,
nsIScriptError::warningFlag, "ORB"_ns, contentWindowId,
SourceLocation(mURI.get()));
}
AutoTArray<nsString, 2> params;
params.AppendElement(NS_ConvertUTF8toUTF16(uri));
params.AppendElement(aReason);
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "ORB"_ns, doc,
nsContentUtils::eNECKO_PROPERTIES,
"ResourceBlockedORB", params);
}
NS_IMETHODIMP HttpBaseChannel::SetEarlyHintLinkType(
uint32_t aEarlyHintLinkType) {
mEarlyHintLinkType = aEarlyHintLinkType;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::GetEarlyHintLinkType(
uint32_t* aEarlyHintLinkType) {
*aEarlyHintLinkType = mEarlyHintLinkType;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetHasContentDecompressed(bool aValue) {
LOG(("HttpBaseChannel::SetHasContentDecompressed [this=%p value=%d]\n", this,
aValue));
mHasContentDecompressed = aValue;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetHasContentDecompressed(bool* value) {
*value = mHasContentDecompressed;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::SetRenderBlocking(bool aRenderBlocking) {
mRenderBlocking = aRenderBlocking;
return NS_OK;
}
NS_IMETHODIMP
HttpBaseChannel::GetRenderBlocking(bool* aRenderBlocking) {
*aRenderBlocking = mRenderBlocking;
return NS_OK;
}
NS_IMETHODIMP HttpBaseChannel::GetLastTransportStatus(
nsresult* aLastTransportStatus) {
return NS_ERROR_NOT_IMPLEMENTED;
}
void HttpBaseChannel::SetFetchPriorityDOM(
mozilla::dom::FetchPriority aPriority) {
switch (aPriority) {
case mozilla::dom::FetchPriority::Auto:
SetFetchPriority(nsIClassOfService::FETCHPRIORITY_AUTO);
return;
case mozilla::dom::FetchPriority::High:
SetFetchPriority(nsIClassOfService::FETCHPRIORITY_HIGH);
return;
case mozilla::dom::FetchPriority::Low:
SetFetchPriority(nsIClassOfService::FETCHPRIORITY_LOW);
return;
default:
MOZ_ASSERT_UNREACHABLE();
}
}
} // namespace net
} // namespace mozilla
|