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
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=4 sw=2 sts=2 et cin: */
/* 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 "DecoderDoctorDiagnostics.h"
#include "HttpLog.h"
#include "nsNetUtil.h"
#include "mozilla/Atomics.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/Components.h"
#include "mozilla/Encoding.h"
#include "mozilla/LoadContext.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Monitor.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/StaticPrefs_urlclassifier.h"
#include "mozilla/StoragePrincipalHelper.h"
#include "mozilla/TaskQueue.h"
#include "nsAboutProtocolUtils.h"
#include "nsBufferedStreams.h"
#include "nsCategoryCache.h"
#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsEscape.h"
#include "nsFileStreams.h"
#include "nsHashKeys.h"
#include "nsHttp.h"
#include "nsMimeTypes.h"
#include "nsIAuthPrompt.h"
#include "nsIAuthPrompt2.h"
#include "nsIAuthPromptAdapterFactory.h"
#include "nsIBufferedStreams.h"
#include "nsBufferedStreams.h"
#include "nsIChannelEventSink.h"
#include "nsIClassifiedChannel.h"
#include "nsIContentSniffer.h"
#include "mozilla/dom/Document.h"
#include "nsIDownloader.h"
#include "nsIFileProtocolHandler.h"
#include "nsIFileStreams.h"
#include "nsIFileURL.h"
#include "nsIIDNService.h"
#include "nsIInputStreamChannel.h"
#include "nsIInputStreamPump.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsILoadContext.h"
#include "nsIMIMEHeaderParam.h"
#include "nsINode.h"
#include "nsIObjectLoadingContent.h"
#include "nsPersistentProperties.h"
#include "nsIPrivateBrowsingChannel.h"
#include "nsIPropertyBag2.h"
#include "nsIProtocolProxyService.h"
#include "mozilla/net/RedirectChannelRegistrar.h"
#include "nsRequestObserverProxy.h"
#include "nsISensitiveInfoHiddenURI.h"
#include "nsISimpleStreamListener.h"
#include "nsISocketProvider.h"
#include "nsIStandardURL.h"
#include "nsIStreamLoader.h"
#include "nsIIncrementalStreamLoader.h"
#include "nsStringStream.h"
#include "nsSyncStreamListener.h"
#include "nsITextToSubURI.h"
#include "nsIURIWithSpecialOrigin.h"
#include "nsIViewSourceChannel.h"
#include "nsInterfaceRequestorAgg.h"
#include "nsINestedURI.h"
#include "mozilla/dom/nsCSPUtils.h"
#include "mozilla/dom/nsHTTPSOnlyUtils.h"
#include "mozilla/dom/nsMixedContentBlocker.h"
#include "mozilla/dom/BlobURLProtocolHandler.h"
#include "mozilla/net/HttpBaseChannel.h"
#include "nsIScriptError.h"
#include "nsISiteSecurityService.h"
#include "nsHttpHandler.h"
#include "nsNSSComponent.h"
#include "nsIRedirectHistoryEntry.h"
#include "nsICertStorage.h"
#include "nsICertOverrideService.h"
#include "nsQueryObject.h"
#include "mozIThirdPartyUtil.h"
#include "../mime/nsMIMEHeaderParamImpl.h"
#include "nsStandardURL.h"
#include "DefaultURI.h"
#include "nsChromeProtocolHandler.h"
#include "nsJSProtocolHandler.h"
#include "nsDataHandler.h"
#include "mozilla/dom/BlobURLProtocolHandler.h"
#include "nsStreamUtils.h"
#include "nsSocketTransportService2.h"
#include "nsViewSourceHandler.h"
#include "nsJARURI.h"
#ifndef XP_IOS
# include "nsIconURI.h"
#endif
#include "nsAboutProtocolHandler.h"
#include "nsResProtocolHandler.h"
#include "mozilla/net/CookieJarSettings.h"
#include "mozilla/net/MozSrcProtocolHandler.h"
#include "mozilla/net/ExtensionProtocolHandler.h"
#include "mozilla/net/PageThumbProtocolHandler.h"
#include "mozilla/net/SFVService.h"
#include "nsICookieService.h"
#include "nsIXPConnect.h"
#include "nsParserConstants.h"
#include "nsCRT.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/dom/MediaList.h"
#include "MediaContainerType.h"
#include "DecoderTraits.h"
#include "imgLoader.h"
#if defined(MOZ_THUNDERBIRD) || defined(MOZ_SUITE)
# include "nsNewMailnewsURI.h"
#endif
using namespace mozilla;
using namespace mozilla::net;
using mozilla::dom::BlobURLProtocolHandler;
using mozilla::dom::ClientInfo;
using mozilla::dom::PerformanceStorage;
using mozilla::dom::ServiceWorkerDescriptor;
#define MAX_RECURSION_COUNT 50
enum class ClassifierMode {
Disabled = 0,
AntiTracking = 1,
SafeBrowsing = 2,
Enabled = 3,
};
already_AddRefed<nsIIOService> do_GetIOService(nsresult* error /* = 0 */) {
nsCOMPtr<nsIIOService> io;
io = mozilla::components::IO::Service();
if (error) *error = io ? NS_OK : NS_ERROR_FAILURE;
return io.forget();
}
nsresult NS_NewLocalFileInputStream(nsIInputStream** result, nsIFile* file,
int32_t ioFlags /* = -1 */,
int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsresult rv;
nsCOMPtr<nsIFileInputStream> in =
do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = in->Init(file, ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) in.forget(result);
}
return rv;
}
Result<nsCOMPtr<nsIInputStream>, nsresult> NS_NewLocalFileInputStream(
nsIFile* file, int32_t ioFlags /* = -1 */, int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsCOMPtr<nsIInputStream> stream;
const nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), file,
ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) {
return stream;
}
return Err(rv);
}
nsresult NS_NewLocalFileOutputStream(nsIOutputStream** result, nsIFile* file,
int32_t ioFlags /* = -1 */,
int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsresult rv;
nsCOMPtr<nsIFileOutputStream> out =
do_CreateInstance(NS_LOCALFILEOUTPUTSTREAM_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = out->Init(file, ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) out.forget(result);
}
return rv;
}
Result<nsCOMPtr<nsIOutputStream>, nsresult> NS_NewLocalFileOutputStream(
nsIFile* file, int32_t ioFlags /* = -1 */, int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsCOMPtr<nsIOutputStream> stream;
const nsresult rv = NS_NewLocalFileOutputStream(getter_AddRefs(stream), file,
ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) {
return stream;
}
return Err(rv);
}
nsresult NS_NewLocalFileOutputStream(nsIOutputStream** result,
const mozilla::ipc::FileDescriptor& fd) {
nsCOMPtr<nsIFileOutputStream> out;
nsFileOutputStream::Create(NS_GET_IID(nsIFileOutputStream),
getter_AddRefs(out));
nsresult rv =
static_cast<nsFileOutputStream*>(out.get())->InitWithFileDescriptor(fd);
if (NS_FAILED(rv)) {
return rv;
}
out.forget(result);
return NS_OK;
}
nsresult net_EnsureIOService(nsIIOService** ios, nsCOMPtr<nsIIOService>& grip) {
nsresult rv = NS_OK;
if (!*ios) {
grip = do_GetIOService(&rv);
*ios = grip;
}
return rv;
}
nsresult NS_NewFileURI(
nsIURI** result, nsIFile* spec,
nsIIOService*
ioService /* = nullptr */) // pass in nsIIOService to optimize callers
{
nsresult rv;
nsCOMPtr<nsIIOService> grip;
rv = net_EnsureIOService(&ioService, grip);
if (ioService) rv = ioService->NewFileURI(spec, result);
return rv;
}
nsresult NS_GetURIWithNewRef(nsIURI* aInput, const nsACString& aRef,
nsIURI** aOutput) {
MOZ_DIAGNOSTIC_ASSERT(aRef.IsEmpty() || aRef[0] == '#');
if (NS_WARN_IF(!aInput || !aOutput)) {
return NS_ERROR_INVALID_ARG;
}
bool hasRef;
nsresult rv = aInput->GetHasRef(&hasRef);
nsAutoCString ref;
if (NS_SUCCEEDED(rv)) {
rv = aInput->GetRef(ref);
}
// If the ref is already equal to the new ref, we do not need to do anything.
// Also, if the GetRef failed (it could return NS_ERROR_NOT_IMPLEMENTED)
// we can assume SetRef would fail as well, so returning the original
// URI is OK.
//
// Note that aRef contains the hash, but ref doesn't, so need to account for
// that in the equality check.
if (NS_FAILED(rv) || (!hasRef && aRef.IsEmpty()) ||
(!aRef.IsEmpty() && hasRef &&
Substring(aRef.Data() + 1, aRef.Length() - 1) == ref)) {
nsCOMPtr<nsIURI> uri = aInput;
uri.forget(aOutput);
return NS_OK;
}
return NS_MutateURI(aInput).SetRef(aRef).Finalize(aOutput);
}
nsresult NS_GetURIWithoutRef(nsIURI* aInput, nsIURI** aOutput) {
return NS_GetURIWithNewRef(aInput, ""_ns, aOutput);
}
nsresult NS_NewChannelInternal(
nsIChannel** outChannel, nsIURI* aUri, nsILoadInfo* aLoadInfo,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */) {
// NS_NewChannelInternal is mostly called for channel redirects. We should
// allow the creation of a channel even if the original channel did not have a
// loadinfo attached.
NS_ENSURE_ARG_POINTER(outChannel);
nsCOMPtr<nsIIOService> grip;
nsresult rv = net_EnsureIOService(&aIoService, grip);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIChannel> channel;
rv = aIoService->NewChannelFromURIWithLoadInfo(aUri, aLoadInfo,
getter_AddRefs(channel));
NS_ENSURE_SUCCESS(rv, rv);
if (aLoadGroup) {
rv = channel->SetLoadGroup(aLoadGroup);
NS_ENSURE_SUCCESS(rv, rv);
}
if (aCallbacks) {
rv = channel->SetNotificationCallbacks(aCallbacks);
NS_ENSURE_SUCCESS(rv, rv);
}
#ifdef DEBUG
nsLoadFlags channelLoadFlags = 0;
channel->GetLoadFlags(&channelLoadFlags);
// Will be removed when we remove LOAD_REPLACE altogether
// This check is trying to catch protocol handlers that still
// try to set the LOAD_REPLACE flag.
MOZ_DIAGNOSTIC_ASSERT(!(channelLoadFlags & nsIChannel::LOAD_REPLACE));
#endif
if (aLoadFlags != nsIRequest::LOAD_NORMAL) {
rv = channel->SetLoadFlags(aLoadFlags);
NS_ENSURE_SUCCESS(rv, rv);
}
if (aPerformanceStorage) {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
loadInfo->SetPerformanceStorage(aPerformanceStorage);
}
channel.forget(outChannel);
return NS_OK;
}
namespace {
void AssertLoadingPrincipalAndClientInfoMatch(
nsIPrincipal* aLoadingPrincipal, const ClientInfo& aLoadingClientInfo,
nsContentPolicyType aType) {
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
// Verify that the provided loading ClientInfo matches the loading
// principal. Unfortunately we can't just use nsIPrincipal::Equals() here
// because of some corner cases:
//
// 1. Worker debugger scripts want to use a system loading principal for
// worker scripts with a content principal. We exempt these from this
// check.
// 2. Null principals currently require exact object identity for
// nsIPrincipal::Equals() to return true. This doesn't work here because
// ClientInfo::GetPrincipal() uses PrincipalInfoToPrincipal() to allocate
// a new object. To work around this we compare the principal origin
// string itself. If bug 1431771 is fixed then we could switch to
// Equals().
// Allow worker debugger to load with a system principal.
if (aLoadingPrincipal->IsSystemPrincipal() &&
(aType == nsIContentPolicy::TYPE_INTERNAL_WORKER ||
aType == nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER ||
aType == nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER ||
aType == nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS ||
aType == nsIContentPolicy::TYPE_INTERNAL_WORKER_STATIC_MODULE)) {
return;
}
// Perform a fast comparison for most principal checks.
auto clientPrincipalOrErr(aLoadingClientInfo.GetPrincipal());
if (clientPrincipalOrErr.isOk()) {
nsCOMPtr<nsIPrincipal> clientPrincipal = clientPrincipalOrErr.unwrap();
if (aLoadingPrincipal->Equals(clientPrincipal)) {
return;
}
// Fall back to a slower origin equality test to support null principals.
nsAutoCString loadingOriginNoSuffix;
MOZ_ALWAYS_SUCCEEDS(
aLoadingPrincipal->GetOriginNoSuffix(loadingOriginNoSuffix));
nsAutoCString clientOriginNoSuffix;
MOZ_ALWAYS_SUCCEEDS(
clientPrincipal->GetOriginNoSuffix(clientOriginNoSuffix));
// The client principal will have the partitionKey set if it's in a third
// party context, but the loading principal won't. So, we ignore he
// partitionKey when doing the verification here.
MOZ_DIAGNOSTIC_ASSERT(loadingOriginNoSuffix == clientOriginNoSuffix);
MOZ_DIAGNOSTIC_ASSERT(
aLoadingPrincipal->OriginAttributesRef().EqualsIgnoringPartitionKey(
clientPrincipal->OriginAttributesRef()));
}
#endif
}
} // namespace
nsresult NS_NewChannel(nsIChannel** outChannel, nsIURI* aUri,
nsIPrincipal* aLoadingPrincipal,
nsSecurityFlags aSecurityFlags,
nsContentPolicyType aContentPolicyType,
nsICookieJarSettings* aCookieJarSettings /* = nullptr */,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */,
uint32_t aSandboxFlags /* = 0 */) {
return NS_NewChannelInternal(
outChannel, aUri,
nullptr, // aLoadingNode,
aLoadingPrincipal,
nullptr, // aTriggeringPrincipal
Maybe<ClientInfo>(), Maybe<ServiceWorkerDescriptor>(), aSecurityFlags,
aContentPolicyType, aCookieJarSettings, aPerformanceStorage, aLoadGroup,
aCallbacks, aLoadFlags, aIoService, aSandboxFlags);
}
nsresult NS_NewChannel(nsIChannel** outChannel, nsIURI* aUri,
nsIPrincipal* aLoadingPrincipal,
const ClientInfo& aLoadingClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController,
nsSecurityFlags aSecurityFlags,
nsContentPolicyType aContentPolicyType,
nsICookieJarSettings* aCookieJarSettings /* = nullptr */,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */,
uint32_t aSandboxFlags /* = 0 */) {
AssertLoadingPrincipalAndClientInfoMatch(
aLoadingPrincipal, aLoadingClientInfo, aContentPolicyType);
Maybe<ClientInfo> loadingClientInfo;
loadingClientInfo.emplace(aLoadingClientInfo);
return NS_NewChannelInternal(outChannel, aUri,
nullptr, // aLoadingNode,
aLoadingPrincipal,
nullptr, // aTriggeringPrincipal
loadingClientInfo, aController, aSecurityFlags,
aContentPolicyType, aCookieJarSettings,
aPerformanceStorage, aLoadGroup, aCallbacks,
aLoadFlags, aIoService, aSandboxFlags);
}
nsresult NS_NewChannelInternal(
nsIChannel** outChannel, nsIURI* aUri, nsINode* aLoadingNode,
nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
const Maybe<ClientInfo>& aLoadingClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController,
nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
nsICookieJarSettings* aCookieJarSettings /* = nullptr */,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */,
uint32_t aSandboxFlags /* = 0 */) {
NS_ENSURE_ARG_POINTER(outChannel);
nsCOMPtr<nsIIOService> grip;
nsresult rv = net_EnsureIOService(&aIoService, grip);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIChannel> channel;
rv = aIoService->NewChannelFromURIWithClientAndController(
aUri, aLoadingNode, aLoadingPrincipal, aTriggeringPrincipal,
aLoadingClientInfo, aController, aSecurityFlags, aContentPolicyType,
aSandboxFlags, getter_AddRefs(channel));
if (NS_FAILED(rv)) {
return rv;
}
if (aLoadGroup) {
rv = channel->SetLoadGroup(aLoadGroup);
NS_ENSURE_SUCCESS(rv, rv);
}
if (aCallbacks) {
rv = channel->SetNotificationCallbacks(aCallbacks);
NS_ENSURE_SUCCESS(rv, rv);
}
#ifdef DEBUG
nsLoadFlags channelLoadFlags = 0;
channel->GetLoadFlags(&channelLoadFlags);
// Will be removed when we remove LOAD_REPLACE altogether
// This check is trying to catch protocol handlers that still
// try to set the LOAD_REPLACE flag.
MOZ_DIAGNOSTIC_ASSERT(!(channelLoadFlags & nsIChannel::LOAD_REPLACE));
#endif
if (aLoadFlags != nsIRequest::LOAD_NORMAL) {
rv = channel->SetLoadFlags(aLoadFlags);
NS_ENSURE_SUCCESS(rv, rv);
}
if (aPerformanceStorage || aCookieJarSettings) {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
if (aPerformanceStorage) {
loadInfo->SetPerformanceStorage(aPerformanceStorage);
}
if (aCookieJarSettings) {
loadInfo->SetCookieJarSettings(aCookieJarSettings);
}
}
if (aLoadingNode) {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
ClassificationFlags flags =
aLoadingNode->OwnerDoc()->GetScriptTrackingFlags();
loadInfo->SetTriggeringFirstPartyClassificationFlags(flags.firstPartyFlags);
loadInfo->SetTriggeringThirdPartyClassificationFlags(flags.thirdPartyFlags);
}
channel.forget(outChannel);
return NS_OK;
}
nsresult /*NS_NewChannelWithNodeAndTriggeringPrincipal */
NS_NewChannelWithTriggeringPrincipal(
nsIChannel** outChannel, nsIURI* aUri, nsINode* aLoadingNode,
nsIPrincipal* aTriggeringPrincipal, nsSecurityFlags aSecurityFlags,
nsContentPolicyType aContentPolicyType,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */) {
MOZ_ASSERT(aLoadingNode);
NS_ASSERTION(aTriggeringPrincipal,
"Can not create channel without a triggering Principal!");
nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
// Special treatment for resources injected by add-ons if not document,
// iframe, workers.
if (!nsContentUtils::IsNonSubresourceInternalPolicyType(aContentPolicyType) &&
aTriggeringPrincipal &&
StaticPrefs::privacy_antitracking_isolateContentScriptResources() &&
nsContentUtils::IsExpandedPrincipal(aTriggeringPrincipal)) {
bool shouldResistFingerprinting =
nsContentUtils::ShouldResistFingerprinting_dangerous(
aLoadingNode->NodePrincipal(),
"CookieJarSettings can't exist yet, we're creating it",
RFPTarget::IsAlwaysEnabledForPrecompute);
cookieJarSettings = CookieJarSettings::Create(
nsICookieService::BEHAVIOR_REJECT,
StoragePrincipalHelper::PartitionKeyForExpandedPrincipal(
aTriggeringPrincipal),
OriginAttributes::IsFirstPartyEnabled(), false,
shouldResistFingerprinting);
} else {
// Let's inherit the cookie behavior and permission from the parent
// document.
cookieJarSettings = aLoadingNode->OwnerDoc()->CookieJarSettings();
}
return NS_NewChannelInternal(
outChannel, aUri, aLoadingNode, aLoadingNode->NodePrincipal(),
aTriggeringPrincipal, Maybe<ClientInfo>(),
Maybe<ServiceWorkerDescriptor>(), aSecurityFlags, aContentPolicyType,
cookieJarSettings, aPerformanceStorage, aLoadGroup, aCallbacks,
aLoadFlags, aIoService);
}
// See NS_NewChannelInternal for usage and argument description
nsresult NS_NewChannelWithTriggeringPrincipal(
nsIChannel** outChannel, nsIURI* aUri, nsIPrincipal* aLoadingPrincipal,
nsIPrincipal* aTriggeringPrincipal, nsSecurityFlags aSecurityFlags,
nsContentPolicyType aContentPolicyType,
nsICookieJarSettings* aCookieJarSettings /* = nullptr */,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */) {
NS_ASSERTION(aLoadingPrincipal,
"Can not create channel without a loading Principal!");
return NS_NewChannelInternal(
outChannel, aUri,
nullptr, // aLoadingNode
aLoadingPrincipal, aTriggeringPrincipal, Maybe<ClientInfo>(),
Maybe<ServiceWorkerDescriptor>(), aSecurityFlags, aContentPolicyType,
aCookieJarSettings, aPerformanceStorage, aLoadGroup, aCallbacks,
aLoadFlags, aIoService);
}
// See NS_NewChannelInternal for usage and argument description
nsresult NS_NewChannelWithTriggeringPrincipal(
nsIChannel** outChannel, nsIURI* aUri, nsIPrincipal* aLoadingPrincipal,
nsIPrincipal* aTriggeringPrincipal, const ClientInfo& aLoadingClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController,
nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
nsICookieJarSettings* aCookieJarSettings /* = nullptr */,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */) {
AssertLoadingPrincipalAndClientInfoMatch(
aLoadingPrincipal, aLoadingClientInfo, aContentPolicyType);
Maybe<ClientInfo> loadingClientInfo;
loadingClientInfo.emplace(aLoadingClientInfo);
return NS_NewChannelInternal(
outChannel, aUri,
nullptr, // aLoadingNode
aLoadingPrincipal, aTriggeringPrincipal, loadingClientInfo, aController,
aSecurityFlags, aContentPolicyType, aCookieJarSettings,
aPerformanceStorage, aLoadGroup, aCallbacks, aLoadFlags, aIoService);
}
nsresult NS_NewChannel(nsIChannel** outChannel, nsIURI* aUri,
nsINode* aLoadingNode, nsSecurityFlags aSecurityFlags,
nsContentPolicyType aContentPolicyType,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
nsIIOService* aIoService /* = nullptr */,
uint32_t aSandboxFlags /* = 0 */) {
NS_ASSERTION(aLoadingNode, "Can not create channel without a loading Node!");
return NS_NewChannelInternal(
outChannel, aUri, aLoadingNode, aLoadingNode->NodePrincipal(),
nullptr, // aTriggeringPrincipal
Maybe<ClientInfo>(), Maybe<ServiceWorkerDescriptor>(), aSecurityFlags,
aContentPolicyType, aLoadingNode->OwnerDoc()->CookieJarSettings(),
aPerformanceStorage, aLoadGroup, aCallbacks, aLoadFlags, aIoService,
aSandboxFlags);
}
nsresult NS_GetIsDocumentChannel(nsIChannel* aChannel, bool* aIsDocument) {
// Check if this channel is going to be used to create a document. If it has
// LOAD_DOCUMENT_URI set it is trivially creating a document. If
// LOAD_HTML_OBJECT_DATA is set it may or may not be used to create a
// document, depending on its MIME type.
if (!aChannel || !aIsDocument) {
return NS_ERROR_NULL_POINTER;
}
*aIsDocument = false;
nsLoadFlags loadFlags;
nsresult rv = aChannel->GetLoadFlags(&loadFlags);
if (NS_FAILED(rv)) {
return rv;
}
if (loadFlags & nsIChannel::LOAD_DOCUMENT_URI) {
*aIsDocument = true;
return NS_OK;
}
if (!(loadFlags & nsIRequest::LOAD_HTML_OBJECT_DATA)) {
*aIsDocument = false;
return NS_OK;
}
nsAutoCString mimeType;
rv = aChannel->GetContentType(mimeType);
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
if (nsContentUtils::HtmlObjectContentTypeForMIMEType(
mimeType, loadInfo->GetSandboxFlags()) ==
nsIObjectLoadingContent::TYPE_DOCUMENT) {
*aIsDocument = true;
return NS_OK;
}
*aIsDocument = false;
return NS_OK;
}
nsresult NS_MakeAbsoluteURI(nsACString& result, const nsACString& spec,
nsIURI* baseURI) {
nsresult rv;
if (!baseURI) {
NS_WARNING("It doesn't make sense to not supply a base URI");
result = spec;
rv = NS_OK;
} else if (spec.IsEmpty()) {
rv = baseURI->GetSpec(result);
} else {
rv = baseURI->Resolve(spec, result);
}
return rv;
}
nsresult NS_MakeAbsoluteURI(char** result, const char* spec, nsIURI* baseURI) {
nsresult rv;
nsAutoCString resultBuf;
rv = NS_MakeAbsoluteURI(resultBuf, nsDependentCString(spec), baseURI);
if (NS_SUCCEEDED(rv)) {
*result = ToNewCString(resultBuf, mozilla::fallible);
if (!*result) rv = NS_ERROR_OUT_OF_MEMORY;
}
return rv;
}
nsresult NS_MakeAbsoluteURI(nsAString& result, const nsAString& spec,
nsIURI* baseURI) {
nsresult rv;
if (!baseURI) {
NS_WARNING("It doesn't make sense to not supply a base URI");
result = spec;
rv = NS_OK;
} else {
nsAutoCString resultBuf;
if (spec.IsEmpty()) {
rv = baseURI->GetSpec(resultBuf);
} else {
rv = baseURI->Resolve(NS_ConvertUTF16toUTF8(spec), resultBuf);
}
if (NS_SUCCEEDED(rv)) CopyUTF8toUTF16(resultBuf, result);
}
return rv;
}
int32_t NS_GetDefaultPort(const char* scheme,
nsIIOService* ioService /* = nullptr */) {
nsresult rv;
// Getting the default port through the protocol handler previously had a lot
// of XPCOM overhead involved. We optimize the protocols that matter for Web
// pages (HTTP and HTTPS) by hardcoding their default ports here.
//
// XXX: This might not be necessary for performance anymore.
if (strncmp(scheme, "http", 4) == 0) {
if (scheme[4] == 's' && scheme[5] == '\0') {
return 443;
}
if (scheme[4] == '\0') {
return 80;
}
}
nsCOMPtr<nsIIOService> grip;
net_EnsureIOService(&ioService, grip);
if (!ioService) return -1;
int32_t port;
rv = ioService->GetDefaultPort(scheme, &port);
return NS_SUCCEEDED(rv) ? port : -1;
}
int32_t NS_GetRealPort(nsIURI* aURI) {
int32_t port;
nsresult rv = aURI->GetPort(&port);
if (NS_FAILED(rv)) return -1;
if (port != -1) return port; // explicitly specified
// Otherwise, we have to get the default port from the protocol handler
// Need the scheme first
nsAutoCString scheme;
rv = aURI->GetScheme(scheme);
if (NS_FAILED(rv)) return -1;
return NS_GetDefaultPort(scheme.get());
}
nsresult NS_NewInputStreamChannelInternal(
nsIChannel** outChannel, nsIURI* aUri,
already_AddRefed<nsIInputStream> aStream, const nsACString& aContentType,
const nsACString& aContentCharset, nsILoadInfo* aLoadInfo) {
nsresult rv;
nsCOMPtr<nsIInputStreamChannel> isc =
do_CreateInstance(NS_INPUTSTREAMCHANNEL_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = isc->SetURI(aUri);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIInputStream> stream = std::move(aStream);
rv = isc->SetContentStream(stream);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIChannel> channel = do_QueryInterface(isc, &rv);
NS_ENSURE_SUCCESS(rv, rv);
if (!aContentType.IsEmpty()) {
rv = channel->SetContentType(aContentType);
NS_ENSURE_SUCCESS(rv, rv);
}
if (!aContentCharset.IsEmpty()) {
rv = channel->SetContentCharset(aContentCharset);
NS_ENSURE_SUCCESS(rv, rv);
}
MOZ_ASSERT(aLoadInfo, "need a loadinfo to create a inputstreamchannel");
channel->SetLoadInfo(aLoadInfo);
// If we're sandboxed, make sure to clear any owner the channel
// might already have.
if (aLoadInfo && aLoadInfo->GetLoadingSandboxed()) {
channel->SetOwner(nullptr);
}
channel.forget(outChannel);
return NS_OK;
}
nsresult NS_NewInputStreamChannelInternal(
nsIChannel** outChannel, nsIURI* aUri,
already_AddRefed<nsIInputStream> aStream, const nsACString& aContentType,
const nsACString& aContentCharset, nsINode* aLoadingNode,
nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType) {
nsCOMPtr<nsILoadInfo> loadInfo = MOZ_TRY(
LoadInfo::Create(aLoadingPrincipal, aTriggeringPrincipal, aLoadingNode,
aSecurityFlags, aContentPolicyType));
if (!loadInfo) {
return NS_ERROR_UNEXPECTED;
}
nsCOMPtr<nsIInputStream> stream = std::move(aStream);
return NS_NewInputStreamChannelInternal(outChannel, aUri, stream.forget(),
aContentType, aContentCharset,
loadInfo);
}
nsresult NS_NewInputStreamChannel(
nsIChannel** outChannel, nsIURI* aUri,
already_AddRefed<nsIInputStream> aStream, nsIPrincipal* aLoadingPrincipal,
nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
const nsACString& aContentType /* = ""_ns */,
const nsACString& aContentCharset /* = ""_ns */) {
nsCOMPtr<nsIInputStream> stream = aStream;
return NS_NewInputStreamChannelInternal(outChannel, aUri, stream.forget(),
aContentType, aContentCharset,
nullptr, // aLoadingNode
aLoadingPrincipal,
nullptr, // aTriggeringPrincipal
aSecurityFlags, aContentPolicyType);
}
nsresult NS_NewInputStreamChannelInternal(nsIChannel** outChannel, nsIURI* aUri,
const nsAString& aData,
const nsACString& aContentType,
nsILoadInfo* aLoadInfo,
bool aIsSrcdocChannel /* = false */) {
nsresult rv;
nsCOMPtr<nsIStringInputStream> stream;
stream = do_CreateInstance(NS_STRINGINPUTSTREAM_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
uint32_t len;
char* utf8Bytes = ToNewUTF8String(aData, &len);
rv = stream->AdoptData(utf8Bytes, len);
nsCOMPtr<nsIChannel> channel;
rv = NS_NewInputStreamChannelInternal(getter_AddRefs(channel), aUri,
stream.forget(), aContentType,
"UTF-8"_ns, aLoadInfo);
NS_ENSURE_SUCCESS(rv, rv);
if (aIsSrcdocChannel) {
nsCOMPtr<nsIInputStreamChannel> inStrmChan = do_QueryInterface(channel);
NS_ENSURE_TRUE(inStrmChan, NS_ERROR_FAILURE);
inStrmChan->SetSrcdocData(aData);
}
channel.forget(outChannel);
return NS_OK;
}
nsresult NS_NewInputStreamChannelInternal(
nsIChannel** outChannel, nsIURI* aUri, const nsAString& aData,
const nsACString& aContentType, nsINode* aLoadingNode,
nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
bool aIsSrcdocChannel /* = false */) {
nsCOMPtr<nsILoadInfo> loadInfo = MOZ_TRY(
net::LoadInfo::Create(aLoadingPrincipal, aTriggeringPrincipal,
aLoadingNode, aSecurityFlags, aContentPolicyType));
return NS_NewInputStreamChannelInternal(outChannel, aUri, aData, aContentType,
loadInfo, aIsSrcdocChannel);
}
nsresult NS_NewInputStreamChannel(nsIChannel** outChannel, nsIURI* aUri,
const nsAString& aData,
const nsACString& aContentType,
nsIPrincipal* aLoadingPrincipal,
nsSecurityFlags aSecurityFlags,
nsContentPolicyType aContentPolicyType,
bool aIsSrcdocChannel /* = false */) {
return NS_NewInputStreamChannelInternal(outChannel, aUri, aData, aContentType,
nullptr, // aLoadingNode
aLoadingPrincipal,
nullptr, // aTriggeringPrincipal
aSecurityFlags, aContentPolicyType,
aIsSrcdocChannel);
}
nsresult NS_NewInputStreamPump(
nsIInputStreamPump** aResult, already_AddRefed<nsIInputStream> aStream,
uint32_t aSegsize /* = 0 */, uint32_t aSegcount /* = 0 */,
bool aCloseWhenDone /* = false */,
nsISerialEventTarget* aMainThreadTarget /* = nullptr */) {
nsCOMPtr<nsIInputStream> stream = std::move(aStream);
nsresult rv;
nsCOMPtr<nsIInputStreamPump> pump =
do_CreateInstance(NS_INPUTSTREAMPUMP_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = pump->Init(stream, aSegsize, aSegcount, aCloseWhenDone,
aMainThreadTarget);
if (NS_SUCCEEDED(rv)) {
*aResult = nullptr;
pump.swap(*aResult);
}
}
return rv;
}
nsresult NS_NewLoadGroup(nsILoadGroup** result, nsIRequestObserver* obs) {
nsresult rv;
nsCOMPtr<nsILoadGroup> group =
do_CreateInstance(NS_LOADGROUP_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = group->SetGroupObserver(obs);
if (NS_SUCCEEDED(rv)) {
*result = nullptr;
group.swap(*result);
}
}
return rv;
}
bool NS_IsReasonableHTTPHeaderValue(const nsACString& aValue) {
return mozilla::net::nsHttp::IsReasonableHeaderValue(aValue);
}
bool NS_IsValidHTTPToken(const nsACString& aToken) {
return mozilla::net::nsHttp::IsValidToken(aToken);
}
void NS_TrimHTTPWhitespace(const nsACString& aSource, nsACString& aDest) {
mozilla::net::nsHttp::TrimHTTPWhitespace(aSource, aDest);
}
nsresult NS_NewLoadGroup(nsILoadGroup** aResult, nsIPrincipal* aPrincipal) {
using mozilla::LoadContext;
nsresult rv;
nsCOMPtr<nsILoadGroup> group =
do_CreateInstance(NS_LOADGROUP_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<LoadContext> loadContext = new LoadContext(aPrincipal);
rv = group->SetNotificationCallbacks(loadContext);
NS_ENSURE_SUCCESS(rv, rv);
group.forget(aResult);
return rv;
}
bool NS_LoadGroupMatchesPrincipal(nsILoadGroup* aLoadGroup,
nsIPrincipal* aPrincipal) {
if (!aPrincipal) {
return false;
}
// If this is a null principal then the load group doesn't really matter.
// The principal will not be allowed to perform any actions that actually
// use the load group. Unconditionally treat null principals as a match.
if (aPrincipal->GetIsNullPrincipal()) {
return true;
}
if (!aLoadGroup) {
return false;
}
nsCOMPtr<nsILoadContext> loadContext;
NS_QueryNotificationCallbacks(nullptr, aLoadGroup, NS_GET_IID(nsILoadContext),
getter_AddRefs(loadContext));
NS_ENSURE_TRUE(loadContext, false);
return true;
}
nsresult NS_NewDownloader(nsIStreamListener** result,
nsIDownloadObserver* observer,
nsIFile* downloadLocation /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIDownloader> downloader =
do_CreateInstance(NS_DOWNLOADER_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = downloader->Init(observer, downloadLocation);
if (NS_SUCCEEDED(rv)) {
downloader.forget(result);
}
}
return rv;
}
nsresult NS_NewIncrementalStreamLoader(
nsIIncrementalStreamLoader** result,
nsIIncrementalStreamLoaderObserver* observer) {
nsresult rv;
nsCOMPtr<nsIIncrementalStreamLoader> loader =
do_CreateInstance(NS_INCREMENTALSTREAMLOADER_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = loader->Init(observer);
if (NS_SUCCEEDED(rv)) {
*result = nullptr;
loader.swap(*result);
}
}
return rv;
}
nsresult NS_NewStreamLoader(
nsIStreamLoader** result, nsIStreamLoaderObserver* observer,
nsIRequestObserver* requestObserver /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIStreamLoader> loader =
do_CreateInstance(NS_STREAMLOADER_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = loader->Init(observer, requestObserver);
if (NS_SUCCEEDED(rv)) {
*result = nullptr;
loader.swap(*result);
}
}
return rv;
}
nsresult NS_NewStreamLoaderInternal(
nsIStreamLoader** outStream, nsIURI* aUri,
nsIStreamLoaderObserver* aObserver, nsINode* aLoadingNode,
nsIPrincipal* aLoadingPrincipal, nsSecurityFlags aSecurityFlags,
nsContentPolicyType aContentPolicyType,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */) {
nsCOMPtr<nsIChannel> channel;
nsresult rv = NS_NewChannelInternal(
getter_AddRefs(channel), aUri, aLoadingNode, aLoadingPrincipal,
nullptr, // aTriggeringPrincipal
Maybe<ClientInfo>(), Maybe<ServiceWorkerDescriptor>(), aSecurityFlags,
aContentPolicyType,
nullptr, // nsICookieJarSettings
nullptr, // PerformanceStorage
aLoadGroup, aCallbacks, aLoadFlags);
NS_ENSURE_SUCCESS(rv, rv);
rv = NS_NewStreamLoader(outStream, aObserver);
NS_ENSURE_SUCCESS(rv, rv);
return channel->AsyncOpen(*outStream);
}
nsresult NS_NewStreamLoader(
nsIStreamLoader** outStream, nsIURI* aUri,
nsIStreamLoaderObserver* aObserver, nsINode* aLoadingNode,
nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */) {
NS_ASSERTION(aLoadingNode,
"Can not create stream loader without a loading Node!");
return NS_NewStreamLoaderInternal(
outStream, aUri, aObserver, aLoadingNode, aLoadingNode->NodePrincipal(),
aSecurityFlags, aContentPolicyType, aLoadGroup, aCallbacks, aLoadFlags);
}
nsresult NS_NewStreamLoader(
nsIStreamLoader** outStream, nsIURI* aUri,
nsIStreamLoaderObserver* aObserver, nsIPrincipal* aLoadingPrincipal,
nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
nsILoadGroup* aLoadGroup /* = nullptr */,
nsIInterfaceRequestor* aCallbacks /* = nullptr */,
nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */) {
return NS_NewStreamLoaderInternal(outStream, aUri, aObserver,
nullptr, // aLoadingNode
aLoadingPrincipal, aSecurityFlags,
aContentPolicyType, aLoadGroup, aCallbacks,
aLoadFlags);
}
nsresult NS_NewSyncStreamListener(nsIStreamListener** result,
nsIInputStream** stream) {
nsCOMPtr<nsISyncStreamListener> listener = new nsSyncStreamListener();
nsresult rv = listener->GetInputStream(stream);
if (NS_SUCCEEDED(rv)) {
listener.forget(result);
}
return rv;
}
nsresult NS_ImplementChannelOpen(nsIChannel* channel, nsIInputStream** result) {
nsCOMPtr<nsIStreamListener> listener;
nsCOMPtr<nsIInputStream> stream;
nsresult rv = NS_NewSyncStreamListener(getter_AddRefs(listener),
getter_AddRefs(stream));
NS_ENSURE_SUCCESS(rv, rv);
rv = channel->AsyncOpen(listener);
NS_ENSURE_SUCCESS(rv, rv);
uint64_t n;
// block until the initial response is received or an error occurs.
rv = stream->Available(&n);
NS_ENSURE_SUCCESS(rv, rv);
*result = nullptr;
stream.swap(*result);
return NS_OK;
}
nsresult NS_NewRequestObserverProxy(nsIRequestObserver** result,
nsIRequestObserver* observer,
nsISupports* context) {
nsCOMPtr<nsIRequestObserverProxy> proxy = new nsRequestObserverProxy();
nsresult rv = proxy->Init(observer, context);
if (NS_SUCCEEDED(rv)) {
proxy.forget(result);
}
return rv;
}
nsresult NS_NewSimpleStreamListener(
nsIStreamListener** result, nsIOutputStream* sink,
nsIRequestObserver* observer /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsISimpleStreamListener> listener =
do_CreateInstance(NS_SIMPLESTREAMLISTENER_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = listener->Init(sink, observer);
if (NS_SUCCEEDED(rv)) {
listener.forget(result);
}
}
return rv;
}
nsresult NS_CheckPortSafety(int32_t port, const char* scheme,
nsIIOService* ioService /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIIOService> grip;
rv = net_EnsureIOService(&ioService, grip);
if (ioService) {
bool allow;
rv = ioService->AllowPort(port, scheme, &allow);
if (NS_SUCCEEDED(rv) && !allow) {
NS_WARNING("port blocked");
rv = NS_ERROR_PORT_ACCESS_NOT_ALLOWED;
}
}
return rv;
}
nsresult NS_CheckPortSafety(nsIURI* uri) {
int32_t port;
nsresult rv = uri->GetPort(&port);
if (NS_FAILED(rv) || port == -1) { // port undefined or default-valued
return NS_OK;
}
nsAutoCString scheme;
uri->GetScheme(scheme);
return NS_CheckPortSafety(port, scheme.get());
}
nsresult NS_GetFileProtocolHandler(nsIFileProtocolHandler** result,
nsIIOService* ioService /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIIOService> grip;
rv = net_EnsureIOService(&ioService, grip);
if (ioService) {
nsCOMPtr<nsIProtocolHandler> handler;
rv = ioService->GetProtocolHandler("file", getter_AddRefs(handler));
if (NS_SUCCEEDED(rv)) rv = CallQueryInterface(handler, result);
}
return rv;
}
nsresult NS_GetFileFromURLSpec(const nsACString& inURL, nsIFile** result,
nsIIOService* ioService /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIFileProtocolHandler> fileHandler;
rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler), ioService);
if (NS_SUCCEEDED(rv)) rv = fileHandler->GetFileFromURLSpec(inURL, result);
return rv;
}
nsresult NS_GetURLSpecFromFile(nsIFile* file, nsACString& url,
nsIIOService* ioService /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIFileProtocolHandler> fileHandler;
rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler), ioService);
if (NS_SUCCEEDED(rv)) rv = fileHandler->GetURLSpecFromFile(file, url);
return rv;
}
nsresult NS_GetURLSpecFromActualFile(nsIFile* file, nsACString& url,
nsIIOService* ioService /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIFileProtocolHandler> fileHandler;
rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler), ioService);
if (NS_SUCCEEDED(rv)) rv = fileHandler->GetURLSpecFromActualFile(file, url);
return rv;
}
nsresult NS_GetURLSpecFromDir(nsIFile* file, nsACString& url,
nsIIOService* ioService /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIFileProtocolHandler> fileHandler;
rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler), ioService);
if (NS_SUCCEEDED(rv)) rv = fileHandler->GetURLSpecFromDir(file, url);
return rv;
}
void NS_GetReferrerFromChannel(nsIChannel* channel, nsIURI** referrer) {
*referrer = nullptr;
if (nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(channel)) {
// We have to check for a property on a property bag because the
// referrer may be empty for security reasons (for example, when loading
// an http page with an https referrer).
nsresult rv;
nsCOMPtr<nsIURI> uri(
do_GetProperty(props, u"docshell.internalReferrer"_ns, &rv));
if (NS_SUCCEEDED(rv)) {
uri.forget(referrer);
return;
}
}
// if that didn't work, we can still try to get the referrer from the
// nsIHttpChannel (if we can QI to it)
nsCOMPtr<nsIHttpChannel> chan(do_QueryInterface(channel));
if (!chan) {
return;
}
nsCOMPtr<nsIReferrerInfo> referrerInfo = chan->GetReferrerInfo();
if (!referrerInfo) {
return;
}
referrerInfo->GetOriginalReferrer(referrer);
}
already_AddRefed<nsINetUtil> do_GetNetUtil(nsresult* error /* = 0 */) {
nsCOMPtr<nsIIOService> io;
nsCOMPtr<nsINetUtil> util;
io = mozilla::components::IO::Service();
if (io) util = do_QueryInterface(io);
if (error) *error = !!util ? NS_OK : NS_ERROR_FAILURE;
return util.forget();
}
nsresult NS_ParseRequestContentType(const nsACString& rawContentType,
nsCString& contentType,
nsCString& contentCharset) {
// contentCharset is left untouched if not present in rawContentType
nsresult rv;
nsCOMPtr<nsINetUtil> util = do_GetNetUtil(&rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCString charset;
bool hadCharset;
rv = util->ParseRequestContentType(rawContentType, charset, &hadCharset,
contentType);
if (NS_SUCCEEDED(rv) && hadCharset) contentCharset = charset;
return rv;
}
nsresult NS_ParseResponseContentType(const nsACString& rawContentType,
nsCString& contentType,
nsCString& contentCharset) {
// contentCharset is left untouched if not present in rawContentType
nsresult rv;
nsCOMPtr<nsINetUtil> util = do_GetNetUtil(&rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCString charset;
bool hadCharset;
rv = util->ParseResponseContentType(rawContentType, charset, &hadCharset,
contentType);
if (NS_SUCCEEDED(rv) && hadCharset) contentCharset = charset;
return rv;
}
nsresult NS_ExtractCharsetFromContentType(const nsACString& rawContentType,
nsCString& contentCharset,
bool* hadCharset,
int32_t* charsetStart,
int32_t* charsetEnd) {
// contentCharset is left untouched if not present in rawContentType
nsresult rv;
nsCOMPtr<nsINetUtil> util = do_GetNetUtil(&rv);
NS_ENSURE_SUCCESS(rv, rv);
return util->ExtractCharsetFromContentType(
rawContentType, contentCharset, charsetStart, charsetEnd, hadCharset);
}
nsresult NS_NewAtomicFileOutputStream(nsIOutputStream** result, nsIFile* file,
int32_t ioFlags /* = -1 */,
int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsresult rv;
nsCOMPtr<nsIFileOutputStream> out =
do_CreateInstance(NS_ATOMICLOCALFILEOUTPUTSTREAM_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = out->Init(file, ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) out.forget(result);
}
return rv;
}
nsresult NS_NewSafeLocalFileOutputStream(nsIOutputStream** result,
nsIFile* file,
int32_t ioFlags /* = -1 */,
int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsresult rv;
nsCOMPtr<nsIFileOutputStream> out =
do_CreateInstance(NS_SAFELOCALFILEOUTPUTSTREAM_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = out->Init(file, ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) out.forget(result);
}
return rv;
}
nsresult NS_NewLocalFileRandomAccessStream(nsIRandomAccessStream** result,
nsIFile* file,
int32_t ioFlags /* = -1 */,
int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsCOMPtr<nsIFileRandomAccessStream> stream = new nsFileRandomAccessStream();
nsresult rv = stream->Init(file, ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) {
stream.forget(result);
}
return rv;
}
mozilla::Result<nsCOMPtr<nsIRandomAccessStream>, nsresult>
NS_NewLocalFileRandomAccessStream(nsIFile* file, int32_t ioFlags /* = -1 */,
int32_t perm /* = -1 */,
int32_t behaviorFlags /* = 0 */) {
nsCOMPtr<nsIRandomAccessStream> stream;
const nsresult rv = NS_NewLocalFileRandomAccessStream(
getter_AddRefs(stream), file, ioFlags, perm, behaviorFlags);
if (NS_SUCCEEDED(rv)) {
return stream;
}
return Err(rv);
}
nsresult NS_NewBufferedOutputStream(
nsIOutputStream** aResult, already_AddRefed<nsIOutputStream> aOutputStream,
uint32_t aBufferSize) {
nsCOMPtr<nsIOutputStream> outputStream = std::move(aOutputStream);
nsresult rv;
nsCOMPtr<nsIBufferedOutputStream> out =
do_CreateInstance(NS_BUFFEREDOUTPUTSTREAM_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = out->Init(outputStream, aBufferSize);
if (NS_SUCCEEDED(rv)) {
out.forget(aResult);
}
}
return rv;
}
[[nodiscard]] nsresult NS_NewBufferedInputStream(
nsIInputStream** aResult, already_AddRefed<nsIInputStream> aInputStream,
uint32_t aBufferSize) {
nsCOMPtr<nsIInputStream> inputStream = std::move(aInputStream);
nsCOMPtr<nsIBufferedInputStream> in;
nsresult rv = nsBufferedInputStream::Create(
NS_GET_IID(nsIBufferedInputStream), getter_AddRefs(in));
if (NS_SUCCEEDED(rv)) {
rv = in->Init(inputStream, aBufferSize);
if (NS_SUCCEEDED(rv)) {
*aResult = static_cast<nsBufferedInputStream*>(in.get())
->GetInputStream()
.take();
}
}
return rv;
}
Result<nsCOMPtr<nsIInputStream>, nsresult> NS_NewBufferedInputStream(
already_AddRefed<nsIInputStream> aInputStream, uint32_t aBufferSize) {
nsCOMPtr<nsIInputStream> stream;
const nsresult rv = NS_NewBufferedInputStream(
getter_AddRefs(stream), std::move(aInputStream), aBufferSize);
if (NS_SUCCEEDED(rv)) {
return stream;
}
return Err(rv);
}
namespace {
// Returns the buffer size from the pref, floored to the nearest power of two.
static uint32_t GetBufferSize() {
uint32_t prefValue = StaticPrefs::network_buffer_default_size();
return uint32_t(1) << FloorLog2(prefValue);
}
class BufferWriter final : public nsIInputStreamCallback {
public:
NS_DECL_THREADSAFE_ISUPPORTS
BufferWriter(nsIInputStream* aInputStream, void* aBuffer, int64_t aCount)
: mMonitor("BufferWriter.mMonitor"),
mInputStream(aInputStream),
mBuffer(aBuffer),
mCount(aCount),
mWrittenData(0),
mBufferType(aBuffer ? eExternal : eInternal),
mBufferSize(0) {
MOZ_ASSERT(aInputStream);
MOZ_ASSERT(aCount == -1 || aCount > 0);
MOZ_ASSERT_IF(mBuffer, aCount > 0);
}
nsresult Write() {
NS_ASSERT_OWNINGTHREAD(BufferWriter);
// Let's make the inputStream buffered if it's not.
if (!NS_InputStreamIsBuffered(mInputStream)) {
nsCOMPtr<nsIInputStream> bufferedStream;
nsresult rv =
NS_NewBufferedInputStream(getter_AddRefs(bufferedStream),
mInputStream.forget(), GetBufferSize());
NS_ENSURE_SUCCESS(rv, rv);
mInputStream = bufferedStream;
}
mAsyncInputStream = do_QueryInterface(mInputStream);
if (!mAsyncInputStream) {
return WriteSync();
}
// Let's use mAsyncInputStream only.
mInputStream = nullptr;
return WriteAsync();
}
uint64_t WrittenData() const {
NS_ASSERT_OWNINGTHREAD(BufferWriter);
return mWrittenData;
}
void* StealBuffer() {
NS_ASSERT_OWNINGTHREAD(BufferWriter);
MOZ_ASSERT(mBufferType == eInternal);
void* buffer = mBuffer;
mBuffer = nullptr;
mBufferSize = 0;
return buffer;
}
private:
~BufferWriter() {
if (mBuffer && mBufferType == eInternal) {
free(mBuffer);
}
if (mTaskQueue) {
mTaskQueue->BeginShutdown();
}
}
nsresult WriteSync() {
NS_ASSERT_OWNINGTHREAD(BufferWriter);
uint64_t length = (uint64_t)mCount;
if (mCount == -1) {
nsresult rv = mInputStream->Available(&length);
NS_ENSURE_SUCCESS(rv, rv);
if (length == 0) {
// nothing to read.
return NS_OK;
}
}
if (mBufferType == eInternal) {
mBuffer = malloc(length);
if (NS_WARN_IF(!mBuffer)) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
uint32_t writtenData;
nsresult rv = mInputStream->ReadSegments(NS_CopySegmentToBuffer, mBuffer,
length, &writtenData);
NS_ENSURE_SUCCESS(rv, rv);
mWrittenData = writtenData;
return NS_OK;
}
nsresult WriteAsync() {
NS_ASSERT_OWNINGTHREAD(BufferWriter);
if (mCount > 0 && mBufferType == eInternal) {
mBuffer = malloc(mCount);
if (NS_WARN_IF(!mBuffer)) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
while (true) {
if (mCount == -1 && !MaybeExpandBufferSize()) {
return NS_ERROR_OUT_OF_MEMORY;
}
uint64_t offset = mWrittenData;
uint64_t length = mCount == -1 ? GetBufferSize() : mCount;
// Let's try to read data directly.
uint32_t writtenData;
nsresult rv = mAsyncInputStream->ReadSegments(
NS_CopySegmentToBuffer, static_cast<char*>(mBuffer) + offset, length,
&writtenData);
// Operation completed. Nothing more to read.
if (NS_SUCCEEDED(rv) && writtenData == 0) {
return NS_OK;
}
// If we succeeded, let's try to read again.
if (NS_SUCCEEDED(rv)) {
mWrittenData += writtenData;
if (mCount != -1) {
MOZ_ASSERT(mCount >= writtenData);
mCount -= writtenData;
// Is this the end of the reading?
if (mCount == 0) {
return NS_OK;
}
}
continue;
}
// Async wait...
if (rv == NS_BASE_STREAM_WOULD_BLOCK) {
rv = MaybeCreateTaskQueue();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
MonitorAutoLock lock(mMonitor);
rv = mAsyncInputStream->AsyncWait(this, 0, length, mTaskQueue);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
lock.Wait();
continue;
}
// Otherwise, let's propagate the error.
return rv;
}
MOZ_ASSERT_UNREACHABLE("We should not be here");
return NS_ERROR_FAILURE;
}
nsresult MaybeCreateTaskQueue() {
NS_ASSERT_OWNINGTHREAD(BufferWriter);
if (!mTaskQueue) {
nsCOMPtr<nsIEventTarget> target;
target = mozilla::components::StreamTransport::Service();
if (!target) {
return NS_ERROR_FAILURE;
}
mTaskQueue = TaskQueue::Create(target.forget(), "nsNetUtil:BufferWriter");
}
return NS_OK;
}
NS_IMETHOD
OnInputStreamReady(nsIAsyncInputStream* aStream) override {
MOZ_ASSERT(!NS_IsMainThread());
// We have something to read. Let's unlock the main-thread.
MonitorAutoLock lock(mMonitor);
lock.Notify();
return NS_OK;
}
bool MaybeExpandBufferSize() {
NS_ASSERT_OWNINGTHREAD(BufferWriter);
MOZ_ASSERT(mCount == -1);
uint32_t bufSize = GetBufferSize();
if (mBufferSize >= mWrittenData + bufSize) {
// The buffer is big enough.
return true;
}
CheckedUint32 bufferSize =
std::max<uint32_t>(static_cast<uint32_t>(mWrittenData), bufSize);
while (bufferSize.isValid() &&
bufferSize.value() < mWrittenData + bufSize) {
bufferSize *= 2;
}
if (!bufferSize.isValid()) {
return false;
}
void* buffer = realloc(mBuffer, bufferSize.value());
if (!buffer) {
return false;
}
mBuffer = buffer;
mBufferSize = bufferSize.value();
return true;
}
// All the members of this class are touched on the owning thread only. The
// monitor is only used to communicate when there is more data to read.
Monitor mMonitor MOZ_UNANNOTATED;
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsIAsyncInputStream> mAsyncInputStream;
RefPtr<TaskQueue> mTaskQueue;
void* mBuffer;
int64_t mCount;
uint64_t mWrittenData;
enum {
// The buffer is allocated internally and this object must release it
// in the DTOR if not stolen. The buffer can be reallocated.
eInternal,
// The buffer is not owned by this object and it cannot be reallocated.
eExternal,
} mBufferType;
// The following set if needed for the async read.
uint64_t mBufferSize;
};
NS_IMPL_ISUPPORTS(BufferWriter, nsIInputStreamCallback)
} // anonymous namespace
nsresult NS_ReadInputStreamToBuffer(nsIInputStream* aInputStream, void** aDest,
int64_t aCount, uint64_t* aWritten) {
MOZ_ASSERT(aInputStream);
MOZ_ASSERT(aCount >= -1);
uint64_t dummyWritten;
if (!aWritten) {
aWritten = &dummyWritten;
}
if (aCount == 0) {
*aWritten = 0;
return NS_OK;
}
// This will take care of allocating and reallocating aDest.
RefPtr<BufferWriter> writer = new BufferWriter(aInputStream, *aDest, aCount);
nsresult rv = writer->Write();
NS_ENSURE_SUCCESS(rv, rv);
*aWritten = writer->WrittenData();
if (!*aDest) {
*aDest = writer->StealBuffer();
}
return NS_OK;
}
nsresult NS_ReadInputStreamToString(nsIInputStream* aInputStream,
nsACString& aDest, int64_t aCount,
uint64_t* aWritten) {
uint64_t dummyWritten;
if (!aWritten) {
aWritten = &dummyWritten;
}
// Nothing to do if aCount is 0.
if (aCount == 0) {
aDest.Truncate();
*aWritten = 0;
return NS_OK;
}
// If we have the size, we can pre-allocate the buffer.
if (aCount > 0) {
if (NS_WARN_IF(aCount >= INT32_MAX) ||
NS_WARN_IF(!aDest.SetLength(aCount, mozilla::fallible))) {
return NS_ERROR_OUT_OF_MEMORY;
}
void* dest = aDest.BeginWriting();
nsresult rv =
NS_ReadInputStreamToBuffer(aInputStream, &dest, aCount, aWritten);
NS_ENSURE_SUCCESS(rv, rv);
if ((uint64_t)aCount > *aWritten) {
aDest.Truncate(*aWritten);
}
return NS_OK;
}
// If the size is unknown, BufferWriter will allocate the buffer.
void* dest = nullptr;
nsresult rv =
NS_ReadInputStreamToBuffer(aInputStream, &dest, aCount, aWritten);
MOZ_ASSERT_IF(NS_FAILED(rv), dest == nullptr);
NS_ENSURE_SUCCESS(rv, rv);
if (!dest) {
MOZ_ASSERT(*aWritten == 0);
aDest.Truncate();
return NS_OK;
}
aDest.Adopt(reinterpret_cast<char*>(dest), *aWritten);
return NS_OK;
}
nsresult NS_NewURI(nsIURI** result, const nsACString& spec,
NotNull<const Encoding*> encoding,
nsIURI* baseURI /* = nullptr */) {
nsAutoCString charset;
encoding->Name(charset);
return NS_NewURI(result, spec, charset.get(), baseURI);
}
nsresult NS_NewURI(nsIURI** result, const nsAString& aSpec,
const char* charset /* = nullptr */,
nsIURI* baseURI /* = nullptr */) {
nsAutoCString spec;
if (!AppendUTF16toUTF8(aSpec, spec, mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_NewURI(result, spec, charset, baseURI);
}
nsresult NS_NewURI(nsIURI** result, const nsAString& aSpec,
NotNull<const Encoding*> encoding,
nsIURI* baseURI /* = nullptr */) {
nsAutoCString spec;
if (!AppendUTF16toUTF8(aSpec, spec, mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_NewURI(result, spec, encoding, baseURI);
}
nsresult NS_NewURI(nsIURI** result, const char* spec,
nsIURI* baseURI /* = nullptr */) {
return NS_NewURI(result, nsDependentCString(spec), nullptr, baseURI);
}
static nsresult NewStandardURI(const nsACString& aSpec, const char* aCharset,
nsIURI* aBaseURI, int32_t aDefaultPort,
nsIURI** aURI) {
return NS_MutateURI(new nsStandardURL::Mutator())
.Apply(&nsIStandardURLMutator::Init, nsIStandardURL::URLTYPE_AUTHORITY,
aDefaultPort, aSpec, aCharset, aBaseURI, nullptr)
.Finalize(aURI);
}
nsresult NS_GetSpecWithNSURLEncoding(nsACString& aResult,
const nsACString& aSpec) {
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURIWithNSURLEncoding(getter_AddRefs(uri), aSpec);
NS_ENSURE_SUCCESS(rv, rv);
return uri->GetAsciiSpec(aResult);
}
nsresult NS_NewURIWithNSURLEncoding(nsIURI** aResult, const nsACString& aSpec) {
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), aSpec);
NS_ENSURE_SUCCESS(rv, rv);
// Escape the ref portion of the URL. NSURL is more strict about which
// characters in the URL must be % encoded. For example, an unescaped '#'
// to indicate the beginning of the ref component is accepted by NSURL, but
// '#' characters in the ref must be escaped. Also adds encoding for other
// characters not accepted by NSURL in the ref such as '{', '|', '}', and '^'.
// The ref returned from GetRef() does not include the leading '#'.
nsAutoCString ref, escapedRef;
if (NS_SUCCEEDED(uri->GetRef(ref)) && !ref.IsEmpty()) {
if (!NS_Escape(ref, escapedRef, url_NSURLRef)) {
return NS_ERROR_INVALID_ARG;
}
rv = NS_MutateURI(uri).SetRef(escapedRef).Finalize(uri);
NS_ENSURE_SUCCESS(rv, rv);
}
uri.forget(aResult);
return NS_OK;
}
extern MOZ_THREAD_LOCAL(uint32_t) gTlsURLRecursionCount;
template <typename T>
class TlsAutoIncrement {
public:
explicit TlsAutoIncrement(T& var) : mVar(var) {
mValue = mVar.get();
mVar.set(mValue + 1);
}
~TlsAutoIncrement() {
typename T::Type value = mVar.get();
MOZ_ASSERT(value == mValue + 1);
mVar.set(value - 1);
}
typename T::Type value() { return mValue; }
private:
typename T::Type mValue;
T& mVar;
};
nsresult NS_NewURI(nsIURI** aURI, const nsACString& aSpec,
const char* aCharset /* = nullptr */,
nsIURI* aBaseURI /* = nullptr */) {
// we don't expect any other processes than: socket, content or parent
// to be able to create a URL
MOZ_ASSERT(XRE_IsSocketProcess() || XRE_IsContentProcess() ||
XRE_IsParentProcess());
TlsAutoIncrement<decltype(gTlsURLRecursionCount)> inc(gTlsURLRecursionCount);
if (inc.value() >= MAX_RECURSION_COUNT) {
return NS_ERROR_MALFORMED_URI;
}
nsCOMPtr<nsIIOService> ioService = do_GetIOService();
if (!ioService) {
// Individual protocol handlers unfortunately rely on the ioservice, let's
// return an error here instead of causing unpredictable crashes later.
return NS_ERROR_NOT_AVAILABLE;
}
if (StaticPrefs::network_url_max_length() &&
aSpec.Length() > StaticPrefs::network_url_max_length()) {
return NS_ERROR_MALFORMED_URI;
}
nsAutoCString scheme;
nsresult rv = net_ExtractURLScheme(aSpec, scheme);
if (NS_FAILED(rv)) {
// then aSpec is relative
if (!aBaseURI) {
return NS_ERROR_MALFORMED_URI;
}
if (!aSpec.IsEmpty() && aSpec[0] == '#') {
// Looks like a reference instead of a fully-specified URI.
// --> initialize |uri| as a clone of |aBaseURI|, with ref appended.
return NS_GetURIWithNewRef(aBaseURI, aSpec, aURI);
}
rv = aBaseURI->GetScheme(scheme);
if (NS_FAILED(rv)) return rv;
}
// If encoding is not UTF-8 and url is not special or url’s scheme is "ws" or
// "wss" then set encoding to UTF-8.
if (aCharset && !scheme.IsEmpty() &&
(scheme.EqualsLiteral("ws") || scheme.EqualsLiteral("wss") ||
!SchemeIsSpecial(scheme))) {
aCharset = "UTF-8";
}
if (scheme.EqualsLiteral("http") || scheme.EqualsLiteral("ws")) {
return NewStandardURI(aSpec, aCharset, aBaseURI, NS_HTTP_DEFAULT_PORT,
aURI);
}
if (scheme.EqualsLiteral("https") || scheme.EqualsLiteral("wss")) {
return NewStandardURI(aSpec, aCharset, aBaseURI, NS_HTTPS_DEFAULT_PORT,
aURI);
}
if (scheme.EqualsLiteral("ftp")) {
return NewStandardURI(aSpec, aCharset, aBaseURI, 21, aURI);
}
if (scheme.EqualsLiteral("file")) {
return NS_MutateURI(new nsStandardURL::Mutator())
.Apply(&nsIFileURLMutator::MarkFileURL)
.Apply(&nsIStandardURLMutator::Init,
nsIStandardURL::URLTYPE_NO_AUTHORITY, -1, aSpec, aCharset,
aBaseURI, nullptr)
.Finalize(aURI);
}
if (scheme.EqualsLiteral("data")) {
return nsDataHandler::CreateNewURI(aSpec, aCharset, aBaseURI, aURI);
}
if (scheme.EqualsLiteral("moz-safe-about") ||
scheme.EqualsLiteral("page-icon") || scheme.EqualsLiteral("moz") ||
scheme.EqualsLiteral("cached-favicon")) {
return NS_MutateURI(new nsSimpleURI::Mutator())
.SetSpec(aSpec)
.Finalize(aURI);
}
if (scheme.EqualsLiteral("chrome")) {
return nsChromeProtocolHandler::CreateNewURI(aSpec, aCharset, aBaseURI,
aURI);
}
if (scheme.EqualsLiteral("javascript")) {
return nsJSProtocolHandler::CreateNewURI(aSpec, aCharset, aBaseURI, aURI);
}
if (scheme.EqualsLiteral("blob")) {
return BlobURLProtocolHandler::CreateNewURI(aSpec, aCharset, aBaseURI,
aURI);
}
if (scheme.EqualsLiteral("view-source")) {
return nsViewSourceHandler::CreateNewURI(aSpec, aCharset, aBaseURI, aURI);
}
if (scheme.EqualsLiteral("resource")) {
RefPtr<nsResProtocolHandler> handler = nsResProtocolHandler::GetSingleton();
if (!handler) {
return NS_ERROR_NOT_AVAILABLE;
}
return handler->NewURI(aSpec, aCharset, aBaseURI, aURI);
}
if (scheme.EqualsLiteral("moz-src")) {
RefPtr<MozSrcProtocolHandler> handler =
MozSrcProtocolHandler::GetSingleton();
if (!handler) {
return NS_ERROR_NOT_AVAILABLE;
}
return handler->NewURI(aSpec, aCharset, aBaseURI, aURI);
}
if (scheme.EqualsLiteral("indexeddb") || scheme.EqualsLiteral("uuid")) {
return NS_MutateURI(new nsStandardURL::Mutator())
.Apply(&nsIStandardURLMutator::Init, nsIStandardURL::URLTYPE_AUTHORITY,
0, aSpec, aCharset, aBaseURI, nullptr)
.Finalize(aURI);
}
if (scheme.EqualsLiteral("moz-extension")) {
RefPtr<mozilla::net::ExtensionProtocolHandler> handler =
mozilla::net::ExtensionProtocolHandler::GetSingleton();
if (!handler) {
return NS_ERROR_NOT_AVAILABLE;
}
return handler->NewURI(aSpec, aCharset, aBaseURI, aURI);
}
if (scheme.EqualsLiteral("moz-page-thumb")) {
// The moz-page-thumb service runs JS to resolve a URI to a
// storage location, so this should only ever run on the main
// thread.
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_AVAILABLE;
}
RefPtr<mozilla::net::PageThumbProtocolHandler> handler =
mozilla::net::PageThumbProtocolHandler::GetSingleton();
if (!handler) {
return NS_ERROR_NOT_AVAILABLE;
}
return handler->NewURI(aSpec, aCharset, aBaseURI, aURI);
}
if (scheme.EqualsLiteral("about")) {
return nsAboutProtocolHandler::CreateNewURI(aSpec, aCharset, aBaseURI,
aURI);
}
if (scheme.EqualsLiteral("jar")) {
return NS_MutateURI(new nsJARURI::Mutator())
.Apply(&nsIJARURIMutator::SetSpecBaseCharset, aSpec, aBaseURI, aCharset)
.Finalize(aURI);
}
#ifndef XP_IOS
if (scheme.EqualsLiteral("moz-icon")) {
return NS_MutateURI(new nsMozIconURI::Mutator())
.SetSpec(aSpec)
.Finalize(aURI);
}
#endif
#ifdef MOZ_WIDGET_GTK
if (scheme.EqualsLiteral("smb") || scheme.EqualsLiteral("sftp")) {
return NS_MutateURI(new nsStandardURL::Mutator())
.Apply(&nsIStandardURLMutator::Init, nsIStandardURL::URLTYPE_STANDARD,
-1, aSpec, aCharset, aBaseURI, nullptr)
.Finalize(aURI);
}
#endif
if (scheme.EqualsLiteral("android")) {
return NS_MutateURI(NS_STANDARDURLMUTATOR_CONTRACTID)
.Apply(&nsIStandardURLMutator::Init, nsIStandardURL::URLTYPE_STANDARD,
-1, aSpec, aCharset, aBaseURI, nullptr)
.Finalize(aURI);
}
// web-extensions can add custom protocol implementations with standard URLs
// that have notion of hostname, authority and relative URLs. Below we
// manually check agains set of known protocols schemes until more general
// solution is in place (See Bug 1569733)
if (!StaticPrefs::network_url_useDefaultURI()) {
if (scheme.EqualsLiteral("ssh")) {
return NewStandardURI(aSpec, aCharset, aBaseURI, 22, aURI);
}
if (scheme.EqualsLiteral("dweb") || scheme.EqualsLiteral("dat") ||
scheme.EqualsLiteral("ipfs") || scheme.EqualsLiteral("ipns") ||
scheme.EqualsLiteral("ssb") || scheme.EqualsLiteral("wtp")) {
return NewStandardURI(aSpec, aCharset, aBaseURI, -1, aURI);
}
}
#if defined(MOZ_THUNDERBIRD) || defined(MOZ_SUITE)
rv = NS_NewMailnewsURI(aURI, aSpec, aCharset, aBaseURI);
if (rv != NS_ERROR_UNKNOWN_PROTOCOL) {
return rv;
}
#endif
auto mustUseSimpleURI = [](const nsCString& scheme) -> bool {
if (!StaticPrefs::network_url_simple_uri_unknown_schemes_enabled()) {
return false;
}
bool res = false;
RefPtr<nsIIOService> ios = do_GetIOService();
MOZ_ALWAYS_SUCCEEDS(ios->IsSimpleURIUnknownScheme(scheme, &res));
return res;
};
if (aBaseURI) {
nsAutoCString newSpec;
rv = aBaseURI->Resolve(aSpec, newSpec);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString newScheme;
rv = net_ExtractURLScheme(newSpec, newScheme);
if (NS_SUCCEEDED(rv)) {
// The scheme shouldn't really change at this point.
MOZ_DIAGNOSTIC_ASSERT(newScheme == scheme);
}
if (StaticPrefs::network_url_useDefaultURI()) {
if (mustUseSimpleURI(scheme)) {
return NS_MutateURI(new nsSimpleURI::Mutator())
.SetSpec(newSpec)
.Finalize(aURI);
}
return NS_MutateURI(new DefaultURI::Mutator())
.SetSpec(newSpec)
.Finalize(aURI);
}
return NS_MutateURI(new nsSimpleURI::Mutator())
.SetSpec(newSpec)
.Finalize(aURI);
}
if (StaticPrefs::network_url_useDefaultURI()) {
if (mustUseSimpleURI(scheme)) {
return NS_MutateURI(new nsSimpleURI::Mutator())
.SetSpec(aSpec)
.Finalize(aURI);
}
return NS_MutateURI(new DefaultURI::Mutator())
.SetSpec(aSpec)
.Finalize(aURI);
}
// Falls back to external protocol handler.
return NS_MutateURI(new nsSimpleURI::Mutator()).SetSpec(aSpec).Finalize(aURI);
}
nsresult NS_GetSanitizedURIStringFromURI(nsIURI* aUri,
nsACString& aSanitizedSpec) {
aSanitizedSpec.Truncate();
nsCOMPtr<nsISensitiveInfoHiddenURI> safeUri = do_QueryInterface(aUri);
nsAutoCString cSpec;
nsresult rv;
if (safeUri) {
rv = safeUri->GetSensitiveInfoHiddenSpec(cSpec);
} else {
rv = aUri->GetSpec(cSpec);
}
if (NS_SUCCEEDED(rv)) {
aSanitizedSpec.Assign(cSpec);
}
return rv;
}
nsresult NS_LoadPersistentPropertiesFromURISpec(
nsIPersistentProperties** outResult, const nsACString& aSpec) {
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), aSpec);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIChannel> channel;
rv = NS_NewChannel(getter_AddRefs(channel), uri,
nsContentUtils::GetSystemPrincipal(),
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
nsIContentPolicy::TYPE_OTHER);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIInputStream> in;
rv = channel->Open(getter_AddRefs(in));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIPersistentProperties> properties = new nsPersistentProperties();
rv = properties->Load(in);
NS_ENSURE_SUCCESS(rv, rv);
properties.swap(*outResult);
return NS_OK;
}
bool NS_UsePrivateBrowsing(nsIChannel* channel) {
OriginAttributes attrs;
bool result = StoragePrincipalHelper::GetOriginAttributes(
channel, attrs, StoragePrincipalHelper::eRegularPrincipal);
NS_ENSURE_TRUE(result, result);
return attrs.IsPrivateBrowsing();
}
bool NS_HasBeenCrossOrigin(nsIChannel* aChannel, bool aReport) {
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
// TYPE_DOCUMENT loads have a null LoadingPrincipal and can not be cross
// origin.
if (!loadInfo->GetLoadingPrincipal()) {
return false;
}
// Always treat tainted channels as cross-origin.
if (loadInfo->GetTainting() != LoadTainting::Basic) {
return true;
}
nsCOMPtr<nsIPrincipal> loadingPrincipal = loadInfo->GetLoadingPrincipal();
uint32_t mode = loadInfo->GetSecurityMode();
bool dataInherits =
mode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT ||
mode == nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT ||
mode == nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT;
bool aboutBlankInherits = dataInherits && loadInfo->GetAboutBlankInherits();
uint64_t innerWindowID = loadInfo->GetInnerWindowID();
for (nsIRedirectHistoryEntry* redirectHistoryEntry :
loadInfo->RedirectChain()) {
nsCOMPtr<nsIPrincipal> principal;
redirectHistoryEntry->GetPrincipal(getter_AddRefs(principal));
if (!principal) {
return true;
}
nsCOMPtr<nsIURI> uri;
auto* basePrin = BasePrincipal::Cast(principal);
basePrin->GetURI(getter_AddRefs(uri));
if (!uri) {
return true;
}
if (aboutBlankInherits && NS_IsAboutBlank(uri)) {
continue;
}
nsresult res;
if (aReport) {
res = loadingPrincipal->CheckMayLoadWithReporting(uri, dataInherits,
innerWindowID);
} else {
res = loadingPrincipal->CheckMayLoad(uri, dataInherits);
}
if (NS_FAILED(res)) {
return true;
}
}
nsCOMPtr<nsIURI> uri;
NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
if (!uri) {
return true;
}
if (aboutBlankInherits && NS_IsAboutBlank(uri)) {
return false;
}
nsresult res;
if (aReport) {
res = loadingPrincipal->CheckMayLoadWithReporting(uri, dataInherits,
innerWindowID);
} else {
res = loadingPrincipal->CheckMayLoad(uri, dataInherits);
}
return NS_FAILED(res);
}
bool NS_IsSafeMethodNav(nsIChannel* aChannel) {
RefPtr<HttpBaseChannel> baseChan = do_QueryObject(aChannel);
if (!baseChan) {
return false;
}
nsHttpRequestHead* requestHead = baseChan->GetRequestHead();
if (!requestHead) {
return false;
}
return requestHead->IsSafeMethod();
}
void NS_WrapAuthPrompt(nsIAuthPrompt* aAuthPrompt,
nsIAuthPrompt2** aAuthPrompt2) {
nsCOMPtr<nsIAuthPromptAdapterFactory> factory;
factory = mozilla::components::AuthPromptAdapter::Service();
if (!factory) return;
NS_WARNING("Using deprecated nsIAuthPrompt");
factory->CreateAdapter(aAuthPrompt, aAuthPrompt2);
}
void NS_QueryAuthPrompt2(nsIInterfaceRequestor* aCallbacks,
nsIAuthPrompt2** aAuthPrompt) {
CallGetInterface(aCallbacks, aAuthPrompt);
if (*aAuthPrompt) return;
// Maybe only nsIAuthPrompt is provided and we have to wrap it.
nsCOMPtr<nsIAuthPrompt> prompt(do_GetInterface(aCallbacks));
if (!prompt) return;
NS_WrapAuthPrompt(prompt, aAuthPrompt);
}
void NS_QueryAuthPrompt2(nsIChannel* aChannel, nsIAuthPrompt2** aAuthPrompt) {
*aAuthPrompt = nullptr;
// We want to use any auth prompt we can find on the channel's callbacks,
// and if that fails use the loadgroup's prompt (if any)
// Therefore, we can't just use NS_QueryNotificationCallbacks, because
// that would prefer a loadgroup's nsIAuthPrompt2 over a channel's
// nsIAuthPrompt.
nsCOMPtr<nsIInterfaceRequestor> callbacks;
aChannel->GetNotificationCallbacks(getter_AddRefs(callbacks));
if (callbacks) {
NS_QueryAuthPrompt2(callbacks, aAuthPrompt);
if (*aAuthPrompt) return;
}
nsCOMPtr<nsILoadGroup> group;
aChannel->GetLoadGroup(getter_AddRefs(group));
if (!group) return;
group->GetNotificationCallbacks(getter_AddRefs(callbacks));
if (!callbacks) return;
NS_QueryAuthPrompt2(callbacks, aAuthPrompt);
}
nsresult NS_NewNotificationCallbacksAggregation(
nsIInterfaceRequestor* callbacks, nsILoadGroup* loadGroup,
nsIEventTarget* target, nsIInterfaceRequestor** result) {
nsCOMPtr<nsIInterfaceRequestor> cbs;
if (loadGroup) loadGroup->GetNotificationCallbacks(getter_AddRefs(cbs));
return NS_NewInterfaceRequestorAggregation(callbacks, cbs, target, result);
}
nsresult NS_NewNotificationCallbacksAggregation(
nsIInterfaceRequestor* callbacks, nsILoadGroup* loadGroup,
nsIInterfaceRequestor** result) {
return NS_NewNotificationCallbacksAggregation(callbacks, loadGroup, nullptr,
result);
}
nsresult NS_DoImplGetInnermostURI(nsINestedURI* nestedURI, nsIURI** result) {
MOZ_ASSERT(nestedURI, "Must have a nested URI!");
MOZ_ASSERT(!*result, "Must have null *result");
nsCOMPtr<nsIURI> inner;
nsresult rv = nestedURI->GetInnerURI(getter_AddRefs(inner));
NS_ENSURE_SUCCESS(rv, rv);
// We may need to loop here until we reach the innermost
// URI.
nsCOMPtr<nsINestedURI> nestedInner(do_QueryInterface(inner));
while (nestedInner) {
rv = nestedInner->GetInnerURI(getter_AddRefs(inner));
NS_ENSURE_SUCCESS(rv, rv);
nestedInner = do_QueryInterface(inner);
}
// Found the innermost one if we reach here.
inner.swap(*result);
return rv;
}
nsresult NS_ImplGetInnermostURI(nsINestedURI* nestedURI, nsIURI** result) {
// Make it safe to use swap()
*result = nullptr;
return NS_DoImplGetInnermostURI(nestedURI, result);
}
already_AddRefed<nsIURI> NS_GetInnermostURI(nsIURI* aURI) {
MOZ_ASSERT(aURI, "Must have URI");
nsCOMPtr<nsIURI> uri = aURI;
nsCOMPtr<nsINestedURI> nestedURI(do_QueryInterface(uri));
if (!nestedURI) {
return uri.forget();
}
nsresult rv = nestedURI->GetInnermostURI(getter_AddRefs(uri));
if (NS_FAILED(rv)) {
return nullptr;
}
return uri.forget();
}
nsresult NS_GetFinalChannelURI(nsIChannel* channel, nsIURI** uri) {
*uri = nullptr;
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
nsCOMPtr<nsIURI> resultPrincipalURI;
loadInfo->GetResultPrincipalURI(getter_AddRefs(resultPrincipalURI));
if (resultPrincipalURI) {
resultPrincipalURI.forget(uri);
return NS_OK;
}
return channel->GetOriginalURI(uri);
}
nsresult NS_URIChainHasFlags(nsIURI* uri, uint32_t flags, bool* result) {
nsresult rv;
nsCOMPtr<nsINetUtil> util = do_GetNetUtil(&rv);
NS_ENSURE_SUCCESS(rv, rv);
return util->URIChainHasFlags(uri, flags, result);
}
uint32_t NS_SecurityHashURI(nsIURI* aURI) {
nsCOMPtr<nsIURI> baseURI = NS_GetInnermostURI(aURI);
nsAutoCString scheme;
uint32_t schemeHash = 0;
if (NS_SUCCEEDED(baseURI->GetScheme(scheme))) {
schemeHash = mozilla::HashString(scheme);
}
// TODO figure out how to hash file:// URIs
if (scheme.EqualsLiteral("file")) return schemeHash; // sad face
#if IS_ORIGIN_IS_FULL_SPEC_DEFINED
bool hasFlag;
if (NS_FAILED(NS_URIChainHasFlags(
baseURI, nsIProtocolHandler::ORIGIN_IS_FULL_SPEC, &hasFlag)) ||
hasFlag) {
nsAutoCString spec;
uint32_t specHash;
nsresult res = baseURI->GetSpec(spec);
if (NS_SUCCEEDED(res))
specHash = mozilla::HashString(spec);
else
specHash = static_cast<uint32_t>(res);
return specHash;
}
#endif
nsAutoCString host;
uint32_t hostHash = 0;
if (NS_SUCCEEDED(baseURI->GetAsciiHost(host))) {
hostHash = mozilla::HashString(host);
}
return mozilla::AddToHash(schemeHash, hostHash, NS_GetRealPort(baseURI));
}
bool NS_SecurityCompareURIs(nsIURI* aSourceURI, nsIURI* aTargetURI,
bool aStrictFileOriginPolicy) {
nsresult rv;
// Note that this is not an Equals() test on purpose -- for URIs that don't
// support host/port, we want equality to basically be object identity, for
// security purposes. Otherwise, for example, two javascript: URIs that
// are otherwise unrelated could end up "same origin", which would be
// unfortunate.
if (aSourceURI && aSourceURI == aTargetURI) {
return true;
}
if (!aTargetURI || !aSourceURI) {
return false;
}
// If either URI is a nested URI, get the base URI
nsCOMPtr<nsIURI> sourceBaseURI = NS_GetInnermostURI(aSourceURI);
nsCOMPtr<nsIURI> targetBaseURI = NS_GetInnermostURI(aTargetURI);
#if defined(MOZ_THUNDERBIRD) || defined(MOZ_SUITE)
// Check if either URI has a special origin.
nsCOMPtr<nsIURI> origin;
nsCOMPtr<nsIURIWithSpecialOrigin> uriWithSpecialOrigin =
do_QueryInterface(sourceBaseURI);
if (uriWithSpecialOrigin) {
rv = uriWithSpecialOrigin->GetOrigin(getter_AddRefs(origin));
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
MOZ_ASSERT(origin);
sourceBaseURI = origin;
}
uriWithSpecialOrigin = do_QueryInterface(targetBaseURI);
if (uriWithSpecialOrigin) {
rv = uriWithSpecialOrigin->GetOrigin(getter_AddRefs(origin));
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
MOZ_ASSERT(origin);
targetBaseURI = origin;
}
#endif
nsCOMPtr<nsIPrincipal> sourceBlobPrincipal;
if (BlobURLProtocolHandler::GetBlobURLPrincipal(
sourceBaseURI, getter_AddRefs(sourceBlobPrincipal))) {
nsCOMPtr<nsIURI> sourceBlobOwnerURI;
auto* basePrin = BasePrincipal::Cast(sourceBlobPrincipal);
rv = basePrin->GetURI(getter_AddRefs(sourceBlobOwnerURI));
if (NS_SUCCEEDED(rv)) {
sourceBaseURI = sourceBlobOwnerURI;
}
}
nsCOMPtr<nsIPrincipal> targetBlobPrincipal;
if (BlobURLProtocolHandler::GetBlobURLPrincipal(
targetBaseURI, getter_AddRefs(targetBlobPrincipal))) {
nsCOMPtr<nsIURI> targetBlobOwnerURI;
auto* basePrin = BasePrincipal::Cast(targetBlobPrincipal);
rv = basePrin->GetURI(getter_AddRefs(targetBlobOwnerURI));
if (NS_SUCCEEDED(rv)) {
targetBaseURI = targetBlobOwnerURI;
}
}
if (!sourceBaseURI || !targetBaseURI) return false;
// Compare schemes
nsAutoCString targetScheme;
bool sameScheme = false;
if (NS_FAILED(targetBaseURI->GetScheme(targetScheme)) ||
NS_FAILED(sourceBaseURI->SchemeIs(targetScheme.get(), &sameScheme)) ||
!sameScheme) {
// Not same-origin if schemes differ
return false;
}
// For file scheme, reject unless the files are identical.
if (targetScheme.EqualsLiteral("file")) {
// in traditional unsafe behavior all files are the same origin
if (!aStrictFileOriginPolicy) return true;
nsCOMPtr<nsIFileURL> sourceFileURL(do_QueryInterface(sourceBaseURI));
nsCOMPtr<nsIFileURL> targetFileURL(do_QueryInterface(targetBaseURI));
if (!sourceFileURL || !targetFileURL) return false;
nsCOMPtr<nsIFile> sourceFile, targetFile;
sourceFileURL->GetFile(getter_AddRefs(sourceFile));
targetFileURL->GetFile(getter_AddRefs(targetFile));
if (!sourceFile || !targetFile) return false;
// Otherwise they had better match
bool filesAreEqual = false;
rv = sourceFile->Equals(targetFile, &filesAreEqual);
return NS_SUCCEEDED(rv) && filesAreEqual;
}
#if IS_ORIGIN_IS_FULL_SPEC_DEFINED
bool hasFlag;
if (NS_FAILED(NS_URIChainHasFlags(
targetBaseURI, nsIProtocolHandler::ORIGIN_IS_FULL_SPEC, &hasFlag)) ||
hasFlag) {
// URIs with this flag have the whole spec as a distinct trust
// domain; use the whole spec for comparison
nsAutoCString targetSpec;
nsAutoCString sourceSpec;
return (NS_SUCCEEDED(targetBaseURI->GetSpec(targetSpec)) &&
NS_SUCCEEDED(sourceBaseURI->GetSpec(sourceSpec)) &&
targetSpec.Equals(sourceSpec));
}
#endif
// Compare hosts
nsAutoCString targetHost;
nsAutoCString sourceHost;
if (NS_FAILED(targetBaseURI->GetAsciiHost(targetHost)) ||
NS_FAILED(sourceBaseURI->GetAsciiHost(sourceHost))) {
return false;
}
nsCOMPtr<nsIStandardURL> targetURL(do_QueryInterface(targetBaseURI));
nsCOMPtr<nsIStandardURL> sourceURL(do_QueryInterface(sourceBaseURI));
if (!targetURL || !sourceURL) {
return false;
}
if (!targetHost.Equals(sourceHost, nsCaseInsensitiveCStringComparator)) {
return false;
}
return NS_GetRealPort(targetBaseURI) == NS_GetRealPort(sourceBaseURI);
}
bool NS_URIIsLocalFile(nsIURI* aURI) {
nsCOMPtr<nsINetUtil> util = do_GetNetUtil();
bool isFile;
return util &&
NS_SUCCEEDED(util->ProtocolHasFlags(
aURI, nsIProtocolHandler::URI_IS_LOCAL_FILE, &isFile)) &&
isFile;
}
bool NS_IsInternalSameURIRedirect(nsIChannel* aOldChannel,
nsIChannel* aNewChannel, uint32_t aFlags) {
if (!(aFlags & nsIChannelEventSink::REDIRECT_INTERNAL)) {
return false;
}
nsCOMPtr<nsIURI> oldURI, newURI;
aOldChannel->GetURI(getter_AddRefs(oldURI));
aNewChannel->GetURI(getter_AddRefs(newURI));
if (!oldURI || !newURI) {
return false;
}
bool res;
return NS_SUCCEEDED(oldURI->Equals(newURI, &res)) && res;
}
bool NS_IsHSTSUpgradeRedirect(nsIChannel* aOldChannel, nsIChannel* aNewChannel,
uint32_t aFlags) {
if (!(aFlags & nsIChannelEventSink::REDIRECT_STS_UPGRADE)) {
return false;
}
nsCOMPtr<nsIURI> oldURI, newURI;
aOldChannel->GetURI(getter_AddRefs(oldURI));
aNewChannel->GetURI(getter_AddRefs(newURI));
if (!oldURI || !newURI) {
return false;
}
if (!oldURI->SchemeIs("http")) {
return false;
}
nsCOMPtr<nsIURI> upgradedURI;
nsresult rv = NS_GetSecureUpgradedURI(oldURI, getter_AddRefs(upgradedURI));
if (NS_FAILED(rv)) {
return false;
}
bool res;
return NS_SUCCEEDED(upgradedURI->Equals(newURI, &res)) && res;
}
bool NS_ShouldRemoveAuthHeaderOnRedirect(nsIChannel* aOldChannel,
nsIChannel* aNewChannel,
uint32_t aFlags) {
// we need to strip Authentication headers for external cross-origin redirects
// Howerver, we should NOT strip auth headers for
// - internal redirects/HSTS upgrades
// - same origin redirects
// Ref: https://fetch.spec.whatwg.org/#http-redirect-fetch
if ((aFlags & (nsIChannelEventSink::REDIRECT_STS_UPGRADE |
nsIChannelEventSink::REDIRECT_INTERNAL))) {
// this is an internal redirect do not strip auth header
return false;
}
nsCOMPtr<nsIURI> oldUri;
MOZ_ALWAYS_SUCCEEDS(
NS_GetFinalChannelURI(aOldChannel, getter_AddRefs(oldUri)));
nsCOMPtr<nsIURI> newUri;
MOZ_ALWAYS_SUCCEEDS(
NS_GetFinalChannelURI(aNewChannel, getter_AddRefs(newUri)));
nsresult rv = nsContentUtils::GetSecurityManager()->CheckSameOriginURI(
newUri, oldUri, false, false);
return NS_FAILED(rv);
}
nsresult NS_LinkRedirectChannels(uint64_t channelId,
nsIParentChannel* parentChannel,
nsIChannel** _result) {
nsCOMPtr<nsIRedirectChannelRegistrar> registrar =
RedirectChannelRegistrar::GetOrCreate();
MOZ_ASSERT(registrar);
return registrar->LinkChannels(channelId, parentChannel, _result);
}
nsILoadInfo::CrossOriginEmbedderPolicy
NS_GetCrossOriginEmbedderPolicyFromHeader(
const nsACString& aHeader, bool aIsOriginTrialCoepCredentiallessEnabled) {
nsCOMPtr<nsISFVService> sfv = GetSFVService();
nsCOMPtr<nsISFVItem> item;
nsresult rv = sfv->ParseItem(aHeader, getter_AddRefs(item));
if (NS_FAILED(rv)) {
return nsILoadInfo::EMBEDDER_POLICY_NULL;
}
nsCOMPtr<nsISFVBareItem> value;
rv = item->GetValue(getter_AddRefs(value));
if (NS_FAILED(rv)) {
return nsILoadInfo::EMBEDDER_POLICY_NULL;
}
nsCOMPtr<nsISFVToken> token = do_QueryInterface(value);
if (!token) {
return nsILoadInfo::EMBEDDER_POLICY_NULL;
}
nsAutoCString embedderPolicy;
rv = token->GetValue(embedderPolicy);
if (NS_FAILED(rv)) {
return nsILoadInfo::EMBEDDER_POLICY_NULL;
}
if (embedderPolicy.EqualsLiteral("require-corp")) {
return nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP;
} else if (embedderPolicy.EqualsLiteral("credentialless") &&
IsCoepCredentiallessEnabled(
aIsOriginTrialCoepCredentiallessEnabled)) {
return nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS;
}
return nsILoadInfo::EMBEDDER_POLICY_NULL;
}
bool NS_GetForceLoadAtTopFromHeader(const nsACString& aHeader) {
nsCOMPtr<nsISFVService> sfv = mozilla::net::GetSFVService();
nsCOMPtr<nsISFVDictionary> dict;
if (NS_FAILED(sfv->ParseDictionary(aHeader, getter_AddRefs(dict)))) {
return false;
}
nsCOMPtr<nsISFVItemOrInnerList> iil;
if (NS_FAILED(dict->Get("force-load-at-top"_ns, getter_AddRefs(iil)))) {
return false;
}
nsCOMPtr<nsISFVItem> item(do_QueryInterface(iil));
if (!item) {
return false;
}
nsCOMPtr<nsISFVBareItem> bareItem;
if (NS_FAILED(item->GetValue(getter_AddRefs(bareItem)))) {
return false;
}
int32_t type;
if (NS_FAILED(bareItem->GetType(&type))) {
return false;
}
nsCOMPtr<nsISFVBool> boolItem(do_QueryInterface(bareItem));
if (!boolItem) {
return false;
}
bool b;
if (NS_FAILED(boolItem->GetValue(&b))) {
return false;
}
return b;
}
/** Given the first (disposition) token from a Content-Disposition header,
* tell whether it indicates the content is inline or attachment
* @param aDispToken the disposition token from the content-disposition header
*/
uint32_t NS_GetContentDispositionFromToken(const nsAString& aDispToken) {
// RFC 2183, section 2.8 says that an unknown disposition
// value should be treated as "attachment"
// If all of these tests eval to false, then we have a content-disposition of
// "attachment" or unknown
if (aDispToken.IsEmpty() || aDispToken.LowerCaseEqualsLiteral("inline") ||
// Broken sites just send
// Content-Disposition: filename="file"
// without a disposition token... screen those out.
StringHead(aDispToken, 8).LowerCaseEqualsLiteral("filename")) {
return nsIChannel::DISPOSITION_INLINE;
}
return nsIChannel::DISPOSITION_ATTACHMENT;
}
uint32_t NS_GetContentDispositionFromHeader(const nsACString& aHeader,
nsIChannel* aChan /* = nullptr */) {
nsresult rv;
nsCOMPtr<nsIMIMEHeaderParam> mimehdrpar;
mimehdrpar = mozilla::components::MimeHeaderParam::Service(&rv);
if (NS_FAILED(rv)) return nsIChannel::DISPOSITION_ATTACHMENT;
nsAutoString dispToken;
rv = mimehdrpar->GetParameterHTTP(aHeader, "", ""_ns, true, nullptr,
dispToken);
if (NS_FAILED(rv)) {
// special case (see bug 272541): empty disposition type handled as "inline"
if (rv == NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY) {
return nsIChannel::DISPOSITION_INLINE;
}
return nsIChannel::DISPOSITION_ATTACHMENT;
}
return NS_GetContentDispositionFromToken(dispToken);
}
nsresult NS_GetFilenameFromDisposition(nsAString& aFilename,
const nsACString& aDisposition) {
aFilename.Truncate();
nsresult rv;
nsCOMPtr<nsIMIMEHeaderParam> mimehdrpar;
mimehdrpar = mozilla::components::MimeHeaderParam::Service(&rv);
if (NS_FAILED(rv)) return rv;
// Get the value of 'filename' parameter
rv = mimehdrpar->GetParameterHTTP(aDisposition, "filename", ""_ns, true,
nullptr, aFilename);
if (NS_FAILED(rv)) {
aFilename.Truncate();
return rv;
}
if (aFilename.IsEmpty()) return NS_ERROR_NOT_AVAILABLE;
// Filename may still be percent-encoded. Fix:
if (aFilename.FindChar('%') != -1) {
nsCOMPtr<nsITextToSubURI> textToSubURI;
textToSubURI = mozilla::components::TextToSubURI::Service(&rv);
if (NS_SUCCEEDED(rv)) {
nsAutoString unescaped;
textToSubURI->UnEscapeURIForUI(NS_ConvertUTF16toUTF8(aFilename),
/* dontEscape = */ true, unescaped);
aFilename.Assign(unescaped);
}
}
return NS_OK;
}
void net_EnsurePSMInit() {
if (XRE_IsSocketProcess()) {
EnsureNSSInitializedChromeOrContent();
return;
}
MOZ_ASSERT(XRE_IsParentProcess());
MOZ_ASSERT(NS_IsMainThread());
DebugOnly<bool> rv = EnsureNSSInitializedChromeOrContent();
MOZ_ASSERT(rv);
}
bool NS_IsAboutBlank(nsIURI* uri) {
// GetSpec can be expensive for some URIs, so check the scheme first.
if (!uri->SchemeIs("about")) {
return false;
}
nsAutoCString spec;
if (NS_FAILED(uri->GetSpec(spec))) {
return false;
}
return spec.EqualsLiteral("about:blank");
}
bool NS_IsAboutBlankAllowQueryAndFragment(nsIURI* uri) {
// GetSpec can be expensive for some URIs, so check the scheme first.
if (!uri->SchemeIs("about")) {
return false;
}
nsAutoCString name;
if (NS_FAILED(NS_GetAboutModuleName(uri, name))) {
return false;
}
return name.EqualsLiteral("blank");
}
bool NS_IsAboutSrcdoc(nsIURI* uri) {
// GetSpec can be expensive for some URIs, so check the scheme first.
if (!uri->SchemeIs("about")) {
return false;
}
nsAutoCString spec;
if (NS_FAILED(uri->GetSpec(spec))) {
return false;
}
return spec.EqualsLiteral("about:srcdoc");
}
// https://fetch.spec.whatwg.org/#fetch-scheme
bool NS_IsFetchScheme(nsIURI* uri) {
for (const auto& scheme : {
"http",
"https",
"about",
"blob",
"data",
"file",
}) {
if (uri->SchemeIs(scheme)) {
return true;
}
}
return false;
}
nsresult NS_GenerateHostPort(const nsCString& host, int32_t port,
nsACString& hostLine) {
if (strchr(host.get(), ':')) {
// host is an IPv6 address literal and must be encapsulated in []'s
hostLine.Assign('[');
// scope id is not needed for Host header.
int scopeIdPos = host.FindChar('%');
if (scopeIdPos == -1) {
hostLine.Append(host);
} else if (scopeIdPos > 0) {
hostLine.Append(Substring(host, 0, scopeIdPos));
} else {
return NS_ERROR_MALFORMED_URI;
}
hostLine.Append(']');
} else {
hostLine.Assign(host);
}
if (port != -1) {
hostLine.Append(':');
hostLine.AppendInt(port);
}
return NS_OK;
}
void NS_SniffContent(const char* aSnifferType, nsIRequest* aRequest,
const uint8_t* aData, uint32_t aLength,
nsACString& aSniffedType) {
using ContentSnifferCache = nsCategoryCache<nsIContentSniffer>;
extern ContentSnifferCache* gNetSniffers;
extern ContentSnifferCache* gDataSniffers;
extern ContentSnifferCache* gORBSniffers;
extern ContentSnifferCache* gNetAndORBSniffers;
ContentSnifferCache* cache = nullptr;
if (!strcmp(aSnifferType, NS_CONTENT_SNIFFER_CATEGORY)) {
if (!gNetSniffers) {
gNetSniffers = new ContentSnifferCache(NS_CONTENT_SNIFFER_CATEGORY);
}
cache = gNetSniffers;
} else if (!strcmp(aSnifferType, NS_DATA_SNIFFER_CATEGORY)) {
if (!gDataSniffers) {
gDataSniffers = new ContentSnifferCache(NS_DATA_SNIFFER_CATEGORY);
}
cache = gDataSniffers;
} else if (!strcmp(aSnifferType, NS_ORB_SNIFFER_CATEGORY)) {
if (!gORBSniffers) {
gORBSniffers = new ContentSnifferCache(NS_ORB_SNIFFER_CATEGORY);
}
cache = gORBSniffers;
} else if (!strcmp(aSnifferType, NS_CONTENT_AND_ORB_SNIFFER_CATEGORY)) {
if (!gNetAndORBSniffers) {
gNetAndORBSniffers =
new ContentSnifferCache(NS_CONTENT_AND_ORB_SNIFFER_CATEGORY);
}
cache = gNetAndORBSniffers;
} else {
// Invalid content sniffer type was requested
MOZ_ASSERT(false);
return;
}
// In case XCTO nosniff was present, we could just skip sniffing here
nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
if (channel) {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
if (loadInfo->GetSkipContentSniffing()) {
/* Bug 1571742
* We cannot skip snffing if the current MIME-Type might be a JSON.
* The JSON-Viewer relies on its own sniffer to determine, if it can
* render the page, so we need to make an exception if the Server provides
* a application/ mime, as it might be json.
*/
nsAutoCString currentContentType;
channel->GetContentType(currentContentType);
if (!StringBeginsWith(currentContentType, "application/"_ns)) {
return;
}
}
}
nsCOMArray<nsIContentSniffer> sniffers;
cache->GetEntries(sniffers);
for (int32_t i = 0; i < sniffers.Count(); ++i) {
nsresult rv = sniffers[i]->GetMIMETypeFromContent(aRequest, aData, aLength,
aSniffedType);
if (NS_SUCCEEDED(rv) && !aSniffedType.IsEmpty()) {
return;
}
}
aSniffedType.Truncate();
}
bool NS_IsSrcdocChannel(nsIChannel* aChannel) {
bool isSrcdoc;
nsCOMPtr<nsIInputStreamChannel> isr = do_QueryInterface(aChannel);
if (isr) {
isr->GetIsSrcdocChannel(&isSrcdoc);
return isSrcdoc;
}
nsCOMPtr<nsIViewSourceChannel> vsc = do_QueryInterface(aChannel);
if (vsc) {
nsresult rv = vsc->GetIsSrcdocChannel(&isSrcdoc);
if (NS_SUCCEEDED(rv)) {
return isSrcdoc;
}
}
return false;
}
// helper function for NS_ShouldSecureUpgrade for checking HSTS
bool handleResultFunc(bool aAllowSTS, bool aIsStsHost) {
if (aIsStsHost) {
LOG(("nsHttpChannel::Connect() STS permissions found\n"));
if (aAllowSTS) {
return true;
}
}
return false;
};
// That function is a helper function of NS_ShouldSecureUpgrade to check if
// CSP upgrade-insecure-requests, Mixed content auto upgrading or HTTPs-Only/-
// First should upgrade the given request.
static bool ShouldSecureUpgradeNoHSTS(nsIURI* aURI, nsILoadInfo* aLoadInfo) {
// 2. CSP upgrade-insecure-requests
if (aLoadInfo->GetUpgradeInsecureRequests()) {
// let's log a message to the console that we are upgrading a request
nsAutoCString scheme;
aURI->GetScheme(scheme);
// append the additional 's' for security to the scheme :-)
scheme.AppendLiteral("s");
NS_ConvertUTF8toUTF16 reportSpec(aURI->GetSpecOrDefault());
NS_ConvertUTF8toUTF16 reportScheme(scheme);
AutoTArray<nsString, 2> params = {reportSpec, reportScheme};
uint64_t innerWindowId = aLoadInfo->GetInnerWindowID();
CSP_LogLocalizedStr("upgradeInsecureRequest", params,
""_ns, // aSourceFile
u""_ns, // aScriptSample
0, // aLineNumber
1, // aColumnNumber
nsIScriptError::warningFlag,
"upgradeInsecureRequest"_ns, innerWindowId,
aLoadInfo->GetOriginAttributes().IsPrivateBrowsing());
aLoadInfo->SetHttpsUpgradeTelemetry(nsILoadInfo::CSP_UIR);
return true;
}
// 3. Mixed content auto upgrading
if (aLoadInfo->GetBrowserUpgradeInsecureRequests()) {
// let's log a message to the console that we are upgrading a request
nsAutoCString scheme;
aURI->GetScheme(scheme);
// append the additional 's' for security to the scheme :-)
scheme.AppendLiteral("s");
NS_ConvertUTF8toUTF16 reportSpec(aURI->GetSpecOrDefault());
NS_ConvertUTF8toUTF16 reportScheme(scheme);
AutoTArray<nsString, 2> params = {reportSpec, reportScheme};
nsAutoString localizedMsg;
nsContentUtils::FormatLocalizedString(nsContentUtils::eSECURITY_PROPERTIES,
"MixedContentAutoUpgrade", params,
localizedMsg);
// Prepending ixed Content to the outgoing console message
nsString message;
message.AppendLiteral(u"Mixed Content: ");
message.Append(localizedMsg);
uint64_t innerWindowId = aLoadInfo->GetInnerWindowID();
nsContentUtils::ReportToConsoleByWindowID(
message, nsIScriptError::warningFlag, "Mixed Content Message"_ns,
innerWindowId, SourceLocation(aURI));
// Set this flag so we know we'll upgrade because of
// 'security.mixed_content.upgrade_display_content'.
aLoadInfo->SetBrowserDidUpgradeInsecureRequests(true);
return true;
}
// 4. Https-Only
if (nsHTTPSOnlyUtils::ShouldUpgradeRequest(aURI, aLoadInfo)) {
aLoadInfo->SetHttpsUpgradeTelemetry(nsILoadInfo::HTTPS_ONLY_UPGRADE);
return true;
}
// 4.a Https-First
if (nsHTTPSOnlyUtils::ShouldUpgradeHttpsFirstRequest(aURI, aLoadInfo)) {
if (aLoadInfo->GetSchemelessInput() ==
nsILoadInfo::SchemelessInputTypeSchemeless) {
aLoadInfo->SetHttpsUpgradeTelemetry(
nsILoadInfo::HTTPS_FIRST_SCHEMELESS_UPGRADE);
} else {
aLoadInfo->SetHttpsUpgradeTelemetry(nsILoadInfo::HTTPS_FIRST_UPGRADE);
}
return true;
}
return false;
}
// Check if channel should be upgraded. check in the following order:
// 1. HSTS
// 2. CSP upgrade-insecure-requests
// 3. Mixed content auto upgrading
// 4. Https-Only / first
// (5. Https RR - will be checked in nsHttpChannel)
nsresult NS_ShouldSecureUpgrade(
nsIURI* aURI, nsILoadInfo* aLoadInfo, nsIPrincipal* aChannelResultPrincipal,
bool aAllowSTS, const OriginAttributes& aOriginAttributes,
bool& aShouldUpgrade, std::function<void(bool, nsresult)>&& aResultCallback,
bool& aWillCallback) {
MOZ_ASSERT(XRE_IsParentProcess());
if (!XRE_IsParentProcess()) {
return NS_ERROR_NOT_AVAILABLE;
}
aWillCallback = false;
aShouldUpgrade = false;
// Even if we're in private browsing mode, we still enforce existing STS
// data (it is read-only).
// if the connection is not using SSL and either the exact host matches or
// a superdomain wants to force HTTPS, do it.
bool isHttps = aURI->SchemeIs("https");
// If request is https, then there is nothing to do here.
if (isHttps) {
aLoadInfo->SetHttpsUpgradeTelemetry(nsILoadInfo::ALREADY_HTTPS);
aShouldUpgrade = false;
return NS_OK;
}
// If it is a mixed content trustworthy loopback, then we shouldn't upgrade
// it.
if (nsMixedContentBlocker::IsPotentiallyTrustworthyLoopbackURL(aURI)) {
aShouldUpgrade = false;
return NS_OK;
}
// If no loadInfo exist there is nothing to upgrade here.
if (!aLoadInfo) {
aShouldUpgrade = false;
return NS_OK;
}
// The loadInfo indicates no HTTPS upgrade.
bool skipHTTPSUpgrade = false;
(void)aLoadInfo->GetSkipHTTPSUpgrade(&skipHTTPSUpgrade);
if (skipHTTPSUpgrade) {
aLoadInfo->SetHttpsUpgradeTelemetry(nsILoadInfo::SKIP_HTTPS_UPGRADE);
aShouldUpgrade = false;
return NS_OK;
}
MOZ_ASSERT(!aURI->SchemeIs("https"));
// enforce Strict-Transport-Security
nsISiteSecurityService* sss = gHttpHandler->GetSSService();
NS_ENSURE_TRUE(sss, NS_ERROR_OUT_OF_MEMORY);
bool isStsHost = false;
// Calling |IsSecureURI| before the storage is ready to read will
// block the main thread. Once the storage is ready, we can call it
// from main thread.
static Atomic<bool, Relaxed> storageReady(false);
if (!storageReady && gSocketTransportService && aResultCallback) {
nsCOMPtr<nsILoadInfo> loadInfo = aLoadInfo;
nsCOMPtr<nsIURI> uri = aURI;
auto callbackWrapper = [resultCallback{std::move(aResultCallback)}, uri,
loadInfo](bool aShouldUpgrade, nsresult aStatus) {
MOZ_ASSERT(NS_IsMainThread());
// 1. HSTS upgrade
if (aShouldUpgrade || NS_FAILED(aStatus)) {
resultCallback(aShouldUpgrade, aStatus);
return;
}
// Check if we need to upgrade because of other reasons.
// 2. CSP upgrade-insecure-requests
// 3. Mixed content auto upgrading
// 4. Https-Only / first
bool shouldUpgrade = ShouldSecureUpgradeNoHSTS(uri, loadInfo);
resultCallback(shouldUpgrade, aStatus);
};
nsCOMPtr<nsISiteSecurityService> service = sss;
nsresult rv = gSocketTransportService->Dispatch(
NS_NewRunnableFunction(
"net::NS_ShouldSecureUpgrade",
[service{std::move(service)}, uri{std::move(uri)},
originAttributes(aOriginAttributes),
handleResultFunc{std::move(handleResultFunc)},
callbackWrapper{std::move(callbackWrapper)},
allowSTS{std::move(aAllowSTS)}]() mutable {
bool isStsHost = false;
nsresult rv =
service->IsSecureURI(uri, originAttributes, &isStsHost);
// Successfully get the result from |IsSecureURI| implies that
// the storage is ready to read.
storageReady = NS_SUCCEEDED(rv);
bool shouldUpgrade = handleResultFunc(allowSTS, isStsHost);
// Check if request should be upgraded.
NS_DispatchToMainThread(NS_NewRunnableFunction(
"net::NS_ShouldSecureUpgrade::ResultCallback",
[rv, shouldUpgrade,
callbackWrapper{std::move(callbackWrapper)}]() {
callbackWrapper(shouldUpgrade, rv);
}));
}),
NS_DISPATCH_NORMAL);
aWillCallback = NS_SUCCEEDED(rv);
return rv;
}
nsresult rv = sss->IsSecureURI(aURI, aOriginAttributes, &isStsHost);
// if the SSS check fails, it's likely because this load is on a
// malformed URI or something else in the setup is wrong, so any error
// should be reported.
NS_ENSURE_SUCCESS(rv, rv);
aShouldUpgrade = handleResultFunc(aAllowSTS, isStsHost);
// we can't pass the loadinfo to handleResultFunc since it's not threadsafe
// hence we set the http telemetry information on the loadinfo here.
if (aShouldUpgrade) {
aLoadInfo->SetHttpsUpgradeTelemetry(nsILoadInfo::HSTS);
}
if (!aShouldUpgrade) {
// Check for CSP upgrade-insecure-requests, Mixed content auto upgrading
// and Https-Only / -First.
aShouldUpgrade = ShouldSecureUpgradeNoHSTS(aURI, aLoadInfo);
}
return rv;
}
nsresult NS_GetSecureUpgradedURI(nsIURI* aURI, nsIURI** aUpgradedURI) {
NS_MutateURI mutator(aURI);
mutator.SetScheme("https"_ns); // Change the scheme to HTTPS:
// Change the default port to 443:
nsCOMPtr<nsIStandardURL> stdURL = do_QueryInterface(aURI);
if (stdURL) {
mutator.Apply(&nsIStandardURLMutator::SetDefaultPort, 443, nullptr);
} else {
// If we don't have a nsStandardURL, fall back to using GetPort/SetPort.
// XXXdholbert Is this function even called with a non-nsStandardURL arg,
// in practice?
NS_WARNING("Calling NS_GetSecureUpgradedURI for non nsStandardURL");
int32_t oldPort = -1;
nsresult rv = aURI->GetPort(&oldPort);
if (NS_FAILED(rv)) return rv;
// Keep any nonstandard ports so only the scheme is changed.
// For example:
// http://foo.com:80 -> https://foo.com:443
// http://foo.com:81 -> https://foo.com:81
if (oldPort == 80 || oldPort == -1) {
mutator.SetPort(-1);
} else {
mutator.SetPort(oldPort);
}
}
return mutator.Finalize(aUpgradedURI);
}
nsresult NS_CompareLoadInfoAndLoadContext(nsIChannel* aChannel) {
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
nsCOMPtr<nsILoadContext> loadContext;
NS_QueryNotificationCallbacks(aChannel, loadContext);
if (!loadContext) {
return NS_OK;
}
// We try to skip about:newtab.
// about:newtab will use SystemPrincipal to download thumbnails through
// https:// and blob URLs.
bool isAboutPage = false;
nsINode* node = loadInfo->LoadingNode();
if (node) {
nsIURI* uri = node->OwnerDoc()->GetDocumentURI();
isAboutPage = uri->SchemeIs("about");
}
if (isAboutPage) {
return NS_OK;
}
// We skip the favicon loading here. The favicon loading might be
// triggered by the XUL image. For that case, the loadContext will have
// default originAttributes since the XUL image uses SystemPrincipal, but
// the loadInfo will use originAttributes from the content. Thus, the
// originAttributes between loadInfo and loadContext will be different.
// That's why we have to skip the comparison for the favicon loading.
if (loadInfo->GetLoadingPrincipal() &&
loadInfo->GetLoadingPrincipal()->IsSystemPrincipal() &&
loadInfo->InternalContentPolicyType() ==
nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON) {
return NS_OK;
}
OriginAttributes originAttrsLoadInfo = loadInfo->GetOriginAttributes();
OriginAttributes originAttrsLoadContext;
loadContext->GetOriginAttributes(originAttrsLoadContext);
LOG(
("NS_CompareLoadInfoAndLoadContext - loadInfo: %d, %d; "
"loadContext: %d, %d. [channel=%p]",
originAttrsLoadInfo.mUserContextId,
originAttrsLoadInfo.mPrivateBrowsingId,
originAttrsLoadContext.mUserContextId,
originAttrsLoadContext.mPrivateBrowsingId, aChannel));
MOZ_ASSERT(originAttrsLoadInfo.mUserContextId ==
originAttrsLoadContext.mUserContextId,
"The value of mUserContextId in the loadContext and in the "
"loadInfo are not the same!");
MOZ_ASSERT(originAttrsLoadInfo.mPrivateBrowsingId ==
originAttrsLoadContext.mPrivateBrowsingId,
"The value of mPrivateBrowsingId in the loadContext and in the "
"loadInfo are not the same!");
return NS_OK;
}
nsresult NS_SetRequestBlockingReason(nsIChannel* channel, uint32_t reason) {
NS_ENSURE_ARG(channel);
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
return NS_SetRequestBlockingReason(loadInfo, reason);
}
nsresult NS_SetRequestBlockingReason(nsILoadInfo* loadInfo, uint32_t reason) {
NS_ENSURE_ARG(loadInfo);
return loadInfo->SetRequestBlockingReason(reason);
}
nsresult NS_SetRequestBlockingReasonIfNull(nsILoadInfo* loadInfo,
uint32_t reason) {
NS_ENSURE_ARG(loadInfo);
uint32_t existingReason;
if (NS_SUCCEEDED(loadInfo->GetRequestBlockingReason(&existingReason)) &&
existingReason != nsILoadInfo::BLOCKING_REASON_NONE) {
return NS_OK;
}
return loadInfo->SetRequestBlockingReason(reason);
}
bool NS_IsOffline() {
bool offline = true;
bool connectivity = true;
nsCOMPtr<nsIIOService> ios = do_GetIOService();
if (ios) {
ios->GetOffline(&offline);
ios->GetConnectivity(&connectivity);
}
return offline || !connectivity;
}
/**
* This function returns true if this channel should be classified by
* the URL Classifier, false otherwise. There are two types of classification:
* 1. SafeBrowsing
* 2. Enhanced Tracking Protection (ETP)
*
* The idea of the algorithm to determine if a channel should be
* classified is based on:
* 1. Channels created by non-privileged code should be classified for
* ETP. For SafeBrowsing, it depends on the pref
* "browser.safebrowsing.only_top_level" to decide if it should be
* classified.
* 2. Top-level document’s channels, if loaded by privileged code
* (system principal), should be classified for both types.
* 3. Any other channel, created by privileged code, is considered safe.
*
* A bad/hacked/corrupted safebrowsing database, plus a mistakenly
* classified critical channel (this may result from a bug in the exemption
* rules or incorrect information being passed into) can cause serious
* problems. For example, if the updater channel is classified and blocked
* by the Safe Browsing, Firefox can't update itself, and there is no way to
* recover from that.
*
* So two safeguards are added to ensure critical channels are never
* automatically classified either because there is a bug in the algorithm
* or the data in loadinfo is wrong.
* 1. beConservative, this is set by ServiceRequest and we treat
* channel created for ServiceRequest as critical channels.
* 2. nsIChannel::LOAD_BYPASS_URL_CLASSIFIER, channel's opener can use this
* flag to enforce bypassing the URL classifier check.
*/
bool NS_ShouldClassifyChannel(nsIChannel* aChannel, ClassifyType aType) {
auto pref =
static_cast<ClassifierMode>(StaticPrefs::urlclassifier_enabled_mode());
if (pref == ClassifierMode::Disabled) {
return false;
}
if (aType == ClassifyType::SafeBrowsing &&
pref == ClassifierMode::AntiTracking) {
return false;
}
if (aType == ClassifyType::ETP && pref == ClassifierMode::SafeBrowsing) {
return false;
}
nsLoadFlags loadFlags;
(void)aChannel->GetLoadFlags(&loadFlags);
// If our load flags dictate that we must let this channel through without
// URL classification, obey that here without performing more checks.
if (loadFlags & nsIChannel::LOAD_BYPASS_URL_CLASSIFIER) {
return false;
}
nsCOMPtr<nsIHttpChannelInternal> httpChannel(do_QueryInterface(aChannel));
if (httpChannel) {
bool beConservative;
nsresult rv = httpChannel->GetBeConservative(&beConservative);
// beConservative flag, set by ServiceRequest to ensure channels that
// fetch update use conservative TLS setting, are used here to identify
// channels are critical to bypass classification. for channels don't
// support beConservative, continue to apply the exemption rules.
if (NS_SUCCEEDED(rv) && beConservative) {
return false;
}
}
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
ExtContentPolicyType type = loadInfo->GetExternalContentPolicyType();
// Skip classifying channel for safe browsing unless it is a top-level.
if (aType == ClassifyType::SafeBrowsing &&
(StaticPrefs::browser_safebrowsing_only_top_level() &&
ExtContentPolicy::TYPE_DOCUMENT != type)) {
return false;
}
// Skip classifying channel triggered by system unless it is a top-level
// load.
return !(loadInfo->TriggeringPrincipal()->IsSystemPrincipal() &&
ExtContentPolicy::TYPE_DOCUMENT != type);
}
namespace mozilla {
namespace net {
bool InScriptableRange(int64_t val) {
return (val <= kJS_MAX_SAFE_INTEGER) && (val >= kJS_MIN_SAFE_INTEGER);
}
bool InScriptableRange(uint64_t val) { return val <= kJS_MAX_SAFE_UINTEGER; }
nsresult GetParameterHTTP(const nsACString& aHeaderVal, const char* aParamName,
nsAString& aResult) {
return nsMIMEHeaderParamImpl::GetParameterHTTP(aHeaderVal, aParamName,
aResult);
}
bool ChannelIsPost(nsIChannel* aChannel) {
if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel)) {
nsAutoCString method;
(void)httpChannel->GetRequestMethod(method);
return method.EqualsLiteral("POST");
}
return false;
}
bool SchemeIsHttpOrHttps(nsIURI* aURI) {
MOZ_ASSERT(aURI);
return aURI->SchemeIs("http") || aURI->SchemeIs("https");
}
bool SchemeIsSpecial(const nsACString& aScheme) {
// See https://url.spec.whatwg.org/#special-scheme
return aScheme.EqualsIgnoreCase("ftp") || aScheme.EqualsIgnoreCase("file") ||
aScheme.EqualsIgnoreCase("http") ||
aScheme.EqualsIgnoreCase("https") || aScheme.EqualsIgnoreCase("ws") ||
aScheme.EqualsIgnoreCase("wss");
}
bool IsSchemeChangePermitted(nsIURI* aOldURI, const nsACString& newScheme) {
// See step 2.1 in https://url.spec.whatwg.org/#special-scheme
// Note: The spec text uses "buffer" instead of newScheme, and "url"
MOZ_ASSERT(aOldURI);
nsAutoCString tmp;
nsresult rv = aOldURI->GetScheme(tmp);
// If url's scheme is a special scheme and buffer is not a
// special scheme, then return.
// If url's scheme is not a special scheme and buffer is a
// special scheme, then return.
if (NS_FAILED(rv) || SchemeIsSpecial(tmp) != SchemeIsSpecial(newScheme)) {
return false;
}
// If url's scheme is "file" and its host is an empty host, then return.
if (aOldURI->SchemeIs("file")) {
rv = aOldURI->GetHost(tmp);
if (NS_FAILED(rv) || tmp.IsEmpty()) {
return false;
}
}
// URL Spec: If url includes credentials or has a non-null port, and
// buffer is "file", then return.
if (newScheme.EqualsIgnoreCase("file")) {
bool hasUserPass;
if (NS_FAILED(aOldURI->GetHasUserPass(&hasUserPass)) || hasUserPass) {
return false;
}
int32_t port;
rv = aOldURI->GetPort(&port);
if (NS_FAILED(rv) || port != -1) {
return false;
}
}
return true;
}
already_AddRefed<nsIURI> TryChangeProtocol(nsIURI* aURI,
const nsACString& aProtocol) {
MOZ_ASSERT(aURI);
nsACString::const_iterator start;
aProtocol.BeginReading(start);
nsACString::const_iterator end;
aProtocol.EndReading(end);
nsACString::const_iterator iter(start);
FindCharInReadable(':', iter, end);
// Changing the protocol of a URL, changes the "nature" of the URI
// implementation. In order to do this properly, we have to serialize the
// existing URL and reparse it in a new object.
nsCOMPtr<nsIURI> clone;
nsresult rv =
NS_MutateURI(aURI).SetScheme(Substring(start, iter)).Finalize(clone);
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
nsAutoCString newScheme;
rv = clone->GetScheme(newScheme);
if (NS_FAILED(rv) || !net::IsSchemeChangePermitted(aURI, newScheme)) {
nsAutoCString url;
(void)clone->GetSpec(url);
AutoTArray<nsString, 2> params;
params.AppendElement(NS_ConvertUTF8toUTF16(url));
params.AppendElement(NS_ConvertUTF8toUTF16(newScheme));
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "Strict Url Protocol Setter"_ns, nullptr,
nsContentUtils::eNECKO_PROPERTIES, "StrictUrlProtocolSetter", params);
return nullptr;
}
nsAutoCString href;
rv = clone->GetSpec(href);
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
RefPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), href);
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
return uri.forget();
}
// Decode a parameter value using the encoding defined in RFC 5987 (in place)
//
// charset "'" [ language ] "'" value-chars
//
// returns true when decoding happened successfully (otherwise leaves
// passed value alone)
static bool Decode5987Format(nsAString& aEncoded) {
nsresult rv;
nsCOMPtr<nsIMIMEHeaderParam> mimehdrpar;
mimehdrpar = mozilla::components::MimeHeaderParam::Service(&rv);
if (NS_FAILED(rv)) return false;
nsAutoCString asciiValue;
const char16_t* encstart = aEncoded.BeginReading();
const char16_t* encend = aEncoded.EndReading();
// create a plain ASCII string, aborting if we can't do that
// converted form is always shorter than input
while (encstart != encend) {
if (*encstart > 0 && *encstart < 128) {
asciiValue.Append((char)*encstart);
} else {
return false;
}
encstart++;
}
nsAutoString decoded;
nsAutoCString language;
rv = mimehdrpar->DecodeRFC5987Param(asciiValue, language, decoded);
if (NS_FAILED(rv)) return false;
aEncoded = decoded;
return true;
}
LinkHeader::LinkHeader() { mCrossOrigin.SetIsVoid(true); }
void LinkHeader::Reset() {
mHref.Truncate();
mRel.Truncate();
mTitle.Truncate();
mNonce.Truncate();
mIntegrity.Truncate();
mSrcset.Truncate();
mSizes.Truncate();
mType.Truncate();
mMedia.Truncate();
mAnchor.Truncate();
mCrossOrigin.Truncate();
mReferrerPolicy.Truncate();
mAs.Truncate();
mCrossOrigin.SetIsVoid(true);
mFetchPriority.Truncate();
}
nsresult LinkHeader::NewResolveHref(nsIURI** aOutURI, nsIURI* aBaseURI) const {
if (mAnchor.IsEmpty()) {
// use the base uri
return NS_NewURI(aOutURI, mHref, nullptr, aBaseURI);
}
// compute the anchored URI
nsCOMPtr<nsIURI> anchoredURI;
nsresult rv =
NS_NewURI(getter_AddRefs(anchoredURI), mAnchor, nullptr, aBaseURI);
NS_ENSURE_SUCCESS(rv, rv);
return NS_NewURI(aOutURI, mHref, nullptr, anchoredURI);
}
bool LinkHeader::operator==(const LinkHeader& rhs) const {
return mHref == rhs.mHref && mRel == rhs.mRel && mTitle == rhs.mTitle &&
mNonce == rhs.mNonce && mIntegrity == rhs.mIntegrity &&
mSrcset == rhs.mSrcset && mSizes == rhs.mSizes && mType == rhs.mType &&
mMedia == rhs.mMedia && mAnchor == rhs.mAnchor &&
mCrossOrigin == rhs.mCrossOrigin &&
mReferrerPolicy == rhs.mReferrerPolicy && mAs == rhs.mAs &&
mFetchPriority == rhs.mFetchPriority;
}
constexpr auto kTitleStar = "title*"_ns;
nsTArray<LinkHeader> ParseLinkHeader(const nsAString& aLinkData) {
nsTArray<LinkHeader> linkHeaders;
// keep track where we are within the header field
bool seenParameters = false;
// parse link content and add to array
LinkHeader header;
nsAutoString titleStar;
// copy to work buffer
nsAutoString stringList(aLinkData);
// put an extra null at the end
stringList.Append(kNullCh);
char16_t* start = stringList.BeginWriting();
while (*start != kNullCh) {
// parse link content and call process style link
// skip leading space
while ((*start != kNullCh) && nsCRT::IsAsciiSpace(*start)) {
++start;
}
char16_t* end = start;
char16_t* last = end - 1;
bool wasQuotedString = false;
// look for semicolon or comma
while (*end != kNullCh && *end != kSemicolon && *end != kComma) {
char16_t ch = *end;
if (ch == kQuote || ch == kLessThan) {
// quoted string
char16_t quote = ch;
if (quote == kLessThan) {
quote = kGreaterThan;
}
wasQuotedString = (ch == kQuote);
char16_t* closeQuote = (end + 1);
// seek closing quote
while (*closeQuote != kNullCh && quote != *closeQuote) {
// in quoted-string, "\" is an escape character
if (wasQuotedString && *closeQuote == kBackSlash &&
*(closeQuote + 1) != kNullCh) {
++closeQuote;
}
++closeQuote;
}
if (quote == *closeQuote) {
// found closer
// skip to close quote
end = closeQuote;
last = end - 1;
ch = *(end + 1);
if (ch != kNullCh && ch != kSemicolon && ch != kComma) {
// end string here
*(++end) = kNullCh;
ch = *(end + 1);
// keep going until semi or comma
while (ch != kNullCh && ch != kSemicolon && ch != kComma) {
++end;
ch = *(end + 1);
}
}
}
}
++end;
++last;
}
char16_t endCh = *end;
// end string here
*end = kNullCh;
if (start < end) {
if ((*start == kLessThan) && (*last == kGreaterThan)) {
*last = kNullCh;
// first instance of <...> wins
// also, do not allow hrefs after the first param was seen
if (header.mHref.IsEmpty() && !seenParameters) {
header.mHref = (start + 1);
header.mHref.StripWhitespace();
}
} else {
char16_t* equals = start;
seenParameters = true;
while ((*equals != kNullCh) && (*equals != kEqual)) {
equals++;
}
const bool hadEquals = *equals != kNullCh;
*equals = kNullCh;
nsAutoString attr(start);
attr.StripWhitespace();
char16_t* value = hadEquals ? ++equals : equals;
while (nsCRT::IsAsciiSpace(*value)) {
value++;
}
if ((*value == kQuote) && (*value == *last)) {
*last = kNullCh;
value++;
}
if (wasQuotedString) {
// unescape in-place
char16_t* unescaped = value;
char16_t* src = value;
while (*src != kNullCh) {
if (*src == kBackSlash && *(src + 1) != kNullCh) {
src++;
}
*unescaped++ = *src++;
}
*unescaped = kNullCh;
}
if (attr.LowerCaseEqualsASCII(kTitleStar.get())) {
if (titleStar.IsEmpty() && !wasQuotedString) {
// RFC 5987 encoding; uses token format only, so skip if we get
// here with a quoted-string
nsAutoString tmp;
tmp = value;
if (Decode5987Format(tmp)) {
titleStar = tmp;
titleStar.CompressWhitespace();
} else {
// header value did not parse, throw it away
titleStar.Truncate();
}
}
} else {
header.MaybeUpdateAttribute(attr, value);
}
}
}
if (endCh == kComma) {
// hit a comma, process what we've got so far
header.mHref.Trim(" \t\n\r\f"); // trim HTML5 whitespace
if (!header.mHref.IsEmpty() && !header.mRel.IsEmpty()) {
if (!titleStar.IsEmpty()) {
// prefer RFC 5987 variant over non-I18zed version
header.mTitle = titleStar;
}
linkHeaders.AppendElement(header);
}
titleStar.Truncate();
header.Reset();
seenParameters = false;
}
start = ++end;
}
header.mHref.Trim(" \t\n\r\f"); // trim HTML5 whitespace
if (!header.mHref.IsEmpty() && !header.mRel.IsEmpty()) {
if (!titleStar.IsEmpty()) {
// prefer RFC 5987 variant over non-I18zed version
header.mTitle = titleStar;
}
linkHeaders.AppendElement(header);
}
return linkHeaders;
}
void LinkHeader::MaybeUpdateAttribute(const nsAString& aAttribute,
const char16_t* aValue) {
MOZ_ASSERT(!aAttribute.LowerCaseEqualsASCII(kTitleStar.get()));
if (aAttribute.LowerCaseEqualsLiteral("rel")) {
if (mRel.IsEmpty()) {
mRel = aValue;
mRel.CompressWhitespace();
}
} else if (aAttribute.LowerCaseEqualsLiteral("title")) {
if (mTitle.IsEmpty()) {
mTitle = aValue;
mTitle.CompressWhitespace();
}
} else if (aAttribute.LowerCaseEqualsLiteral("type")) {
if (mType.IsEmpty()) {
mType = aValue;
mType.StripWhitespace();
}
} else if (aAttribute.LowerCaseEqualsLiteral("media")) {
if (mMedia.IsEmpty()) {
mMedia = aValue;
// The HTML5 spec is formulated in terms of the CSS3 spec,
// which specifies that media queries are case insensitive.
nsContentUtils::ASCIIToLower(mMedia);
}
} else if (aAttribute.LowerCaseEqualsLiteral("anchor")) {
if (mAnchor.IsEmpty()) {
mAnchor = aValue;
mAnchor.StripWhitespace();
}
} else if (aAttribute.LowerCaseEqualsLiteral("crossorigin")) {
if (mCrossOrigin.IsVoid()) {
mCrossOrigin.SetIsVoid(false);
mCrossOrigin = aValue;
mCrossOrigin.StripWhitespace();
}
} else if (aAttribute.LowerCaseEqualsLiteral("as")) {
if (mAs.IsEmpty()) {
mAs = aValue;
mAs.CompressWhitespace();
}
} else if (aAttribute.LowerCaseEqualsLiteral("referrerpolicy")) {
// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#referrer-policy-attribute
// Specs says referrer policy attribute is an enumerated attribute,
// case insensitive and includes the empty string
// We will parse the aValue with AttributeReferrerPolicyFromString
// later, which will handle parsing it as an enumerated attribute.
if (mReferrerPolicy.IsEmpty()) {
mReferrerPolicy = aValue;
}
} else if (aAttribute.LowerCaseEqualsLiteral("nonce")) {
if (mNonce.IsEmpty()) {
mNonce = aValue;
}
} else if (aAttribute.LowerCaseEqualsLiteral("integrity")) {
if (mIntegrity.IsEmpty()) {
mIntegrity = aValue;
}
} else if (aAttribute.LowerCaseEqualsLiteral("imagesrcset")) {
if (mSrcset.IsEmpty()) {
mSrcset = aValue;
}
} else if (aAttribute.LowerCaseEqualsLiteral("imagesizes")) {
if (mSizes.IsEmpty()) {
mSizes = aValue;
}
} else if (aAttribute.LowerCaseEqualsLiteral("fetchpriority")) {
if (mFetchPriority.IsEmpty()) {
LOG(("Update fetchPriority to \"%s\"",
NS_ConvertUTF16toUTF8(aValue).get()));
mFetchPriority = aValue;
}
}
}
// We will use official mime-types from:
// https://www.iana.org/assignments/media-types/media-types.xhtml#font
// We do not support old deprecated mime-types for preload feature.
// (We currectly do not support font/collection)
static uint32_t StyleLinkElementFontMimeTypesNum = 5;
static const char* StyleLinkElementFontMimeTypes[] = {
"font/otf", "font/sfnt", "font/ttf", "font/woff", "font/woff2"};
bool IsFontMimeType(const nsAString& aType) {
if (aType.IsEmpty()) {
return true;
}
for (uint32_t i = 0; i < StyleLinkElementFontMimeTypesNum; i++) {
if (aType.EqualsASCII(StyleLinkElementFontMimeTypes[i])) {
return true;
}
}
return false;
}
static constexpr nsAttrValue::EnumTableEntry kAsAttributeTable[] = {
{"", DESTINATION_INVALID}, {"audio", DESTINATION_AUDIO},
{"font", DESTINATION_FONT}, {"image", DESTINATION_IMAGE},
{"script", DESTINATION_SCRIPT}, {"style", DESTINATION_STYLE},
{"track", DESTINATION_TRACK}, {"video", DESTINATION_VIDEO},
{"fetch", DESTINATION_FETCH}, {"json", DESTINATION_JSON},
};
void ParseAsValue(const nsAString& aValue, nsAttrValue& aResult) {
DebugOnly<bool> success =
aResult.ParseEnumValue(aValue, kAsAttributeTable, false,
// default value is a empty string
// if aValue is not a value we
// understand
&kAsAttributeTable[0]);
MOZ_ASSERT(success);
}
nsContentPolicyType AsValueToContentPolicy(const nsAttrValue& aValue) {
switch (aValue.GetEnumValue()) {
case DESTINATION_INVALID:
return nsIContentPolicy::TYPE_INVALID;
case DESTINATION_AUDIO:
return nsIContentPolicy::TYPE_INTERNAL_AUDIO;
case DESTINATION_TRACK:
return nsIContentPolicy::TYPE_INTERNAL_TRACK;
case DESTINATION_VIDEO:
return nsIContentPolicy::TYPE_INTERNAL_VIDEO;
case DESTINATION_FONT:
return nsIContentPolicy::TYPE_FONT;
case DESTINATION_IMAGE:
return nsIContentPolicy::TYPE_IMAGE;
case DESTINATION_SCRIPT:
return nsIContentPolicy::TYPE_SCRIPT;
case DESTINATION_STYLE:
return nsIContentPolicy::TYPE_STYLESHEET;
case DESTINATION_FETCH:
return nsIContentPolicy::TYPE_INTERNAL_FETCH_PRELOAD;
case DESTINATION_JSON:
return nsIContentPolicy::TYPE_JSON;
}
return nsIContentPolicy::TYPE_INVALID;
}
// TODO: implement this using nsAttrValue's destination enums when support for
// the new destinations is added; see this diff for a possible start:
// https://phabricator.services.mozilla.com/D172368?vs=705114&id=708720
bool IsScriptLikeOrInvalid(const nsAString& aAs) {
return !(
aAs.LowerCaseEqualsASCII("fetch") || aAs.LowerCaseEqualsASCII("audio") ||
aAs.LowerCaseEqualsASCII("document") ||
aAs.LowerCaseEqualsASCII("embed") || aAs.LowerCaseEqualsASCII("font") ||
aAs.LowerCaseEqualsASCII("frame") || aAs.LowerCaseEqualsASCII("iframe") ||
aAs.LowerCaseEqualsASCII("image") ||
aAs.LowerCaseEqualsASCII("manifest") ||
aAs.LowerCaseEqualsASCII("object") ||
aAs.LowerCaseEqualsASCII("report") || aAs.LowerCaseEqualsASCII("style") ||
aAs.LowerCaseEqualsASCII("track") || aAs.LowerCaseEqualsASCII("video") ||
aAs.LowerCaseEqualsASCII("webidentity") ||
aAs.LowerCaseEqualsASCII("xslt") || aAs.LowerCaseEqualsASCII("json"));
}
bool CheckPreloadAttrs(const nsAttrValue& aAs, const nsAString& aType,
const nsAString& aMedia,
mozilla::dom::Document* aDocument) {
nsContentPolicyType policyType = AsValueToContentPolicy(aAs);
if (policyType == nsIContentPolicy::TYPE_INVALID) {
return false;
}
// Check if media attribute is valid.
if (!aMedia.IsEmpty()) {
RefPtr<mozilla::dom::MediaList> mediaList =
mozilla::dom::MediaList::Create(NS_ConvertUTF16toUTF8(aMedia));
if (!mediaList->Matches(*aDocument)) {
return false;
}
}
if (aType.IsEmpty()) {
return true;
}
if (policyType == nsIContentPolicy::TYPE_INTERNAL_FETCH_PRELOAD) {
return true;
}
nsAutoString type(aType);
ToLowerCase(type);
if (policyType == nsIContentPolicy::TYPE_MEDIA) {
if (aAs.GetEnumValue() == DESTINATION_TRACK) {
return type.EqualsASCII("text/vtt");
}
Maybe<MediaContainerType> mimeType = MakeMediaContainerType(aType);
if (!mimeType) {
return false;
}
DecoderDoctorDiagnostics diagnostics;
CanPlayStatus status =
DecoderTraits::CanHandleContainerType(*mimeType, &diagnostics);
// Preload if this return CANPLAY_YES and CANPLAY_MAYBE.
return status != CANPLAY_NO;
}
if (policyType == nsIContentPolicy::TYPE_FONT) {
return IsFontMimeType(type);
}
if (policyType == nsIContentPolicy::TYPE_IMAGE) {
return imgLoader::SupportImageWithMimeType(
NS_ConvertUTF16toUTF8(type), AcceptedMimeTypes::IMAGES_AND_DOCUMENTS);
}
if (policyType == nsIContentPolicy::TYPE_SCRIPT) {
return nsContentUtils::IsJavascriptMIMEType(type);
}
if (policyType == nsIContentPolicy::TYPE_STYLESHEET) {
return type.EqualsASCII("text/css");
}
if (policyType == nsIContentPolicy::TYPE_JSON) {
return nsContentUtils::IsJsonMimeType(type);
}
return false;
}
void WarnIgnoredPreload(const mozilla::dom::Document& aDoc, nsIURI& aURI) {
AutoTArray<nsString, 1> params;
{
nsCString uri = nsContentUtils::TruncatedURLForDisplay(&aURI);
AppendUTF8toUTF16(uri, *params.AppendElement());
}
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, &aDoc,
nsContentUtils::eDOM_PROPERTIES,
"PreloadIgnoredInvalidAttr", params);
}
bool NS_ParseUseAsDictionary(const nsACString& aValue, nsACString& aMatch,
nsACString& aMatchId,
nsTArray<nsCString>& aMatchDestItems,
nsACString& aType) {
// Note: match= is required
// Use-As-Dictionary = %s"match" /
// %il"match-dest" /
// %s"id" /
// %t"type" ; case-sensitive
nsCOMPtr<nsISFVService> sfv = GetSFVService();
nsCOMPtr<nsISFVDictionary> parsedHeader;
nsresult rv;
if (NS_FAILED(
rv = sfv->ParseDictionary(aValue, getter_AddRefs(parsedHeader)))) {
return false;
}
nsCOMPtr<nsISFVItemOrInnerList> match;
rv = parsedHeader->Get("match"_ns, getter_AddRefs(match));
if (NS_FAILED(rv)) {
return false; // match is required, fail if not found
}
if (nsCOMPtr<nsISFVItem> listItem = do_QueryInterface(match)) {
nsCOMPtr<nsISFVBareItem> value;
rv = listItem->GetValue(getter_AddRefs(value));
if (NS_FAILED(rv)) {
return false;
}
if (nsCOMPtr<nsISFVString> stringVal = do_QueryInterface(value)) {
if (NS_FAILED(stringVal->GetValue(aMatch))) {
return false;
}
if (aMatch.IsEmpty()) {
return false; // match is required, fail if not found
}
} else {
return false;
}
} else {
return false;
}
nsCOMPtr<nsISFVItemOrInnerList> matchdest;
rv = parsedHeader->Get("match-dest"_ns, getter_AddRefs(matchdest));
if (NS_SUCCEEDED(rv)) {
if (nsCOMPtr<nsISFVInnerList> innerList = do_QueryInterface(matchdest)) {
// Extract the first entry of each inner list, which should contain the
// endpoint's URL string
nsTArray<RefPtr<nsISFVItem>> items;
if (NS_FAILED(innerList->GetItems(items))) {
return false;
}
// Don't check items.IsEmpty() because an empty list is valid
for (auto& item : items) {
nsCOMPtr<nsISFVBareItem> value;
if (NS_FAILED(item->GetValue(getter_AddRefs(value)))) {
return false;
}
if (nsCOMPtr<nsISFVString> stringVal = do_QueryInterface(value)) {
nsAutoCString string;
if (NS_FAILED(stringVal->GetValue(string))) {
return false;
}
aMatchDestItems.AppendElement(string);
} else {
return false; // match-dest is an inner list of strings
}
}
}
}
nsCOMPtr<nsISFVItemOrInnerList> matchid;
rv = parsedHeader->Get("id"_ns, getter_AddRefs(matchid));
if (NS_SUCCEEDED(rv)) {
if (nsCOMPtr<nsISFVItem> listItem = do_QueryInterface(matchid)) {
nsCOMPtr<nsISFVBareItem> value;
rv = listItem->GetValue(getter_AddRefs(value));
if (NS_FAILED(rv)) {
return false;
}
if (nsCOMPtr<nsISFVString> stringVal = do_QueryInterface(value)) {
if (NS_FAILED(stringVal->GetValue(aMatchId))) {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
nsCOMPtr<nsISFVItemOrInnerList> type;
rv = parsedHeader->Get("type"_ns, getter_AddRefs(type));
if (NS_SUCCEEDED(rv)) {
if (nsCOMPtr<nsISFVItem> listItem = do_QueryInterface(type)) {
nsCOMPtr<nsISFVBareItem> value;
rv = listItem->GetValue(getter_AddRefs(value));
if (NS_FAILED(rv)) {
return false;
}
if (nsCOMPtr<nsISFVToken> tokenVal = do_QueryInterface(value)) {
if (NS_FAILED(tokenVal->GetValue(aType))) {
return false;
}
if (!aType.Equals("raw"_ns)) {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
return true;
}
nsresult HasRootDomain(const nsACString& aInput, const nsACString& aHost,
bool* aResult) {
if (NS_WARN_IF(!aResult)) {
return NS_ERROR_FAILURE;
}
*aResult = false;
// If the strings are the same, we obviously have a match.
if (aInput == aHost) {
*aResult = true;
return NS_OK;
}
// If aHost is not found, we know we do not have it as a root domain.
int32_t index = nsAutoCString(aInput).Find(aHost);
if (index == kNotFound) {
return NS_OK;
}
// Otherwise, we have aHost as our root domain iff the index of aHost is
// aHost.length subtracted from our length and (since we do not have an
// exact match) the character before the index is a dot or slash.
*aResult = index > 0 && (uint32_t)index == aInput.Length() - aHost.Length() &&
(aInput[index - 1] == '.' || aInput[index - 1] == '/');
return NS_OK;
}
void CheckForBrokenChromeURL(nsILoadInfo* aLoadInfo, nsIURI* aURI) {
if (!aURI) {
return;
}
nsAutoCString scheme;
aURI->GetScheme(scheme);
if (!scheme.EqualsLiteral("chrome") && !scheme.EqualsLiteral("resource")) {
return;
}
nsAutoCString host;
aURI->GetHost(host);
// Ignore test hits.
if (host.EqualsLiteral("mochitests") || host.EqualsLiteral("reftest")) {
return;
}
nsAutoCString filePath;
aURI->GetFilePath(filePath);
// Fluent likes checking for files everywhere and expects failure.
if (StringEndsWith(filePath, ".ftl"_ns)) {
return;
}
// Ignore fetches/xhrs, as they are frequently used in a way where
// non-existence is OK (ie with fallbacks). This risks false negatives (ie
// files that *should* be there but aren't) - which we accept for now.
ExtContentPolicy policy = aLoadInfo
? aLoadInfo->GetExternalContentPolicyType()
: ExtContentPolicy::TYPE_OTHER;
if (policy == ExtContentPolicy::TYPE_FETCH ||
policy == ExtContentPolicy::TYPE_XMLHTTPREQUEST) {
return;
}
nsCString spec;
aURI->GetSpec(spec);
#ifdef ANDROID
// Various toolkit files use this and are shipped on android, but
// info-pages.css and aboutLicense.css are not - bug 1808987
if (StringEndsWith(spec, "info-pages.css"_ns) ||
StringEndsWith(spec, "aboutLicense.css"_ns) ||
// Error page CSS is also missing: bug 1810039
StringEndsWith(spec, "aboutNetError.css"_ns) ||
StringEndsWith(spec, "aboutHttpsOnlyError.css"_ns) ||
StringEndsWith(spec, "error-pages.css"_ns) ||
// popup.css is used in a single mochitest: bug 1810577
StringEndsWith(spec, "/popup.css"_ns) ||
// Used by an extension installation test - bug 1809650
StringBeginsWith(spec, "resource://android/assets/web_extensions/"_ns)) {
return;
}
#endif
// DTD files from gre may not exist when requested by tests.
if (StringBeginsWith(spec, "resource://gre/res/dtd/"_ns)) {
return;
}
// The background task machinery allows the caller to specify a JSM on the
// command line, which is then looked up in both app-specific and toolkit-wide
// locations.
if (spec.Find("backgroundtasks") != kNotFound) {
return;
}
if (xpc::IsInAutomation()) {
#ifdef DEBUG
if (NS_IsMainThread()) {
nsCOMPtr<nsIXPConnect> xpc = nsIXPConnect::XPConnect();
(void)xpc->DebugDumpJSStack(false, false, false);
}
#endif
MOZ_CRASH_UNSAFE_PRINTF("Missing chrome or resource URLs: %s", spec.get());
} else {
printf_stderr("Missing chrome or resource URL: %s\n", spec.get());
}
}
bool IsCoepCredentiallessEnabled(bool aIsOriginTrialCoepCredentiallessEnabled) {
return StaticPrefs::
browser_tabs_remote_coep_credentialless_DoNotUseDirectly() ||
aIsOriginTrialCoepCredentiallessEnabled;
}
nsresult AddExtraHeaders(nsIHttpChannel* aHttpChannel,
const nsACString& aExtraHeaders,
bool aMerge /* = true */) {
nsresult rv;
nsAutoCString oneHeader;
nsAutoCString headerName;
nsAutoCString headerValue;
int32_t crlf = 0;
int32_t colon = 0;
const char* kWhitespace = "\b\t\r\n ";
nsAutoCString extraHeaders(aExtraHeaders);
while (true) {
crlf = extraHeaders.Find("\r\n");
if (crlf == -1) break;
extraHeaders.Mid(oneHeader, 0, crlf);
extraHeaders.Cut(0, crlf + 2);
colon = oneHeader.Find(":");
if (colon == -1) break; // Should have a colon.
oneHeader.Left(headerName, colon);
colon++;
oneHeader.Mid(headerValue, colon, oneHeader.Length() - colon);
headerName.Trim(kWhitespace);
headerValue.Trim(kWhitespace);
// Add the header (merging if required).
rv = aHttpChannel->SetRequestHeader(headerName, headerValue, aMerge);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
bool IsLocalHostAccess(
const nsILoadInfo::IPAddressSpace aParentIPAddressSpace,
const nsILoadInfo::IPAddressSpace aTargetIPAddressSpace) {
// Determine if the request is moving to a more private address space
// i.e. Public -> LocalHost
// Private -> LocalHost
return ((aTargetIPAddressSpace == nsILoadInfo::IPAddressSpace::Local) &&
(aParentIPAddressSpace == nsILoadInfo::IPAddressSpace::Public ||
aParentIPAddressSpace == nsILoadInfo::IPAddressSpace::Private));
}
bool IsPrivateNetworkAccess(
const nsILoadInfo::IPAddressSpace aParentIPAddressSpace,
const nsILoadInfo::IPAddressSpace aTargetIPAddressSpace) {
// Determine if the request is moving from public to private address space
return ((aTargetIPAddressSpace == nsILoadInfo::IPAddressSpace::Private) &&
(aParentIPAddressSpace == nsILoadInfo::IPAddressSpace::Public));
}
bool IsLocalOrPrivateNetworkAccess(
const nsILoadInfo::IPAddressSpace aParentIPAddressSpace,
const nsILoadInfo::IPAddressSpace aTargetIPAddressSpace) {
// Determine if the request is moving to a more private address space
// i.e. Public -> Private or Local
// Private -> Local
// Refer
// https://wicg.github.io/private-network-access/#private-network-request-heading
// for private network access
// XXX (sunil) add link to LNA spec once it is published
return IsPrivateNetworkAccess(aParentIPAddressSpace, aTargetIPAddressSpace) ||
IsLocalHostAccess(aParentIPAddressSpace, aTargetIPAddressSpace);
}
Result<ActivateStorageAccess, nsresult> ParseActivateStorageAccess(
const nsACString& aActivateStorageAcess) {
nsCOMPtr<nsISFVService> sfv = GetSFVService();
// Parse storage acces values
// * Activate-Storage-Access: load
// * Activate-Storage-Access: retry; allowed-origin="https://foo.bar"
// * Activate-Storage-Access: retry; allowed-origin=*
// into ActivateStorageAccess struct. See ActivateStorageAccessVariant for
// documentation on fields
nsCOMPtr<nsISFVItem> parsedHeader;
MOZ_TRY(sfv->ParseItem(aActivateStorageAcess, getter_AddRefs(parsedHeader)));
nsCOMPtr<nsISFVBareItem> value;
MOZ_TRY(parsedHeader->GetValue(getter_AddRefs(value)));
nsCOMPtr<nsISFVToken> token = do_QueryInterface(value);
if (!token) {
return Err(NS_ERROR_FAILURE);
}
nsAutoCString tokenValue;
token->GetValue(tokenValue);
if (tokenValue.EqualsLiteral("load")) {
return ActivateStorageAccess{
ActivateStorageAccessVariant::Load,
};
}
if (!tokenValue.EqualsLiteral("retry")) {
return Err(NS_ERROR_FAILURE);
}
nsCOMPtr<nsISFVParams> params;
MOZ_TRY(parsedHeader->GetParams(getter_AddRefs(params)));
nsCOMPtr<nsISFVBareItem> item;
MOZ_TRY(params->Get("allowed-origin"_ns, getter_AddRefs(item)));
// Evaluate whether the token value is a wildcard symbol.
nsCOMPtr<nsISFVToken> itemToken = do_QueryInterface(item);
if (itemToken) {
itemToken->GetValue(tokenValue);
if (!tokenValue.EqualsLiteral("*")) {
return Err(NS_ERROR_FAILURE);
}
return ActivateStorageAccess{
ActivateStorageAccessVariant::RetryAny,
};
}
// Evaluate whether the token value is an origin.
nsCOMPtr<nsISFVString> itemString = do_QueryInterface(item);
if (!itemString) {
return Err(NS_ERROR_FAILURE);
}
ActivateStorageAccess result{ActivateStorageAccessVariant::RetryOrigin};
itemString->GetValue(result.origin);
return result;
}
} // namespace net
} // namespace mozilla
|